Home > Backend Development > PHP Tutorial > YII2 implements aspect-oriented programming

YII2 implements aspect-oriented programming

不言
Release: 2023-04-03 09:06:01
Original
2729 people have browsed it

This article introduces to you the implementation of aspect-oriented programming in YII2. Friends in need can refer to it

Introduction:
The goal of software development is to establish a model of some elements or information flows in the world. To realize the engineering of software systems, it is necessary to decompose the system into components that can be created and Management module. As a result, object-oriented programming technology with system modularity emerged. Modular object-oriented programming greatly improves the readability, reusability and scalability of software systems. The focus of the object-oriented approach is to select the object as the main unit of the module and connect the object to all behaviors of the system. Objects become the main elements of problem domains and computational processes. However, object-oriented technology does not essentially solve the reusability of software systems. When creating a software system, there are many cross-cutting concerns in real-world problems, such as security checks, logging, performance monitoring, exception handling, etc. Their implementation codes are mixed with other business logic codes and scattered in different parts of the software. (Directly adding the code to handle these operations into each module), this undoubtedly destroys the "single responsibility" principle of OOP, and the reusability of the module will be greatly reduced, which makes the maintainability and reusability of the software system affected. Extremely restrictive. At this time, the strategy often adopted by traditional OOP design is to add the corresponding proxy layer to complete the functional requirements of the system. However, such processing obviously adds a level of division to the overall system, and the complexity also increases, thus giving The feeling of being too heavy. This gave rise to aspect-oriented programming (AOP) technology. This programming model extracts cross-cutting concern codes scattered throughout the software system, modularizes them, and groups them together, thus further improving the maintainability, reusability, and scalability of the software.

Introduction to AOP:
AOP: Aspect Oriented Programming.
Aspect-oriented programming (also called aspect-oriented): Aspect Oriented Programming (AOP) is a hot spot in current software development. AOP can be used to isolate various parts of the business logic, thereby reducing the coupling between the various parts of the business logic, improving the reusability of the program, and improving the efficiency of development.
AOP is the continuation of OOP and is the abbreviation of (Aspect Oriented Programming), which means aspect-oriented programming.
The main functions are: logging, performance statistics, security control, transaction processing, exception handling, etc.
The main intention is to separate logging, performance statistics, security control, transaction processing, exception handling and other codes from the business logic code. By separating these behaviors, we hope to separate them into non-guiding businesses. Logic methods, and then change these behaviors without affecting the business logic code.
 A technology that can dynamically and uniformly add functions to a program without modifying the source code through precompilation and runtime dynamic proxies. AOP is actually a continuation of the GoF design pattern. The design pattern tirelessly pursues the decoupling between the caller and the callee. AOP can be said to be a realization of this goal.
Assuming that the application is thought of as a three-dimensional structure, the sharp edge of OOP is to cut into the system vertically and divide the system into many modules (such as user modules, article modules, etc.), while the sharp edge of AOP is to cut into the system horizontally. Extract parts that may require repeated operations in each module (such as: permission checks, logging, etc.). It can be seen that AOP is an effective supplement to OOP.
Note: AOP is not a technology, it is actually a programming idea. Any technology that conforms to AOP thinking can be regarded as the implementation of AOP.

Basic concepts of AOP:
In object-oriented programming, class, object, encapsulation, inheritance, polymorphism and other concepts It is the main term describing object-oriented thinking. Similarly, in aspect-oriented programming, there are also some basic concepts:
JointPoint: A specific point in the execution of a joint program. Typical connection points include: calling a method; the method executing the process itself; class initialization; object initialization, etc. Connection points are one of the core concepts of AOP, which are used to define where in the program new logic is added through AOP.
Pointcut: A pointcut is a set of connection points used to define when a notification should be executed. By defining pointcuts, we can precisely control which components in the program receive what notifications. We mentioned above that a typical connection point is a method call, and a typical entry point is a collection of method calls to a certain class. Usually we control when notifications are executed by forming complex entry points.
                                                                                                                                                                                                                                                                                                      Advice There are many types of advice, such as
