Php Symfony2服务等级。函数调用
我有这样的服务:Php Symfony2服务等级。函数调用,php,symfony,Php,Symfony,我有这样的服务: services: prodacom_authentication.encode: class: Prodacom\AuthenticationBundle\Service\Encode arguments: ["@security.context"] 我要在控制器中调用的服务函数: public function encodePassword() { $factory = $this->get('security.encod
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()
仅在控制器上下文中可用
您可以在官方文档中找到完整的示例:
注意:您必须在注入中传递所需的每个服务或参数。
注入容器以调用其他服务似乎更容易,但这是一种不好的做法。问题出现在方法的第二行,您可以在其中调用:
$this->get('security.encoder\u factory')
在您的服务中,如果您自己没有实现方法get()
,则不会定义该方法。您的控制器拥有它,因为它扩展了一个名为containerware
的类,该类实现了此方法
现在,您可以将完整的依赖项容器(不推荐)注入,也可以只将所需的服务注入到服务中。下面列出了可用于将服务注入服务的各种方法:
我看到你已经熟悉构造函数注入…如果你想在你的服务中使用
->get(“”)
,你必须将容器
服务传递给它。