Adapters
Overview
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 Adapter
.
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
Magento/Framework/Code/Minifier
The minifier functionality provided by the Magento/Framework/Code
library involves the use of third-party libraries for code compression.
The AdapterInterface
for this class contains a minify($content)
function that the CSSmin
and JShrink
implementation class define.
The jshrink(tedivm/jshrink) and cssmin(tubalmartin/cssmin) libraries registered in the composer.json
file provide the functionalities for the implementation classes.
Magento/Framework/Image
The Magento/Framework/Image
library uses adapters to access functionality provided by GD(php-gd2) and ImageMagick(php-imagick) third-party libraries.
The AdapterInterface
class defines the available functionality, and the Gd2
and ImageMagick
adapter classes provides the concrete implementation using the third-party libraries.
Example Code
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 di.xml
file.
They describe to the ObjectManager how to create the third-party and adapter classes.