3

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?

1
  • its depends on your requirements, where you want to use your plugin code. Commented Jan 10, 2018 at 5:03

1 Answer 1

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.