Adapter classes follow the adapter pattern and wrap around classes from third-party libraries. These classes allow you to use functionality from third-party libraries in your code by converting the third-party class interfaces into an interface that is expected by your native code.
When to use
You should always use adapter classes instead of directly using classes from third-party libraries. This reduces the change impact on your code when the API changes in a third-party library .
We recommend using adapter classes for dependency injection to get access to the functionality provided by third-party classes.
How to write
A common approach in developing an adapter is to create an interface named
AdapterInterface to describe the functionality the third-party class provides.
This class is typically found in a directory labeled
Classes implementing this adapter interface use the third-party class directly to provide indirect functionality.
This approach allows you to update or substitute different implementations provided by other third-party classes without the need to update code that uses your adapter.
Examples of adapters in Magento
The minifier functionality provided by the
Magento/Framework/Code library involves the use of third-party libraries for code compression.
Magento/Framework/Image library uses adapters to access functionality provided by GD(php-gd2) and ImageMagick(php-imagick) third-party libraries.
The code below describes an interface for an adapter that parses markdown .
The code below is an implementation class of the
AdapterInterface that uses the php-markdown library to convert markdown into HTML
To configure the ObjectManager to use the PhpMarkdown implementation when the AdapterInterface class is requested as a dependency, add the following code in your di.xml file.
The code below is an alternate implementation class of the
AdapterInterface that uses the Ciconia library to parse markdown into HTML.
This code differs from the previous implementations in that an instance of the
Ciconia class is a constructor dependency.
The following dependency injection
entries belong in the
They describe to the ObjectManager how to create the third-party and adapter classes.