G
G
gupovski2019-12-25 12:42:24
symfony
gupovski, 2019-12-25 12:42:24

Symfony 4 autowiring and inheritance?

What is the correct way to use autowiring in a child class?
There is an abstract class where some services are connected by autowiring, I'm trying to ensure that all services are loaded in the child class, but I still need to add a service dependency only for a specific class. When defining a constructor in a child class, autowiring breaks. When calling parent::__construct(), an error about missing parameters occurs. Tell me how this can be achieved?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Flying, 2019-12-25
@gupovski

Since you inherit your class from an abstract class, it is your responsibility to initialize parent (see footnote after the first paragraph). Thus, if an abstract class accepts its dependencies through a constructor, you need to accept them and pass them higher in the inheritance hierarchy.
Those. if the abstract class looks like:

abstract class AbstractExample 
{
  public function __construct(Foo $foo, Bar $bar) 
  {
  }
}

and you need an extra dependency Baz $baz, your constructor should look something like this:
class MyExample extends AbstractExample 
{
  public function __construct(Foo $foo, Bar $bar, Baz $baz) 
  {
    parent::__construct($foo, $bar);
    // ... и далее ваша логика ...
  }
}

E
Evgeny Romashkan, 2019-12-25
@EvgeniiR

1. Require in the constructor all dependencies necessary for the initialization of the parent. By inheriting, you undertake to initialize an instance of the parent class, to comply with the contract, judging by the question, you should pay attention to paragraph 2:
2. Getting rid of inheritance is better in all plans, in the vast majority (if not 100%) of situations.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question