preadvice (before advice) that is executed before the connection point and postadvice (after advice) that is executed after the connection point.
       方面(Aspect) :通知和切入点的组合叫做方面,所以,方面定义了一段程序中应该包括的逻辑,以及何时应该执行该逻辑。
       织入(Weaving) :织入是将方面真正加入程序代码的过程。对于静态 AOP 方案而言,织入是在编译时完成的,通常是在编译过程中增加一个步骤。类似的,动态 AOP 方案则是在程序运行是动态织入的。
       目标(Target) :如果一个对象的执行过程受到某一个 AOP 的修改,那么它就叫一个目标对象。目标对象通常也称为被通知对象。
       引入(Introduction) :   通过引入,可以在一个对象中加入新的方法或属性,以改变它的结构,这样即使该对象的类没有实现某一个接口,也可以修改它,使之成为该接口的一个实现。   

       静态和动态:静态 AOP 和动态 AOP 两者之间的区别主要在于什么时间织入,以及如何织入。最早的 AOP 实现大多都是静态的。在静态 AOP 中,织入是编译过程的一个步骤。用Java 的术语说,静态 AOP 通过直接对字节码进行操作,包括修改代码和扩展类,来完成织入过程。显然,这种办法生成的程序性能很好,因为最后的结果就是普通的 Java 字节码,在运行时不再需要特别的技巧来确定什么时候应该执行通知。这种方法的缺点是,如果想对方面做什么修改,即使只是加入一个新的联结点,都必须重新编译整个程序。AspectJ 是静态 AOP 的一个典型例子。与静态 AOP 不同,动态 AOP 中织入是在运行时动态完成的。织入具体是如何完成的,各个实现有所不同。Spring AOP 采取的方法是建立代理,然后代理在适当的时候执行通知。动态 AOP 的一个弱点就在于,其性能一般不如静态 AOP。而动态AOP 的主要优点在于可以随时修改程序的所有方面,而不需重新编译目标。

AOP实践:

YII2框架本身拥有一个功能,叫做行为.它可以动态的为当前的类附加额外的功能,但这种功能在代码层级结构是静态的,有侵入性的。

下面以YII2框架集成go!aop库为例,介绍在YII2中如何实现AOP编程.(go!aop简介,可以参考go!aop的官网.)

由于YII框架拥有自己的类加载器,所在集成go!aop的时候,不能正常的工作,所以要将其禁用掉,使用composer提供的类加载器。

如下代码所示(这里使用YII2高级应用模板):

1、找到  spl_autoload_register(['Yii', 'autoload'], true, true);  (PROJECT_PATH/vendor/yiisoft/yii2/Yii.php) 将其禁用掉.

2、执行  composer require goaop/framework

3、修改composer.json文件,加入如下代码段:

 "autoload": {
        "psr-4": {
          "backend\\": "backend//",
          "frontend\\": "frontend//",
          "common\\": "common//"
        }
  }
Copy after login

4、 在frontend 目录下创建一个components是目录,并新建一个类AopAspectKernel,例如:

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());
        }
}
Copy after login

5、在forntend目录下在新建一个类InitAopComponent,并使其实现BootstrapInterface,使其可以在YII2框架引导时被自动引导

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']);
        }
}
Copy after login

6、在frontend/config/params.php中新增如下代码:

 'aop' => [
        'debug' => true,
        'appDir' => dirname(__DIR__),
        'cacheDir' => dirname(__DIR__) . '/runtime/aop',
        'includePaths' => [
            dirname(__DIR__)
        ]
    ]
Copy after login

7、在frontend下面新建aspects目录,并新建类MonitorAspect,代码如下:

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";
        }
}
Copy after login

9、修改frontend/config/main.php文件,并在components数组下新增一个key,代码如下:

 &#39;components&#39;=>[
        &#39;aop&#39; => [
            &#39;class&#39; => &#39;frontend\components\InitAopComponent&#39;
        ]
    ]
Copy after login


10、修改frontend/config/main.php文件,并在bootstrap数组下新增aop值,代码如下:

&#39;bootstrap&#39;=>[&#39;log&#39;,&#39;aop&#39;]
Copy after login

至此,YII2整合go!aop完成...

相关推荐:

关于IIS下PHP快三平台源码的架设环境的配置过程

如何在yii2框架的di容器源码中了解反射的作用

The above is the detailed content of YII2 implements aspect-oriented programming. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template