What Classes are Interceptable/Pluginable in Magento 2?

interceptormagento2PHPplugin

Date: May 30, 2015 (given the changing nature of Magento 2).

Magento 2 introduced a plugin concept, implemented via an interceptor pattern.

What's not clear from the docs is — which classes and objects in Magento are "intercept-able"? That is, you configure a plugin with XML that looks like the following

<config>
    <type name="{ObservedType}">
        <plugin name="{pluginName}" type="{PluginClassName}" sortOrder="1" disabled="true"/>
    </type>
</config>

but it's not clear which classes are valid as an ObservedType. This older wiki article provides some clues when it says

Please note that the plugin feature does not apply to
– Classes created without dependency injection, that is, created with operator new directly, -Final methods, -Final classes

Is any object created via dependency injection available to be intercepted? Does the ObservedType need to be the type hint provided in the a __construct method, or can it (should it?) be something else?

Mainly trying to get my head around what can and can't be done with a Magento 2 interceptor before I start using them.

Best Answer

Every Class of an Magento Module is intercaptable.

As described on the current wiki, it is limited by final methods and classes

Not validated, but Classes of libraries (lib directory) are(/should) not allowed to get intercepted.

The limitation how the object got created is not true anymore I think, at least if the autoloader is correctly configured. And should not matter as they dont get created on the fly, but when the generator got executed. (so it is only a matter of, the magento autoloader should be the first one)

Related Topic