我有这样的服务:
services:
prodacom_authentication.encode:
class: Prodacom'AuthenticationBundle'Service'Encode
arguments: ["@security.context"]
我想在控制器中调用的服务功能:
public function encodePassword() {
$factory = $this->get('security.encoder_factory');
$user = new Prodacom'MainBundle'Entity'PdbUser();
$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword('ryanpass', $user->getSalt());
var_dump($password);
$user->setPassword($password);
}
我想调用authenticationController.php.中的encodePassword函数
$this->get('prodacom_authentication.encode')->encodePassword();
但我一直收到这个错误:
Attempted to call method "get" on class "Prodacom'AuthenticationBundle'Service'Encode" in C:'htdocs'domeinbeheer'src'Prodacom'AuthenticationBundle'Service'Encode.php line 12.
有什么想法吗???
问题出现在方法的第二行,您调用:$this->get('security.encoder_factory')
在您的服务中,如果您自己没有实现方法get()
,则不会定义该方法。您的控制器有它,因为它扩展了一个名为ContainerAware
的类,实现了这个方法。
现在,您可以注入完整的依赖容器(不推荐),也可以将所需的服务注入到服务中。以下是可用于将服务注入服务的不同方法列表:http://symfony.com/doc/current/components/dependency_injection/types.html
我看到你已经熟悉构造函数注入。。。
如果你想在另一个服务中使用一个服务,你必须使用依赖注入。
$this->get()
仅在控制器上下文中可用。
您可以在官方文档中找到完整的示例:http://symfony.com/doc/2.3/components/dependency_injection/introduction.html
注意 :您必须在注入中传递所需的每个服务或参数。注入容器来调用其他服务似乎更容易,但这是一种糟糕的做法。