从服务中调用帮助程序

时间:2016-04-09 16:01:40

标签: symfony

我想从我的服务中打电话给他们。

$notificationService = $this->get('Notification');
  

尝试调用名为“get”的类

的未定义方法

1 个答案:

答案 0 :(得分:3)

Symfony不是魔术。 Symfony只是PHP。这是与Symfony合作时最重要的事情。

因此,如果您的班级中没有get()方法,则无法调用该方法。在您的控制器中,您从FrameworkBundle的基础Controller扩展。这个类确实包含这样的方法,所以在控制器中你可以调用这个方法。

现在,您仍希望在新服务中使用Notification服务。而不是从容器中获取容器,让容器在创建它时将其注入您的服务中。您可以使用某些服务配置执行此操作:

# app/config/services.yml
services:
    app.your_service:
        class: AppBundle\Some\Class
        arguments: ['@Notification'] # <<-- this tells to inject the service

然后在课堂上进行调整:

class SomeClass
{
    private $nofication;

    public function __construct(NotificationInterface $notification)
    {
        $this->notification = $notification;
    }
}

还有很多要解释的内容。见http://symfony.com/doc/current/book/service_container