简体   繁体   English

Symfony2中的服务

[英]Services in Symfony2

I'm trying to get some service (eg session) from outside of controller. 我正在尝试从控制器外部获取一些服务(例如会话)。

Please, explain how to do this right-way. 请说明如何正确执行此操作。

There are many different ways, all having pros and cons. 有很多不同的方式,各有利弊。

First, every service is some kind of object, so you can always just create the object in question yourself. 首先,每个服务都是某种对象,因此您始终可以自己创建有问题的对象。 You may be forced to deal with many references, but it's possible. 您可能被迫处理许多参考,但这是可能的。 This undermines the idea of Dependency Injection, so it's not what you should do! 这破坏了依赖注入的想法,所以这不是您应该做的!

The second way is inject the service into your class: 第二种方法是将服务注入您的类中:

class MyClass{

    public function __construct($session){
        // ...
    }
}

class MyContainer extends Controller{

    public function SomeKindOfAction(){
        $myClass = new MyClass($this->get('session'));
    }
}

This might be ok if you only use the class within your Controller. 如果仅在Controller中使用该类,则可能没问题。 If you have more nested relations, like in MyClass, you create another class where you need the session, you might run into tight coupling (which is to avoid) as well as complexity issues. 如果您有更多的嵌套关系,例如在MyClass中,则在需要会话的地方创建另一个类,则可能会遇到紧密耦合(这是可以避免的)以及复杂性问题。

The best way is to create your own service and injecting the things you need there. 最好的方法是创建自己的服务并将所需的东西注入那里。 There are many documentations out there, so I'll just give a short example using MyClass above. 那里有很多文档,因此我仅在上面使用MyClass给出一个简短示例。

services.yml:

services:
    my.myClass:
        class: /Acme/DefaultBundle/MyStuff/MyClass
        arguments: ["@session"]

Now your Class is as service (who would guess it's that easy!) and you can use it within your controller: 现在您的类即服务(谁会猜到那很简单!),您可以在控制器中使用它:

class MyContainer extends Controller{

    public function SomeKindOfAction(){
        $myClass = $this->get('my.myClass');
    }
}

Now you don't have to think about constructor and how to get your objects, the DI-Container will do it for you. 现在,您无需考虑构造函数以及如何获取对象,DI容器将为您完成。 If you want to know more, read here . 如果您想了解更多,请在这里阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM