Question

The codes below can achieve the same output:

  • Using solely around plugin

    public function aroundXXX(
        SomeClass $subject,
        \Closure $proceed
    ){
        beforeFunctions();
        /*Perform XXX*/
        $result = proceed();
        afterFunctions();
        return $result;
    }
    
  • Using before+after plugin combined

    public function beforeXXX(
        SomeClass $subject
    ){
        beforeFunctions();
    }
    
    public function afterXXX(
        SomeClass $subject,
        $result
    ){
        afterFunctions();
        return $result;
    }
    

My question is: Which method is better, in terms of best practice and efficiency?

Was it helpful?

Solution

It depends on what type of customization you need.

Before methods are the first methods to run in an observer method. You can return a modified argument. If there are multiple arguments, the returning will be carried out according to a range of those arguments. If the returning is invalid, that means the arguments for the observed method should not be modified.

After methods start running right after the observed method is finished. After methods take a responsibility of editing the results of an observed method in the correct way and being required to have a return value.

Around methods allows the code to run before and after the observed method, so you can override a method. Before the arrange of the original method’s argument, a callable from around methods will be called to the next method in the chain, that means the next plugin or the observed function is also called.

In Short

If you want to modify arguments before running function then you should use before method.

If you want to change output of function, then you should use after method.

If you want to change both arguments and output of function then you should use around method

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top