In Drupal, the class for a service defined in a module .services.yml file doesn't need to implement create(ContainerInterface $container)
. It's not even requested to implement a specific PHP interface.
See one of the services Drupal core implements, for example the path_alias.manager service.
aliaspath_alias.manager:
class: Drupal\path_alias\AliasManager
arguments:
- '@path_alias.repository'
- '@path_alias.whitelist'
- '@language_manager'
- '@cache.data'
The AliasManager
class that implements that service doesn't implement any create()
method; it just implement the constructor, with the parameters defined in the same order the service arguments are listed.
public function __construct($alias_repository, AliasWhitelistInterface $whitelist, LanguageManagerInterface $language_manager, CacheBackendInterface $cache) {
$this->pathAliasRepository = $alias_repository;
$this->languageManager = $language_manager;
$this->whitelist = $whitelist;
$this->cache = $cache;
}
The classes that implement create(ContainerInterface $container)
and which implement ContainerInjectionInterface
, for example the CronForm
class, don't return a closure from create(ContainerInterface $container)
; they actually only return an instance of themselves. See CronForm::create()
.
public static function create(ContainerInterface $container) {
return new static($container->get('config.factory'),
$container->get('state'),
$container->get('cron'),
$container->get('date.formatter'),
$container->get('module_handler')
);
}
If you want to implement a factory service in Drupal, you should take the cache_factory service as example to write your code.
cache_factory:
class: Drupal\Core\Cache\CacheFactory
arguments:
- '@settings'
- '%cache_default_bin_backends%'
calls:
- [setContainer, ['@service_container']]
A service that uses that service as factory is, for example, the cache.render service.
cache.render:
class: Drupal\Core\Cache\CacheBackendInterface
tags:
- { name: cache.bin }
factory:
- '@cache_factory'
- get
arguments:
- render
The factory key defines which service is the factory service and which method is called for that factory service; the arguments key define the arguments passed to that method. In this case, it's telling Drupal to instantiate the cache.render service by instantiating the cache_factory service and calling get('render')
on that object.