when trying to use a service in drupal actually there is 3 ways , what is the preferred way to use a service and why :
passing dependencies directly through the constructor:
public function __construct(AccountProxyInterface $current_user) { }
passing the dependencies through the
create()
method wich look to me the same as injecting it through the__construct()
, with the only difference , an instance will be created eah time (no singleton design pattern - not same instance will be reused)
public static function create(ContainerInterface $container) { //1.getting service from the service container. $Door = $container->get('custom_service.door'); //2.create a new object of current class, and Inject the dependency object into the constructor return new static($Door); } //constructor receive the dependency set by the create() method public function __construct(Door $Door) { kint($Door); }
- just get get the service from the service container and no need to inject it using :
$Door = \Drupal::service('custom_service.door')
\Drupal::service...
is largely used from procedural code when not in an OOP context.