Home Backend Development PHP Tutorial An example of PHP reconstruction and optimization - application of template method pattern_PHP tutorial

An example of PHP reconstruction and optimization - application of template method pattern_PHP tutorial

Jul 13, 2016 pm 05:48 PM
php optimization exist application method model template experience Refactor project

Recently optimized the php project, recorded the experience, and started working directly. . .

PHP is mainly used for page display in company projects. There is a view on the front end, and the view requests data from the back-end service. The data transmission format is json. Let’s look at the service code before optimization:

[php]
require_once('../../../global.php'); 
require_once(INCLUDE_PATH . '/discache/CacherManager.php'); 
require_once(INCLUDE_PATH.'/oracle_oci.php'); 
require_once(INCLUDE_PATH.'/caihui/cwsd.php'); 
header('Content-type: text/plain; charset=utf-8'); 
$max_age = isset($_GET['max-age']) ? $_GET['max-age']*1 : 15*60; 
if($max_age < 30) { 
    $max_age = 30; 

header('Cache-Control: max-age='.$max_age); 
// 通过将url进行hash作为缓冲key 
$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; 
$url_hash = md5($url); 
//echo "/finance/hs/marketdata/segment/${url_hash}.json"; 
if (!CacherManager::cachePageStart(CACHER_MONGO, "/finance/hs/marketdata/segment/${url_hash}.json", 60*60)) { 
 
// 查询条件 
$page = isset($_GET['page']) ? $_GET['page']*1 : 0; 
$count = isset($_GET['count']) ? $_GET['count']*1 : 30; 
$type = isset($_GET['type']) ? $_GET['type'] : 'query'; 
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'symbol'; 
$order = isset($_GET['order']) ? $_GET['order'] : 'desc'; 
$callback = isset($_GET['callback']) ? $_GET['callback'] : null; 
$fieldsstring = isset($_GET['fields']) ? $_GET['fields'] : null; 
$querystring = isset($_GET['query']) ? $_GET['query'] : null; 
$symbol=isset($_GET['symbol'])?$_GET['symbol']:''; 
$date=isset($_GET['date'])?$_GET['date']:''; 
 
if ($type == 'query') { 
    $queryObj = preg_split('/:|;/', $querystring, -1); 
    for($i=0; $i         if(emptyempty($queryObj[$i])) continue; 
        if($queryObj[$i]=='symbol'){ 
            $symbol = $queryObj[$i+1]; 
        } 
        if($queryObj[$i]=='date'){ 
            $date = $queryObj[$i+1]; 
        } 
    } 
}  
 
// 查询列表 
$oci = ntes_get_caihui_oci(); 
$stocklist = array(); 
$cwsd = new namespacedaocaihuiCwsd($oci); 
                       
$stockcurror = $cwsd->getCznlList($symbol,$date,$sort,$order,$count*($page),$count); 
$sumrecords=$cwsd->getRecordCount($symbol,$date); 
$i=0; 
//var_dump($symbol,$date,$sort,$order,$count*($page),$count); 
foreach($stockcurror as $item){ 
    $item['RSMFRATIO1422']=isset($item['RSMFRATIO1422'])?number_format($item['RSMFRATIO1422'],2).'%':'--'; 
    $item['RSMFRATIO1822']=isset($item['RSMFRATIO1822'])?number_format($item['RSMFRATIO1822'],2).'%':'--'; 
    $item['RSMFRATIO22']=isset($item['RSMFRATIO22'])?number_format($item['RSMFRATIO22'],2).'%':'--'; 
     
    $item['RSMFRATIO10']=isset($item['RSMFRATIO10'])?number_format($item['RSMFRATIO10'],2):'--'; 
    $item['RSMFRATIO12']=isset($item['RSMFRATIO12'])?number_format($item['RSMFRATIO12'],2):'--'; 
    $item['RSMFRATIO4']=isset($item['RSMFRATIO4'])?number_format($item['RSMFRATIO4'],2):'--'; 
    $item['RSMFRATIO18']=isset($item['RSMFRATIO18'])?number_format($item['RSMFRATIO18'],2):'--'; 
    $item['RSMFRATIO14']=isset($item['RSMFRATIO14'])?number_format($item['RSMFRATIO14'],2):'--'; 
 
    $item['CODE']=$item['EXCHANGE'].$item['SYMBOL']; 
//$item['REPORTDATE']=isset($item['REPORTDATE'])?$item['REPORTDATE']:'--';
$stocklist[$i] = $item;
$i=$i+1;
}


// Output results
$result = array();
//Page number, count per page, total number of results, pagecount, result list
$result['page'] = $page;
$result['count'] = $count;
$result['order'] = $order;
$result['total'] = $i;//$stockcurror->count();
$result['pagecount'] = ceil($sumrecords['SUMRECORD']/$count);
$result['time'] = date('Y-m-d H:i:s');
$result['list'] = $stocklist;
if(emptyempty($callback)){
echo json_encode($result);
}else{
echo $callback.'('.json_encode($result).');';
}

CacherManager::cachePageEnd();
}
?>
Let's take a look at the specific completion of this service:

1. Lines 6-16, prepare cache parameters and enable caching.
​​​​ 2. Lines 19-41, extract request parameters.
​​​​ 3. Lines 44-49, connect and query the database.
​ ​ 4. Lines 50-67, put the database query results into the array.
​ ​ 5. Lines 71-84, prepare json data.
​ ​ 6. Lines 86-87, turn off caching.

If you only look at this file, the problems are:
​ ​ 1. Lines 19-86, no indentation.
​ ​​ 2. Line 44, the database will be reconnected with each request.
​​​​ 3. Lines 53-61, the repeated logic can be extracted as a function and then completed through iteration.
If most back-end services adopt this structure, then the problem is that all services need to go through a series of processes: opening cache, getting parameters, getting data, json conversion, and closing cache. In all processes, except for the logic of obtaining data, other processes are the same. There is a lot of repetitive logic in the code, which even gives people a "copy-paste" feeling, which seriously violates the DRY principle (Don't Repeat Yourself). Therefore, it needs to be reconstructed using object-oriented thinking. In the process of my reconstruction, I always kept one principle in mind - the principle of encapsulation change. The so-called encapsulation of changes is to distinguish between the constant and the variable in the system, and to encapsulate the variable, so that changes can be easily dealt with.
Through the above analysis, only the logic of obtaining data changes, and other logic remains unchanged. Therefore, the logic of obtaining data needs to be encapsulated. The specific encapsulation method can be inheritance or combination. I adopt the inheritance method. First, I abstract the service processing process as:
       service(){
                 startCache();
                     getParam();
                      getData(); // Abstract method, implemented by subclasses
                 toJson();
Closecache ();
}
                                                                                                                                   ServiceBase class is abstracted and inherited by subclasses to implement the corresponding logic of obtaining data. Subclasses do not need to deal with other logic such as parameter fetching and caching, as these are all handled by the ServiceBase class.
[php]
abstract class ServiceBase {                                     Public function __construct($cache_path, $cache_type, $max_age, $age_explore) {
// Get request parameters
          $this->page = $this->getQueryParamDefault('page', 0, INT);
                    // Omit other logic for obtaining parameters
       …                                                                    
               // Generate response
$this->response();
}  

/**
* *
* Subclass implementation, returns data in array format
​​*/
abstract protected function data();

/**
* *
* Subclass implementation, returns the total number of all data
​​*/
abstract protected function total();

private function cache() {
$url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$url_hash = md5($url);
$key = $this->cache_path.$url_hash.'.json';
If(!CacherManager::cachePageStart($this->cache_type, $key, $this->age_cache)){
$this->no_cache();
​​​​​CacherManager::cachePageEnd();
         } 
}  

private function no_cache(){
$data = $this->data();
$total = $this->total();
           $this->send_data($data, $total);
}  

Private function send_data($data, $total){
// Convert json, omit specific code
}  

private function response() {
header('Content-type: text/plain; charset=utf-8');
header('Cache-Control: max-age='.$this->age_explore);
If($this->cache_type == NONE || self::$enable_cache == false){
$this->no_cache();
         }else{
                $this->cache();
         } 
}  
}
This is the abstract parent class of each service. There are two abstract methods data and total. Data returns data in array format. Tatol is added due to paging. A specific service only needs to inherit ServiceBase and implement the data and total methods, and other logic is reused from the parent class. In fact, the optimized ServiceBase uses the template method pattern (Template Method). The parent class defines the algorithm processing process (the processing process of the service), and the subclass implements the steps of a specific change (the logic of obtaining data for the specific service). . By using the template method pattern, you can ensure that step changes are transparent to the client, and the logic in the parent class can be reused.

The following is the code of the above php using ServiceBase:

[php]
class CWSDService extends ServiceBase{ 
    function __construct(){ 
        parent::__construct(); 
        $oci = ntes_get_caihui_oci(); 
        $this->$cwsd = new namespacedaocaihuiCwsd($oci); 
    } 
    public function data(){ 
        $stocklist = array(); 
        $stockcurror = $this->cwsd->getCznlList($this->query_obj['symbol'],  
            $this->query_obj['symbol'], $sort, $order, $count*($page), $count); 
        $filter_list = array('RSMFRATIO1422', 'RSMFRATIO1822', 'RSMFRATIO22', 
            'RSMFRATIO10', 'RSMFRATIO12', 'RSMFRATIO4', 'RSMFRATIO18', 
            'RSMFRATIO14'); 
        $i=0; 
        foreach($stockcurror as $item){ 
            foreach($filter_list as $k) 
                $this->filter($item, $k); 
            $item['CODE']=$item['EXCHANGE'].$item['SYMBOL']; 
            $stocklist[$i] = $item; 
            $i=$i+1; 
        } 
        return $stocklist; 
    } 
    public function total(){ 
        return $sumrecords=$this->cwsd->getRecordCount($this->query_obj['symbol'],  
            $this->query_obj['symbol']); 
    } 
    private function filter($item, $k){ 
        isset($item[$k])?number_format($item[$k],2).'%':'--'; 
    } 

new CWSDService('/finance/hs/realtimedata/market/ab', MONGO, 30, 30); 
 代码量从87减少到32行,是因为大部分的逻辑都由父类完成,具体service只需要关注自己的业务逻辑就可以了。通过上面代码可以看出继承可以实现代码复用,多个子类中的相同的逻辑可以提取到父类中达到复用的目的;同时,继承也增加了父类和子类之间的耦合性,这也就是组合由于继承的方面,如果这个例子采用组合来封装变化,则具体的实现就是策略模式,将具体获取数据的逻辑看成是策略,不同的service就是不同的策略,由于时间原因,不再赘述。。。

摘自 chosen0ne的专栏
 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/478442.htmlTechArticle最近优化php项目,记录下经验,直接上干活。。。 php在公司项目中主要用于页面展现,前端有个view,view向后端的service请求数据,数据的传...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles