YII2 implementing aspect-oriented programming

Source: Internet
Author: User
Tags autoload
This article introduces to you the content is YII2 implementation aspect-oriented programming, the need for friends can refer to

Introduction:
The goal of software development is to establish a model of some elements or information flow in the world, and to realize the engineering of software system needs to decompose the system into modules that can be created and managed. So the object-oriented programming technology with modularization of system is presented. Modular object-oriented programming greatly improves the readability, reusability and extensibility of software systems. The focus of the object method is to select the object as the primary unit of the module and to associate the object with all the behavior of the system. Object becomes the main element of the problem domain and the computational process. But object-oriented technology does not fundamentally solve the reusability of software systems. When creating a software system, there are many crosscutting concerns in real-world issues, such as security checks, logging, performance monitoring, exception handling, and their implementation code mixed with other business logic code and scattered in different parts of the software (directly adding the code that handles these operations to each module). This undoubtedly destroys the "single duty" principle of OOP, and the reusability of the modules is greatly reduced, which makes the maintainability and reusability of the software system greatly limited. At this time traditional oop design often take the strategy is to join the corresponding agent (proxy) layer to complete the functional requirements of the system, but such processing obviously makes the whole system to add a level of division, the complexity of the increase, thus giving people too thick feeling. This has resulted in aspect-oriented programming (AOP) technology. This programming pattern extracts the crosscutting concerns code scattered throughout the software system, and is modular and organised to further improve the maintainability, reusability, and scalability of the software.

Introduction to AOP:
Aop:aspect oriented programming is programming for facets.
Plane-oriented programming (also called aspect-oriented): Aspect oriented Programming (AOP) is a hotspot in software development at present. AOP enables the isolation of parts of the business logic, which reduces the coupling between parts of the business logic, improves the reusability of the program, and improves the efficiency of development.
AOP is the continuation of OOP, the abbreviation for (Aspect oriented programming), which means programming for facets (aspect).
The main functions are: Logging, performance statistics, security control, transaction processing, exception handling and so on.
The main intent is to divide the code of logging, performance statistics, security control, transaction processing, exception handling, and so forth from the business logic code, and by separating these behaviors, we want to be able to separate them into non-instructional methods of business logic, and then change these behaviors without affecting the code of the business logic.
A technology that can dynamically and uniformly add functionality to a program without modifying source code is possible through precompilation and run-time dynamic proxies. AOP is actually a continuation of the GOF design pattern, and the design pattern pursues the decoupling between the caller and the callee, and AOP can be said to be an implementation of this goal.
If the application is thought of as a stereoscopic structure, the blade of OOP is a longitudinal cut-in system, which divides the system into many modules (e.g. user module, article module, etc.), while the blade of AOP is the horizontal cut-in system, which extracts the parts that each module may want to repeat (such as: Permission check, logging, etc.). Thus, AOP is an effective complement to OOP.
Note: AOP is not a technique, it is actually a programming idea. Any technology that conforms to the idea of AOP can be seen as an implementation of AOP.

Basic concepts of AOP:
In object-oriented programming,classes, objects, encapsulation, inheritance, polymorphismConcept is the main term to describe the object oriented thinking. Similarly, there are some basic concepts in aspect-oriented programming:
Junction Point (Jointpoint): A specific point during the execution of a junction program. A typical junction point is the invocation of a method, the execution of the procedure itself, the initialization of the class, initialization of the object, and so on. Junction points are one of the core concepts of AOP and are used to define where the program is to add new logic through AOP.
Pointcut (Pointcut): A pointcut is a set of junction points that defines when a notification is to be executed. By defining pointcuts, we can precisely control what components receive notifications in the program. As we mentioned above, a typical junction point is a method call, and a typical pointcut is a collection of method calls to a class. Usually we have a complex pointcut to control when notifications are executed.
Notification (Advice): code that runs at a particular junction point is called a notification. There are many kinds of notifications, such as
The pre-notification (before advice) that was executed before the junction point and the post-notification (after advice) that was executed after the junction point.
Aspect (Aspect): A combination of notifications and pointcuts is called an aspect, so the facet defines the logic that should be included in a program and when it should be executed.
Weaving (Weaving): Weaving is the process of actually adding aspects to the program code. For static AOP scenarios, weaving is done at compile time, usually by adding a step in the compilation process. Similarly, the dynamic AOP scheme is dynamically woven into the program when it is running.
Target: If an object's execution is modified by an AOP, it is called a target object. The target object is also often referred to as the notified object.
Introduction (Introduction): By introducing, you can add a new method or property to an object to change its structure so that if the object's class does not implement an interface, you can modify it so that it becomes an implementation of the interface.

