Building an AOP Framework for PHP – Weaving Strategies

In the previous posts (see [1], [2] and [3]) we have learned how to add metadata to classes and how to work with annotations. Now it’s time to talk about adding advices to the objects using these annotations.

Consider two different functions each defined within a separate class – the original code and the advice handling cross-cutting functionality. AOP allows you to execute both of them in one turn, for example the original code followed by the advice code. We have to connect both pieces of code or, in other words, we have to apply the aspect to the original class.

The process of applying aspects to a class is called weaving.

Building an AOP Framework for PHP – Instantiating Annotation Objects

Our previous post covered the task of reading annotations from DocBlocks. It described how to get the name and the parameters (also called attributes) for an annotation defined like this:

We finished the last post by taking a look at the AnnotationParser where we filled the variables $annotationName and $parameters with some data. That’s all we have to know about the annotation. So what’s next?

Our extended reflection API will keep all the information about the annotations. Thus, the answer is obvious: For each annotation, there is an object to be created which will encapsulate all data read out from the annotation definition.

Building an AOP Framework for PHP – Reading Annotations

As mentioned in our previous post, the very first step towards an annotation based AOP framework is a reflection API that is aware of annotations and is therefore more powerful than the standard reflection API of PHP. The API shall be able to read annotations on classes, class methods and class properties. At first, we have to think about how annotations will look like. This is pretty obvious if we bear in mind that we want take Java as a model.

Building an AOP Framework for PHP – Motivation

A couple of years ago, in 2009 to be precise, I came into contact with aspect-oriented programming (AOP) for the first time. That was a Java EE project in which JBoss Seam was used. Amongst others, the implementation used JBoss Seam Interceptors while EJB 3.0 introduced a standard interceptor model for session bean components.

The possibilities which were opened up by using such annotation based features were amazing. They allowed the encapsulation of cross-cutting concerns without having to change the affected code. By using AOP, in particular non-functional requirements can be realized, such as logging oder security checks. At the same time, the program logic remains lean.