ASPECT-ORIENTED PROGRAMMING (AOP)

Aspect-Oriented Programming (AOP) is a programming paradigm that works in tandem with Object-Oriented Programming (OOP) to increase modularization by separating concerns in a software application. Separation of concerns (SoC) seeks to make software easier to maintain by separating features and behavior into manageable components, each with its own purpose and business to look after.

Modularizing concerns into discrete methods, classes, and packages is already possible with OOP. Some concerns, however, are difficult to categorise since they cut between classes and even packages. Security is an example of a cross-cutting concern: Although the primary function of a Forum package is to display and handle forum postings, it must also provide some level of security to ensure that only moderators may approve or delete entries.

Many more packages require comparable security features to secure record creation, destruction, and updates. AOP allows you to separate the security (or any other) part into its own package and assign explicit duties to the other objects, who will most likely not be implementing any security.

Aspect-Oriented Programming (AOP) has been present for a long time in other programming languages, and sophisticated solutions that use AOP exist. You may apply the most popular AOP techniques in your own PHP application with Flow’s AOP framework. It doesn’t require any additional PHP extensions or manual build procedures, unlike previous ways, and it’s simple to set up.

As the name implies, aspect oriented programming (AOP) employs aspects in programming. It is described as the division of code into separate modules, also known as modularization, with the aspect serving as the primary unit of modularity. Aspects provide for the implementation of crosscutting concerns like transaction and logging that aren’t vital to business logic without clogging up the code that is essential to its functionality. It accomplishes this by providing new behaviour to the current code in the form of advise. For example, security is a crosscutting concern; security rules can be applied to multiple functions in an application, so instead of repeating the code in each method, describe the functionality in a common class and control where to apply it throughout the application.

EXAMPLE: LOGGING WITHOUT AOP

namespace Examples\Forum\Domain\Model;
use Examples\Forum\Logger\ApplicationLoggerInterface;
 
class Forum {
 
        /**
         * @Flow\Inject
         * @var ApplicationLoggerInterface
         */
        protected $applicationLogger;
 
        /**
         * Delete a forum post and log operation
         */
        public function deletePost(Post $post): void
        {
                $this->applicationLogger->log('Removing post ' . $post->getTitle(), LOG_INFO);
                $this->posts->remove($post);
        }
 
}

The logging is now done from an AOP aspect. It’s just a class tagged with @aspect and a method that implements the specific action, an before advice. The expression after the @before tag tells the AOP framework to which method calls this action should be applied. It’s called point cut expression and has many possibilities, even for complex scenarios.

Example: logging with AOP

namespace Examples\Forum\Logging;
use Examples\Forum\Logger\ApplicationLoggerInterface;
use Neos\Flow\AOP\JoinPointInterface;
 
/**
 * @Flow\Aspect
 */
class LoggingAspect {
 
        /**
         * @Flow\Inject
         * @var ApplicationLoggerInterface
         */
        protected $applicationLogger;
 
        /**
         * Log a message if a post is deleted
         *
         * @Flow\Before("method(Examples\Forum\Domain\Model\Forum->deletePost())")
         */
        public function logDeletePost(JoinPointInterface $joinPoint): void
        {
                $post = $joinPoint->getMethodArgument('post');
                $this->applicationLogger->log('Removing post ' . $post->getTitle(), LOG_INFO);
        }
 
}

As you can see, the advice has complete access to the actual method call, the join point, as well as class, method, and method parameter information.

AOP’s Dominant Frameworks:

AOP refers to programming methodologies and frameworks that support and implement code modularization. Let’s have a look at the three most common AOP frameworks:

AspectJ is a Java programming extension developed at the PARC research centre. It has a Java-like syntax and connectors with IDEs for presenting crosscutting structure. It comes with its own compiler and weaver, which allows you to use the entire AspectJ language.

JBoss is a Java application server that was created by JBoss and is used for Java development.

Spring: It implements AOP utilising XML-based configuration, as well as annotations that are interpreted using an AspectJ-supplied library for parsing and matching.

Because AspectJ libraries with the Spring framework are currently dominating the market, let’s look at how Aspect-oriented programming works with Spring.

Aspect-Oriented Programming in Spring: How Does It Work?

It is a common misconception that calling a method immediately implements cross-cutting concerns, however this is not the case. The advise is not invoked simply by calling the method (the job which is meant to be done). Spring employs a proxy-based technique, in which it constructs a proxy Object that wraps around the actual object and accepts the applicable method call advice. Proxy objects can be generated manually using the proxy factory bean or automatically using the XML file’s auto proxy setup, and they are destroyed once the execution is complete. Proxy objects are used to enhance the genuine object’s original behaviour.

Terminologies used in AOP:

Aspect:

The aspect is the class that implements the JEE application cross-cutting concerns (transaction, logger, and so on). It can be configured as a regular class via XML settings or as a regular class annotated with @Aspect.

Weaving:

The procedure of tying Aspects to a Recommended Object. It can be done at the time of loading, compiling, or running. At runtime, Spring AOP weaves.

Advice:

The work that an Aspect is supposed to do, or the action that the Aspect is supposed to conduct at a certain point. Before, After, Around, AfterThrowing, and AfterReturning are the five forms of advice.

Before:

This method is called before the suggested method is called. The @Before annotation is used to indicate it.

After:

Regardless of whether the advised approach is successful or not, it runs after it has completed. The @After annotation is used to indicate it.

AfterReturning:

Runs after the recommended method completes successfully, that is, without any runtime exceptions. It’s indicated with the annotation @AfterReturning.

