Symfony2-如何使用从控制器外部访问服务 [英] Symfony2-How to use access a service from outside of a controller

查看:25
本文介绍了Symfony2-如何使用从控制器外部访问服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Symfony2 控制器中,这工作正常:

In my Symfony2 controller, this works fine:

$uploadManager = $this->get('upload.upload_manager');

但是当我将其移动到自定义侦听器时:

use Doctrine\ORM\Event\LifecycleEventArgs;
use Acme\UploadBundle\Upload\UploadManager;

class PersonChange
{
    public function postRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $entityManager = $args->getEntityManager();

        $uploadManager = $this->get('ep_upload.upload_manager');
        echo "the upload dir is " . $uploadManager->getUploadDir();
    }
}

我收到一个错误:

Fatal error: Call to undefined method Acme\MainBundle\Listener\PersonChange::get() in /home/frank/...

我知道我必须需要一个 use 语句,但不知道该使用什么.

I know I must need a use statement but don't know what to use.

推荐答案

更新:Symfony 不再正式推荐将控制器定义为服务.

Controller 类中的 get() 方法只是一个从容器中获取服务的辅助方法,它旨在让新的 Symfony2 开发人员跟上进度快点.一旦人们熟悉了框架和依赖注入,建议定义控制器作为服务并显式注入每个所需的服务.

The get() method in the Controller class is just a helper method to get services from the container, and it was meant to get new Symfony2 developers up to speed faster. Once people get comfortable with the framework and dependency injection, it's recommended to define controllers as services and inject each required service explicitly.

由于您的 PersonChange 类不是控制器并且不扩展 Controller 类,因此您没有那个 get()辅助方法.相反,您需要将您的类定义为服务并显式注入所需的服务.阅读服务容器章节了解详情.

Since your PersonChange class is not a controller and doesn't extend the Controller class, you don't have that get() helper method. Instead, you need to define your class as a service and inject needed services explicitly. Read the Service Container chapter for details.

这篇关于Symfony2-如何使用从控制器外部访问服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