Why protected methods can't be intercepted?

According to Magento docs it is not "possible" to use a plugin on a protected method.

(http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html)

You cannot apply plugins to:

  • Final methods
  • Final classes
  • Any class that contains at least one final public method
  • Non-public methods
  • Class methods (such as static methods)
  • __construct Virtual types

But your point is correct, according to ___callPlugins definition in Magento\Framework\Interception\Interceptor, I do not see any problem using protected methods.

My first guess is that they limited it to avoid an high code complexity since Magento should rewrite any protected method and call ___callPlugins for each of them... it will terribly slowdown IMHO.

But I think the real reason is for a logical consinstency: plugins should be used to change the class methods output/input, not to rewrite internal behaviour, so they should only access public methods.

To rewrite an internal behaviour you have to use a preference. It makes sense.


If I remember correctly from a presentation of Anton Krill, he said that technically protected methods can be intercepted, but it defeats the purpose of having them "protected".
The interceptor class that is autogenerated extends the original class so it has access to the protected methods.
But... Protected methods should not be available outside the class.
So it's more of a decision than a limitation.

Tags:

Magento2