Static and dynamic: The difference between static AOP and dynamic AOP is mainly in what time it is woven and how it is woven into. Most of the earliest implementations of AOP are static. In static AOP, weaving is a step in the compilation process. In Java terminology, static AOP accomplishes the weaving process by directly manipulating bytecode, including modifying code and extending classes. Obviously, this approach produces good performance because the final result is plain Java bytecode, which no longer requires special skill at runtime to determine when notifications should be executed. The disadvantage of this approach is that if you want to modify the aspect, you must recompile the entire program, even if you are adding a new junction point. AspectJ is a typical example of static AOP. Unlike static AOP, the weaving of dynamic AOP is done dynamically at runtime. How the weaving is done, each implementation is different. Spring AOP takes the form of an agent, and then the agent executes the notification at the appropriate time. One of the weaknesses of dynamic AOP is that it is generally less performance than static AOP. The main advantage of dynamic AOP is that it is possible to modify all aspects of the program at any time without recompiling the target.

AOP Practices:

The YII2 framework itself has a function called behavior. It can dynamically append additional functionality to the current class, but this functionality is static and intrusive in the code hierarchy.

The following is an example of how to implement AOP programming in YII2 using the YII2 Framework Integrated GO!AOP Library. (GO!AOP introduction, you can refer to the official website of GO!AOP.)

Because the YII framework has its own classloader, it does not work properly when it is integrated GO!AOP, so disable it and use the class loader provided by composer.

As shown in the following code (using the YII2 Advanced Application template here):

1. Find Spl_autoload_register ([' Yii ', ' AutoLoad '], true, true); (project_path/vendor/yiisoft/yii2/yii.php) to disable it.

2, the implementation of composer require goaop/framework

3, modify the Composer.json file, add the following code snippet:

"AutoLoad": {        "psr-4": {          "backend\\": "backend//",          "frontend\\": "frontend//",          "common\\": "common/ /"        }  }

4, create a directory under the Frontend directory, and a new class Aopaspectkernel, for example:

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

5, in the Forntend directory in a new class initaopcomponent, and make it bootstrapinterface, so that it can be automatically booted when the YII2 frame boot

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 ');        }}

6, add the following code in frontend/config/params.php:

' AOP ' = [        ' debug ' = ' = ',        ' appdir ' + dirname (__dir__),        ' cachedir ' = dirname (__dir__). '/runtime/aop ',        ' includepaths ' = [            dirname (__dir__)        ]    

7. Create a new aspects directory under Frontend and create a new class Monitoraspect with the following code:

namespace frontend\aspects;use go\aop\aspect;use Go\Aop\Intercept\ Methodinvocation;use Go\lang\annotation\before;class Monitoraspect implements aspect{/** * Method that wil L be called before real method * * @param methodinvocation $invocation invocation * @Before ("Execu tion (Public frontend\components\aoptestcomponent->* (*)) ") */Public function beforemethodexecution (metho            Dinvocation $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"; }}

9, modify the frontend/config/main.php file, and add a key under the components array, the code is as follows:

' Components ' =>[        ' AOP ' = [            ' class ' = ' Frontend\components\initaopcomponent '        ]    


10, modify the frontend/config/main.php file, and under the bootstrap array new AOP values, the code is as follows:

' Bootstrap ' =>[' log ', ' AOP '

At this point, YII2 integration GO!AOP complete ...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.