Creating our own cache bin

Usually, the existing cache bins, particularly the default one, will be enough to store our own cache entries. However, there are times in which we need to create multiple entries for the same functionality, in which case, it would help to have a special bin for that. So, let's see how that can be created.

It's quite easy because all we have to do is define a service:

cache.my_bin: 
class: Drupal\Core\Cache\CacheBackendInterface
tags:
- { name: cache.bin }
factory: cache_factory:get
arguments: [my_bin]

The class used in this service definition is actually an interface. This is because we are using a factory to instantiate the service rather than the container directly. This means we don't know what class will be instantiated. In this case, the factory in question is the service with the name cache_factory and its get() method. In Chapter 3, Logging and Mailing, we saw an example in which something like this happened when we talked about logger channels.

The cache.bin tag is used so that Drupal can understand the function of this service, namely, that it is a cache bin. The responsibility of making sure this bin gets its storage belongs to the actual backend. So in our example, the DatabaseBackend creates and removes the cache table as needed.

Lastly, the static argument is the name of the bin that gets passed to the factory and that is used to create the cache backend for this particular bin. That is pretty much it. If we clear the cache, we can already see a new cache table for our bin in the database.