A plugin is used to extend or modify a public method’s behaviour by applying code before, after, or around that observed method.

The first argument for the before, after, and around methods is an object that provides access to all public methods of the observed method’s class.

Note: The rest of the parameters for these functions are depending on the function type (before, after, around) – they are having a dynamic number of parameters.

Before

Before methods run prior to an observed method. These methods must have the same name as the observed method with ‘before’ as the prefix.

Very important: the number of arguments that before method is taking is equal with the number of arguments of the observed  +1 (the subject argument).

 

Exercise:  Customise Magento\Theme\Block\Html\Breadcrumbs class, addCrumb() method, so that every crumbName is transformed into: $crumbName . “(!)”

My Solution:  (more about XML implementation)

Create file at this locations:

with the following content for XML:

And for PHP file:

 

Key points:

  • Pay attention at the number of arguments, it is exact the same number of arguments as the main function addCrumb().
  • The returned result should be an array containing the number of parameters.
  • The IF check is because the parent breadcrumb is returning an object and we want to apply it only for the children.

 

After

These type of methods run after the completion of the observed method. These methods must have the same name as the observed method with ‘after’ as the prefix.

Exercise: Customize Magento\Theme\Block\Html\Footer class, to replace the body of the getCopyright() method with your implementation. Return a hard-coded string: “Customized copyright!”

Solution:

Create the files at these paths:

And the PHP implementation:

Key points: 

  • The after method  is taking just ONE parameter  Another one that provides access to all public methods of the observed method’s class.
  • The returning value should be the same type as the extended method.