2

Most classes are instantiated using create($container) and __construct(...$services) in conjunction, it seems that the more efficient workflow would be to simply pass the container to the constructor __construct($container) and not have the create method at all. Is this inherited from Symfony? What purpose does it serve?

  • 3
    This is not inherited from Symfony. Drupal introduced this factory pattern to instantiate non service classes like controllers and plugins. – 4k4 Jan 20 at 23:38
  • Check out the static keyword for more details. – Kevin Jan 21 at 1:22
  • I'm not asking how it works. I'm asking what its benefits are. So far the only explanation I've found is that it makes testing easier, but testing without it is also easy. – Charles Bamford Jan 21 at 1:40
  • This is a question about drupal theory, explicitly in scope in the help center. – Charles Bamford Jan 21 at 16:36
  • The Help Center also says that questions should be reasonably scoped. Any too-broad question is off-topic, even if the argument is on-topic. – kiamlaluno Jan 22 at 12:35
1

The create() __construct() pattern does make testing easier, but not by much. A new container can be very easily generated and populated with the required services for unit testing.

1

Just my two cents: If you use such a system it is not needed to set the required services in a service.yml but you can easily set, overlook and check the services in the class itself - in the create() method, where you define all the services. I find this more comfortable than writing everything in a YAML file

Not the answer you're looking for? Browse other questions tagged or ask your own question.