3 namespace Drupal\Core\Cache;
6 * Defines the cache backend factory.
8 use Drupal\Core\Site\Settings;
9 use Symfony\Component\DependencyInjection\ContainerAwareInterface;
10 use Symfony\Component\DependencyInjection\ContainerAwareTrait;
12 class CacheFactory implements CacheFactoryInterface, ContainerAwareInterface {
14 use ContainerAwareTrait;
19 * @var \Drupal\Core\Site\Settings
24 * A map of cache bin to default cache backend service name.
26 * All mappings in $settings takes precedence over this, but this can be used
27 * to optimize cache storage for a Drupal installation without cache
28 * customizations in settings.php. For example, this can be used to map the
29 * 'bootstrap' bin to 'cache.backend.chainedfast', while allowing other bins
30 * to fall back to the global default of 'cache.backend.database'.
34 protected $defaultBinBackends;
37 * Constructs CacheFactory object.
39 * @param \Drupal\Core\Site\Settings $settings
41 * @param array $default_bin_backends
42 * (optional) A mapping of bin to backend service name. Mappings in
43 * $settings take precedence over this.
45 public function __construct(Settings $settings, array $default_bin_backends = []) {
46 $this->settings = $settings;
47 $this->defaultBinBackends = $default_bin_backends;
51 * Instantiates a cache backend class for a given cache bin.
53 * By default, this returns an instance of the
54 * Drupal\Core\Cache\DatabaseBackend class.
56 * Classes implementing Drupal\Core\Cache\CacheBackendInterface can register
57 * themselves both as a default implementation and for specific bins.
60 * The cache bin for which a cache backend object should be returned.
62 * @return \Drupal\Core\Cache\CacheBackendInterface
63 * The cache backend object associated with the specified bin.
65 public function get($bin) {
66 $cache_settings = $this->settings->get('cache');
67 // First, look for a cache bin specific setting.
68 if (isset($cache_settings['bins'][$bin])) {
69 $service_name = $cache_settings['bins'][$bin];
71 // Second, use the default backend specified by the cache bin.
72 elseif (isset($this->defaultBinBackends[$bin])) {
73 $service_name = $this->defaultBinBackends[$bin];
75 // Third, use configured default backend.
76 elseif (isset($cache_settings['default'])) {
77 $service_name = $cache_settings['default'];
80 // Fall back to the database backend if nothing else is configured.
81 $service_name = 'cache.backend.database';
83 return $this->container->get($service_name)->get($bin);