PHP v8 supports constructor property promotion, which greatly uses boilerplate code. But basically all Drupal services use a factory pattern with a __construct()
and a create()
function.
Is the create()
still necessary when using constructor property promotion? I've been searching in contrib modules for MR which use the new constructor property, and I've seen both, services with and without create function.
So given this YAML file
services:
my_module.helper:
class: Drupal\my_module\Helper
arguments: ['@request_stack', '@entity_type.manager', '@config.factory', '@current_user', '@logger.factory']
and this service class constructor
public function __construct(
protected RequestStack $requestStack,
protected EntityTypeManagerInterface $entityTypeManager,
protected ConfigFactoryInterface $configFactory,
protected AccountInterface $currentUser,
protected LoggerChannelFactoryInterface $loggerFactory
) {}
do I still need a create($container)
function (with all the redundant $container->get(...)
calls inside it) at all?
If I don't need a create()
function, can I somehow pass arguments to the other factories used inside my own service? E.g. loggers and configs are often used in my service, and I don't want to write
$this->configFactory->get('my_module)->get('foo');
$this->loggerFactory->get('my_module)->error('bar');
all the time. Can I somehow tell the logger and config factories to use my module name to write shorter code like
$this->config->get('foo');
$this->logger->error('bar');
create()
function. What is the trick to avoid the redundantfunction create() { $container->get('service') }
bloat?