symfony 中的自动装配字符串参数 [英] Autowire String parameter in symfony
问题描述
如何在 Symfony 3.4 中连接字符串参数?
我有一个简单的服务,我想连接在 parameters.yml
中指定的 url
参数:
命名空间 AppBundle\Service;使用 Psr\Log\LoggerInterface;类 PythonService {私人 $logger;私人 $url;/*** @param LoggerInterface $logger* @param String $url*/公共函数 __construct(LoggerInterface $logger, String $url) {$this->logger = $logger;$this->url = $url;}}
我的 service.yml
看起来像:
AppBunde\Services\PythonService:参数:['@logger', '%url%']
但我收到错误:
无法自动装配服务AppBundle\Service\PythonService":方法__construct()"的参数$url"是类型提示的string",您应该明确配置其值.
我也试过手动指定参数:
AnalyticsDashboardBunde\Services\PythonService:论据:$logger: '@logger'$url: '%session_memcached_host%'
这给了我以下错误:
无效服务AppBundle\Services\PythonService":类AppBundle\Services\PythonService"不存在.
首先,您在 AppBundle\Services\PythonService
(Services <> Service) 中有一个拼写错误.
然后,字符串 <> 字符串.php 中没有大写.
<小时>您可以将参数绑定到某个参数/服务:
service.yml:
服务:_默认值:绑定:$memcacheHostUri: '%session_memcached_host%'
服务类:(必须与指定的 var 名称相同 ^)
public function __construct(LoggerInterface $logger, string $memcacheHostUri)
控制器操作:
公共函数 myAwesomeAction(PythonService $pythonService){$pythonService->doPythonStuffs();}
使用此解决方案,如果您创建其他需要 memecacheHostUri
的服务,它也会为这些服务自动装配.
资源:
参数绑定>
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.
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:
这篇关于symfony 中的自动装配字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!