services.yml
:
parameters:
uasector.user.abstract_social_network_provider.class: Uasector\UserBundle\UserProvider\AbstractSocialNetworkProvider
services:
uasector_user.uasector_abstract_user_data_service:
class: %uasector.user.abstract_social_network_provider.class%
arguments: ['@service_container', '%kernel.root_dir%', '%uasector_user.image.upload_directory%', '%uasector_user.image.default_avatar_path%']
AbstractSocialNetworkProvider.php
:
public function __construct(Container $container, $kernelWebDir, $uploadDir, $defaultAvatarPath) //Container $container, $kernelWebDir, $uploadDir, $defaultAvatarPath
{
}
错误:
ContextErrorException: Catchable Fatal Error: Argument 1 passed to Uasector\UserBundle\UserProvider\AbstractSocialNetworkProvider::__construct() must be an instance of Symfony\Component\DependencyInjection\Container, none given, called in /Users/roman/Development/Sites/uasector.dev/app/cache/dev/appDevDebugProjectContainer.php on line 6117 and defined in /Users/roman/Development/Sites/uasector.dev/src/Uasector/UserBundle/UserProvider/AbstractSocialNetworkProvider.php line 35
为什么AbstractSocialNetworkProvider::__construct()
不接受Container $container
?
答案 0 :(得分:1)
构建类时不会构建容器。要注入容器,你应该使用类似的设置器。
你的班级。
use Symfony\Component\DependencyInjection\ContainerInterface;
class AcmeClass
{
...
protected $container;
public function __construct(...)
{
...
}
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
}
您的服务。
parameters:
uasector.user.abstract_social_network_provider.class:
Uasector\UserBundle\UserProvider\AbstractSocialNetworkProvider
// Split to 2 lines for readability
services:
uasector_user.uasector_abstract_user_data_service:
class: %uasector.user.abstract_social_network_provider.class%
arguments:
- '%kernel.root_dir%'
- '%uasector_user.image.upload_directory%'
- '%uasector_user.image.default_avatar_path%'
// These are called after construction before before you actually use it
calls:
- [ setContainer, [ @service_container ]]
注意强>
据说通常更好(如果可能的话)将您需要的特定服务注入到您的服务中,以避免与服务容器紧密耦合,并且它还可以使事情更加明显。一瞥(即,当您查看服务定义/ __构造时,您可以看到正在注入的内容,而不是必须通过整个班级来查找您使用$this->container->get()
调用的内容)。