Discovery Decorators

Last updated on
25 March 2021

This documentation needs work. See "Help improve this page" in the sidebar.

A discovery decorator is a class which wraps another discovery mechanism in order to provide additional functionality (Wiki: Decorator pattern). Discovery decorators conform to the same interfaces as regular discovery classes, but they are intended to be used in tandem with another discovery class. Discovery decorators should take a DiscoveryInterface typed variable in their __construct method and any other parameters that are necessary to make them work. There are two included discovery decorators in core, we'll look at the CacheDecorator first.

Drupal\Core\Plugin\Discovery\CacheDecorator

We'll discuss the various methods that exist here and what they do.

public function __construct(DiscoveryInterface $decorated, $cache_key = NULL);

As mentioned above, this function takes a DiscoveryInterface compatible variable called $decorated. This could be any of the previously discussed discovery classes. In addition to this it takes a $cache_key which will be used when making cache()->get() calls.

public function getPluginDefinition($plugin_id);

If you've looked at the code for any of the other discovery classes, then this function should be familiar. In the case of the CacheDecorator, we will check to see if we have a cached version of this already loaded and if we don't, then it will manually load the definition for us by proxying to the discovery class that was passed into the constructor.

public function getPluginDefinitions();

Another familiar discovery function, in this function we will look to see if a cache of all definitions exists, if one does not, we'll get all the definitions and then cache it for next time.

protected function getCachedDefinitions();

The first unfamiliar function, this is a simple function that will get our cached definition either from a variable in the class, or if that's empty, then will attempt to get the definitions via cache()->get($this->cacheKey).

protected function setCachedDefinitions($definitions);

This simple function is used to set the cache definitions via cache()->set($this->cacheKey, $definitions).

public function __call($method, $args);

Finally, the __call() method is added. This will allow our decorator class to proxy any incoming method that the original discovery class supports into that class by calling:

return call_user_func_array(array($this->decorated, $method), $args);

All discovery decorators should implement this function.

Help improve this page

Page status: Needs work

You can: