Reputation: 538
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.
Upvotes: 8
Views: 15731
Reputation: 1879
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:
Upvotes: 25
Reputation: 639
// services.yml
app.python_service:
class: AppBundle\Service\PythonService
arguments:
$logger: '@monolog.logger.request'
$url: 'link'
public: true
// in controller
//use container:
$pS = $this->container->get('app.python_service');
Upvotes: 0