K
K
Kirill Nesmeyanov2016-05-13 12:32:08
symfony
Kirill Nesmeyanov, 2016-05-13 12:32:08

How to call a method in Symfony with autowire'ing?

Good day dear!
The question is already in the title. How to call a method through a container?

<?php
class Some
{
    public function any(DependencyA $a, DependencyB $b)
    {
        // do something
    }
}

// Вызов
// service.name должен быть зарегистрированным в services.yml
$instance = $container->get('service.name'); 

// А дальше?

Similar example in Laravel 5+:
<?php
class Some
{
    public function any(DependencyA $a, DependencyB $b, $some)
    {
        // do something
    }
}

// Вызов
// Получение инстанса из контейнера (аналогично вызову $container->get('service.name') в симфони )
$instance = $container->make(Some::class);

// Все аргументы из контейнера 
// т.е. $a и $b, срабатывает автоматический автовайринг для неуказанных аргументов
// кроме $some - он указывается явно во время вызова
$container->call([$instance, 'any'], [ 'some' => 42 ]);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Radik_Wind, 2016-05-14
@Radik_Wind

In order for your services to comply with Symfony best practices, dependencies must be passed to them in the following way:
- in the constructor, for those dependencies without which your service will not work, for example, data source or something similar
- in dependency setters without which your service will work, but some part of non-core functionality will not be available, for example, logging
- well, you don’t need to transfer the container itself as dependencies, some developers sin with this, especially when the service has many dependencies, if you have such a need, it’s worth splitting the service into several smaller self-contained services with a minimum of dependencies

V
voronkovich, 2016-05-13
@voronkovich

In the Symfony container, the case described for Laravel will not work.
Do it without autowiring. Or add setters for dependencies, then the container will inject them automatically:

<?php
class Some
{
    public function setDependencyA(DependencyA $a)
    {
        $this->dependencyA = $a;
    }

    public function any()
    {
         $this->dependencyA->someMethod();
          // do something 
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question