#! code: Drupal 10: Creating Custom Context Providers

I previously looked at injecting context providers into context aware plugins. This time I will explore more about creating our own context providers to plug into this system.

The context provider system is an ideal way to provide context to context aware plugins, with blocks being the prime example. You would use a context provider to inject an entity or value into the block so that actions can be taken using that data.

For example, we could load the current node from the route using context so that we didn't have to bake the route provider logic into the block.

The values we inject also plug into the cache systems and so we don't need to worry about making sure we integrate the cache systems for each type of context within the block system. Cache contexts is all taken care of in the block plugin code.

In this article I will look at why you might want to create a context provider, how to create one, and some examples of them in use.

By default, Drupal comes with the following context providers:

  • Current language context (provided by \Drupal\Core\Language\ContextProvider\CurrentLanguageContext).
  • The node entity from the current route (provided by \Drupal\node\ContextProvider\NodeRouteContext).
  • The taxonomy term entity from the current route (provided by \Drupal\taxonomy\ContextProvider\TermRouteContext).
  • The current user (provided by \Drupal\user\ContextProvider\CurrentUserContext).

This gives us a variety of contexts that are commonly used, but there are many reasons why we would want to create our own context providers. Here are some examples of potential contexts we could create using this system.

Read more

PubDate

Tags