Home >Backend Development >PHP Tutorial >PHP aspect-oriented programming components_PHP tutorial

PHP aspect-oriented programming components_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:47:111123browse

We use MVC frameworks, such as CI, YII, cakePHP, one of the reasons is: it can make the code easy to maintain.

But as the business logic continues to become more complex, calling methods in the model in the controller will become more and more cumbersome.

The idea of ​​aspect-oriented programming is one of the solutions to solve the changing business logic and write easy-to-maintain code.


The following is the source code of the aspect-oriented component, which is designed based on the idea of ​​​​AOP.

if (function_exists('__autoload')) { 
    trigger_error("Extension: It looks like your code is using an __autoload() function. Extension uses spl_autoload_register() which will bypass your __autoload() function and may break autoloading.", E_USER_WARNING); 

 
spl_autoload_register(array('ExtensionFactory', 'autoload')); 
 
class ExtensionFactory { 
     
    private static $extFamily = null; 
    private static $_classes = array( 
        'Extension' =>  '/Extension.php', 
        'ExtensionFamily' =>  '/ExtensionFamily.php' 
    ); 
     
    /**
     * Class autoloader. This method is provided to be invoked within an 
     * __autoload() magic method.
     * @param string $className The name of the class to load.
    */ 
    public static function autoload() { 
        foreach(self::$_classes as $v){ 
            require_once dirname(__FILE__) . $v; 
        } 
    } 
     
    /**
* This method must be called first to instantiate the extension family before calling addExtensionremoveExtension, etc.
* @return ExtensionFamily
​​*/ 
    public static function createExtension(){ 
        self::$extFamily = new ExtensionFamily(); 
        return self::$extFamily; 
    } 
     
    public static function removeExtension($extName){ 
        if(is_null(self::$extFamily)){ 
            throw new Exception("Please createExtension first"); 
            return false; 
        }else{ 
            unset(self::$extFamily->_extensionArray[$extName]); 
        } 
    } 
     
    public static function addExtension($extName, Extension $ext){ 
        if(is_null(self::$extFamily)){ 
            throw new Exception("Please createExtension first"); 
            return false; 
        }else{ 
            self::$extFamily->_extensionArray[$extName] = $ext; 
        } 
    } 
     
    public static function removeAllExtension(){ 
        if(is_null(self::$extFamily)){ 
            throw new Exception("Please createExtension first"); 
            return false; 
        }else{ 
            foreach(self::$extFamily->_extensionArray as $extName=>$ext){ 
                unset(self::$extFamily->_extensionArray[$extName]); 
            } 
        } 
    } 

if (function_exists('__autoload')) {
 trigger_error("Extension: It looks like your code is using an __autoload() function. Extension uses spl_autoload_register() which will bypass your __autoload() function and may break autoloading.", E_USER_WARNING);
}

spl_autoload_register(array('ExtensionFactory', 'autoload'));

class ExtensionFactory {
   
    private static $extFamily = null;
    private static $_classes = array(
        'Extension' =>  '/Extension.php',
        'ExtensionFamily' =>  '/ExtensionFamily.php'
    );
   
    /**
     * Class autoloader. This method is provided to be invoked within an
     * __autoload() magic method.
     * @param string $className The name of the class to load.
    */
    public static function autoload() {
        foreach(self::$_classes as $v){
            require_once dirname(__FILE__) . $v;
        }
    }
   
    /**
* This method must be called first to instantiate the extension family before calling addExtensionremoveExtension, etc.
* @return ExtensionFamily
​​*/
    public static function createExtension(){
        self::$extFamily = new ExtensionFamily();
        return self::$extFamily;
    }
   
    public static function removeExtension($extName){
        if(is_null(self::$extFamily)){
            throw new Exception("Please createExtension first");
            return false;
        }else{
            unset(self::$extFamily->_extensionArray[$extName]);
        }
    }
   
    public static function addExtension($extName, Extension $ext){
        if(is_null(self::$extFamily)){
            throw new Exception("Please createExtension first");
            return false;
        }else{
            self::$extFamily->_extensionArray[$extName] = $ext;
        }
    }
   
    public static function removeAllExtension(){
        if(is_null(self::$extFamily)){
            throw new Exception("Please createExtension first");
            return false;
        }else{
            foreach(self::$extFamily->_extensionArray as $extName=>$ext){
                unset(self::$extFamily->_extensionArray[$extName]);
            }
        }
    }
}

 


/**
* Extended family
*
* @author Mr.Jin
​*/ 
class ExtensionFamily implements Extension{ 
    public $_extensionArray = array(); 
     
    /**
*
* @param type $extName extension
* @param Extension $ext The object that implements Extension
​​*/ 
    public function addExtension($extName, Extension $ext){ 
        $this->_extensionArray[$extName] = $ext; 
    } 
     
    public function beforeAppend(&$params){ 
        foreach($this->_extensionArray as $ext){ 
            $ext->beforeAppend($params); 
        } 
    } 
     
    public function afterAppend(&$params) { 
        foreach($this->_extensionArray as $ext){ 
            $ext->afterAppend($params); 
        } 
    } 

 
?> 
/**
* Extended family
*
* @author Mr.Jin
​*/
class ExtensionFamily implements Extension{
    public $_extensionArray = array();
   
    /**
*
* @param type $extName extension
* @param Extension $ext The object that implements Extension
​​*/
    public function addExtension($extName, Extension $ext){
        $this->_extensionArray[$extName] = $ext;
    }
   
    public function beforeAppend(&$params){
        foreach($this->_extensionArray as $ext){
            $ext->beforeAppend($params);
        }
    }
   
    public function afterAppend(&$params) {
        foreach($this->_extensionArray as $ext){
            $ext->afterAppend($params);
        }
    }
}

?>

/**
*Extended interface
*
* @author Mr.Jin
​*/ 
interface Extension { 
    public function beforeAppend(&$params); 
     
    public function afterAppend(&$params); 

 
?> 
/**
*Extended interface
*
* @author Mr.Jin
​*/
interface Extension {
    public function beforeAppend(&$params);
   
    public function afterAppend(&$params);
}

?>

以上三个文件实现了简单的AOP组件。

 

下面是Demo:

/**
* Custom Extension
* User Points Extension
* Depending on whether the user is logged in or not, determine whether user points will be recorded for this consumption
*
* @author Mr.Jin
​*/ 
class ExampleExtension implements Extension { 
    public $check=false; 
     
    public function beforeAppend(&$isLogin) { 
        if($isLogin){ 
            $this->check = true; 
        } 
    } 
     
    public function afterAppend(&$pointer) { 
        if($this->check){ 
            //add pointer  
        }else{ 
            echo '未登录用户,积分不录入'; 
            return; 
        } 
    } 
 

 
?> 
/**
* Custom Extension
* User Points Extension
* Depending on whether the user is logged in or not, determine whether user points will be recorded for this consumption
*
* @author Mr.Jin
​*/
class ExampleExtension implements Extension {
 public $check=false;
   
    public function beforeAppend(&$isLogin) {
        if($isLogin){
         $this->check = true;
        }
    }
   
    public function afterAppend(&$pointer) {
        if($this->check){
         //add pointer
        }else{
         echo '未登录用户,积分不录入';
         return;
        }
    }

}

?>

 


demo.php
require_once('ExtensionFactory.php');//导入组件本身  
 
require_once('ExampleExtension.php');//导入扩展  
 
$ext = ExtensionFactory::createExtension(); 
 
ExtensionFactory::addExtension('example', new ExampleExtension());//积分录入功能  
 
/*
 * 按照需求的变化,可以增加相应的Extension.
 * eg.
 * 新需求:新增会员类型,根据不同类型,进行价格优惠。
 * 实现思路:
 * 一、建立卡号类型工厂
 * 二、建立SeniorMemberExtension、PuTongMeberExtension.
 * 三、工厂方法根据会员类型addExtension
 */ 
 
$isLogin = false; //假设用户未登录  
 
$ext->beforeAppend($isLogin); 
 
 
/**
* The most important point in aspect-oriented programming is that you must first analyze which part of the entire business process is the focus.
* The focus here is the warehousing of orders.
* Before the order is put into the warehouse, business logic may continue to increase, such as: login verification, card balance verification, etc.
* After the order is put into storage: points processing, order monitoring, etc.
​*/ 
echo "此处是主要业务逻辑:订单入库rn"; 
 
$pointer = 100; 
 
$ext->afterAppend($pointer); 
require_once('ExtensionFactory.php');//导入组件本身

require_once('ExampleExtension.php');//导入扩展

$ext = ExtensionFactory::createExtension();

ExtensionFactory::addExtension('example', new ExampleExtension());//积分录入功能

/*
* According to the changes in demand, the corresponding Extension can be added.
*eg.
* New requirements: Add new membership types, and provide price discounts according to different types.
* Implementation ideas:
* 1. Establish card number type factory
* 2. Create SeniorMemberExtension and PuTongMeberExtension.
* 3. Factory method addExtension
based on member type */

$isLogin = false; //Assume the user is not logged in

$ext->beforeAppend($isLogin);


/**
* The most important point in aspect-oriented programming is that you must first analyze which part of the entire business process is the focus.
* The focus here is the warehousing of orders.
* Before the order is put into the warehouse, business logic may continue to increase, such as: login verification, card balance verification, etc.
* After the order is put into storage: points processing, order monitoring, etc.
​*/
echo "Here is the main business logic: order storage rn";

$pointer = 100;

$ext->afterAppend($pointer);
Running result:
Here is the main business logic: Order warehousing
For users who are not logged in, points will not be recorded

Excerpted from God's blog

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478518.htmlTechArticleWe use MVC frameworks, such as CI, YII, cakePHP, one of the reasons is: it can make the code easy to maintain. But as the business logic continues to become more complex, calling methods in the model in the controller will become more...
Statement:
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