How can I wire a String parameter in Symfony 3.4?
I have simple service and I want to wire a url
parameter specified in parameters.yml
:
namespace AppBundle\Service;
use Psr\Log\LoggerInterface;
class PythonService {
private $logger;
private $url;
/**
* @param LoggerInterface $logger
* @param String $url
*/
public function __construct(LoggerInterface $logger, String $url) {
$this->logger = $logger;
$this->url = $url;
}
}
My service.yml
looks like:
AppBunde\Services\PythonService:
arguments: ['@logger', '%url%']
But I am getting error:
Cannot autowire service "AppBundle\Service\PythonService": argument "$url" of method "__construct()" is type-hinted "string", you should configure its value explicitly.
I tried also manually specify parameters:
AnalyticsDashboardBunde\Services\PythonService:
arguments:
$logger: '@logger'
$url: '%session_memcached_host%'
This gives me following error:
Invalid service "AppBundle\Services\PythonService": class "AppBundle\Services\PythonService" does not exist.
Autowiring is an exotic word that represents something very simple: the ability of the container to automatically create and inject dependencies. In order to achieve that, PHP-DI uses PHP's reflection to detect what parameters a constructor needs. Autowiring does not affect performances when compiling the container.
In Symfony, these useful objects are called services and each service lives inside a very special object called the service container. The container allows you to centralize the way objects are constructed. It makes your life easier, promotes a strong architecture and is super fast!
First, you have a typo in AppBundle\Services\PythonService
(Services <> Service).
Then, string <> String. No uppercase in php.
You can bind an argument to a certain parameter/service:
service.yml:
services:
_defaults:
bind:
$memcacheHostUri: '%session_memcached_host%'
Service class: (have to be the same var name as specified ^)
public function __construct(LoggerInterface $logger, string $memcacheHostUri)
Controller action:
public function myAwesomeAction(PythonService $pythonService)
{
$pythonService->doPythonStuffs();
}
With this solution, if you create others services which need the memecacheHostUri
, it will be autowired for these services too.
Resources:
Argument binding
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With