I was wondering why it's not possible to create plugins for protected
methods. There's this piece of code in the Magento\Framework\Interception\Code\Generator\Interceptor
:
protected function _getClassMethods()
{
$methods = [$this->_getDefaultConstructorDefinition()];
$reflectionClass = new \ReflectionClass($this->getSourceClassName());
$publicMethods = $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach ($publicMethods as $method) {
if ($this->isInterceptedMethod($method)) {
$methods[] = $this->_getMethodInfo($method);
}
}
return $methods;
}
It checks if method is public
before allowing it to be intercepted. It can be easily changed by creating a preference
in the di.xml
of own module, of course, like this:
<?xml version="1.0"?>
<config>
<preference for="Magento\Framework\Interception\Code\Generator\Interceptor" type="MyVendor\MyModule\Model\MyInterceptorModel" />
</config>
and rewriting the _getClassMethods
with the \ReflectionMethod::IS_PUBLIC
changed to \ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED
inside of the method.
But I wonder why it's not possible to intercept protected methods in the original method definition? Does it have a major impact on the performance, or there's some other reason for that, like allowing 3rd party modules to make Magento logic too "messy"?