AOP實踐:
YII2框架自己擁有一個功能,叫作行爲.它能夠動態的爲當前的類附加額外的功能,但這種功能在代碼層級結構是靜態的,有侵入性的。
下面以YII2框架集成go!aop庫爲例,介紹在YII2中如何實現AOP編程.(go!aop簡介,能夠參考go!aop的官網.)
因爲YII框架擁有本身的類加載器,所在集成go!aop的時候,不能正常的工做,因此要將其禁用掉,使用composer提供的類加載器。
以下代碼所示(這裏使用YII2高級應用模板):
一、找到 spl_autoload_register(['Yii', 'autoload'], true, true); (PROJECT_PATH/vendor/yiisoft/yii2/Yii.php) 將其禁用掉.php
二、執行 composer require goaop/frameworkhtml
三、修改composer.json文件,加入以下代碼段:編程
"autoload": { "psr-4": { "backend\\": "backend//", "frontend\\": "frontend//", "common\\": "common//" } }
四、 在frontend 目錄下建立一個components是目錄,並新建一個類AopAspectKernel,例如:json
namespace frontend\components; use frontend\aspects\MonitorAspect; use Go\Core\AspectContainer; use Go\Core\AspectKernel; class AopAspectKernel extends AspectKernel { protected function configureAop(AspectContainer $container) { $container->registerAspect(new MonitorAspect()); } }
五、在forntend目錄下在新建一個類InitAopComponent,並使其實現BootstrapInterface,使其能夠在YII2框架引導時被自動引導 bootstrap
namespace frontend\components; use yii\base\BootstrapInterface; class InitAopComponent implements BootstrapInterface { public function bootstrap($app) { print_r(\Yii::$app->params['aop']); $applicationAspectKernel = AopAspectKernel::getInstance(); $applicationAspectKernel->init(\Yii::$app->params['aop']); } }
六、在frontend/config/params.php中新增以下代碼:數組
'aop' => [ 'debug' => true, 'appDir' => dirname(__DIR__), 'cacheDir' => dirname(__DIR__) . '/runtime/aop', 'includePaths' => [ dirname(__DIR__) ] ]
七、在frontend下面新建aspects目錄,並新建類MonitorAspect,代碼以下:yii2
namespace frontend\aspects; use Go\Aop\Aspect; use Go\Aop\Intercept\MethodInvocation; use Go\Lang\Annotation\Before; class MonitorAspect implements Aspect { /** * Method that will be called before real method * * @param MethodInvocation $invocation Invocation * @Before("execution(public frontend\components\AopTestComponent->*(*))") */ public function beforeMethodExecution(MethodInvocation $invocation) { $obj = $invocation->getThis(); echo 'Calling Before Interceptor for method: ', is_object($obj) ? get_class($obj) : $obj, $invocation->getMethod()->isStatic() ? '::' : '->', $invocation->getMethod()->getName(), '()', ' with arguments: ', json_encode($invocation->getArguments()), "<br>\n"; } }
八、修改frontend/config/main.php文件,並在components數組下新增一個key,代碼以下:app
'components'=>[ 'aop' => [ 'class' => 'frontend\components\InitAopComponent' ] ]
九、修改frontend/config/main.php文件,並在bootstrap數組下新增aop值,代碼以下:composer
'bootstrap'=>['log','aop'] 框架
原文連接:https://www.cnblogs.com/cmacro/p/9327602.html
參考連接:https://blog.csdn.net/guiyecheng/article/details/56016791