Around:

This is the most powerful piece of advice since it wraps around and runs before and after the recommended approach. When we need frequent access to a method or database, such as caching, this form of advice is employed. The @Around annotation is used to indicate it.

AfterThrowing:

When the suggested method throws a Runtime Exception, this method is called. It’s indicated with the annotation @AfterThrowing.

JoinPoints:

Advice can be applied to thousands of possibilities or points in an application. Join points are what they’re called. For example, advice can be applied at each time a method is called, an exception is thrown, or at any other moment. However, at the moment, Spring AOP only allows method execution join points (advising the execution of methods on Spring beans).

Pointcut

Because it is not possible to apply advice at every point in the code, the Pointcut refers to the selected join points where advice is finally applied. These pointcuts are frequently specified using explicit class and method names or with regular expressions that define matching class and method name patterns. It reduces the amount of code that is repeated by writing it once and using it several times.

Introduction

Declaring new methods or fields on behalf of a type (introduction). Spring AOP enables you to add new interfaces (and their implementations) to any recommended object. To make caching easier, you might use an introduction to make a bean implement the IsModified interface. (In the AspectJ community, an introduction is referred to as an inter-type declaration.)

Target object

One or more aspects are advising the target item. Also known as the recommended object. This object will always be a proxied object because Spring AOP is implemented through runtime proxies.

AOP proxy:

The AOP framework creates an object called an AOP proxy to implement the aspect contracts (advise method executions and so on). An AOP proxy in the Spring Framework is either a JDK dynamic proxy or a CGLIB proxy.

Weaving:

 creating a recommended item by connecting aspects with other application types or objects. This can be done at build time (for example, using the AspectJ compiler), load time, or runtime. Spring AOP weaves at runtime, just like other pure Java AOP frameworks.

Types of advise include:

Before advice: Advice that runs before a join point but doesn’t have the power to stop the execution flow from continuing to the join point (unless it throws an exception).

Following your advice: After a join point completes normally, such as if a method returns without raising an exception, advice should be executed.

After throwing advice: If a method exits by throwing an exception, this advice will be executed.

After that, (finally) advice: Advice should be followed regardless of how a join point exits (normal or exceptional return).

Advice given in the vicinity of a join point, such as a method invocation. This is the most effective form of guidance. Before and after the method call, custom actions can be performed around advise. It’s also in charge of deciding whether to go to the join point or to skip the suggested method execution by returning a value or throwing an exception.

The most general type of advise is about advice. We recommend that you select the least powerful advice type that can implement the desired behaviour because Spring AOP, like AspectJ, provides a full spectrum of advice types. If you simply need to update a cache with a method’s return value, for example, you should use an after returning advice rather than an around advice, albeit an around advice can do the same thing.

Using the most specific advise type simplifies the programming model and reduces the risk of errors. You don’t need to run the continue() function on the JoinPoint used for around guidance, but you can’t avoid doing so.

All advice parameters in Spring 2.0 are statically typed, so you may deal with advice parameters of the proper type (for example, the type of the return value after a method execution) instead of Object arrays.

The core to AOP is the concept of join points, which are matched by pointcuts, which distinguishes it from prior technologies that only offer interception. Pointcuts make it possible to target advise regardless of the Object-Oriented structure. For example, a series of procedures spanning many objects can be applied to an around advice offering declarative transaction management (such as all business operations in the service layer).

Capabilities and objectives of the Spring AOP

Spring AOP is written entirely in Java. A unique compilation process is not required. Spring AOP is suited for usage in a J2EE web container or application server because it does not require control over the class loader hierarchy.

Only method execution join points are presently supported by Spring AOP (advising the execution of methods on Spring beans). Although support for field interception might be introduced without changing the core Spring AOP APIs, it is not implemented. Consider using a language like AspectJ to advise field access and alter join points.

Spring AOP takes a different approach to AOP than most other AOP frameworks. The goal is to provide a close interaction between AOP implementation and Spring IoC to help solve typical difficulties in enterprise applications, rather than to give the most extensive AOP implementation (although Spring AOP is pretty capable).

The AOP capability of the Spring Framework, for example, is typically used in conjunction with the Spring IoC container. Aspects are specified using standard bean definition syntax (with extensive “autoproxying” capabilities): this is a key distinction from other AOP implementations. Some tasks are difficult or impossible to achieve with Spring AOP, such as advising very fine-grained objects (usually domain objects): in these circumstances, AspectJ is the best option.

Spring AOP, on the other hand, has shown to be a great solution for most problems in J2EE applications that are susceptible to AOP.

Spring AOP will never try to compete with AspectJ in terms of providing a full AOP solution. Both proxy-based frameworks like Spring AOP and full-fledged frameworks like AspectJ are valuable in our opinion, and they are complementing rather than competing. Spring 2.0 unifies Spring AOP and IoC with AspectJ, allowing all types of AOP to be supported within a single Spring-based application architecture. The Spring AOP API and the AOP Alliance API are unaffected by this integration, and Spring AOP remains backwards compatible.

Conclusion

To summarise, AOP has the potential to transform the way applications are created, but it also introduces developers and project managers to a new set of challenges regarding application behaviour. Also, it should be clear that AOP is not a replacement for OOP, but rather a new way of thinking about object functionality: allowing an object’s behaviour to be modularized and reused across other components—without the need for complex class hierarchies, but rather complex webs of AOP configuration. AOP is not a new concept, but it is gaining traction and attracting the attention of developers all around the world.

About the author

Ashwini

View all posts
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments