Intercepting Third-Party Code in Magento 2

Photo by Oleg Magni from Pexels because Medium insists on having a photo here.

Intercepting Third-Party Code in Magento 2Not all code is covered by the interceptor generation in Magento 2.

Here’s how we fixed it.

Marcus Pettersen IrgensBlockedUnblockFollowFollowingMar 25While working on a client’s Magento 2 install, we ran into an issue where a third-party library would randomly fail to do what it was designed to do.

Five layers down in the call stack, inside of the custom HTTP client, the library errored.

Unfortunately, the exception message did not at all tell us which part of our implementation was wrong, or which invalid data was provided by us.

The arguments were not logged and were not included in the stack trace, and we were left with a rather cryptic server error caused by the library.

Magento 2 offers a lot of neat features, with code interception and plugins being among the most useful.

The exception was caused in a public method, so to try and track down the cause of the error, we decided to wrap this method in an around-plugin.

(Here’s the relevant gist.

)It worked locally and passed our tests, so we quickly got it deployed and started waiting for the log messages.

It didn’t work.

The plugin was never used.

Turns out, Magento 2 will happily create interceptors for any class as long as you are in developer mode.

Switching to production mode changes that.

This is why: In production mode, Magento only performs interceptor generation on code registered as a component.

This makes sense.

It would, however, be really cool if this behaviour was the same in both modes.

You can solve this issue by registering the code you are intercepting as a Magento component.

<?phpuse MagentoFrameworkComponentComponentRegistrar;ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Vendor_Library', "/path/to/library");.

. More details

Leave a Reply