2012-04-26 71 views
2

我已經創建了我的包內一個簡單的類使用的容器一個簡單的捆綁類中:中的Symfony 2中的Symfony 2

class MyTest { 
    public function myFunction() { 
     $logger = $this->get('logger'); 
     $logger->err('testing out'); 
    } 
} 

如何訪問容器?

回答

11

你需要注入的服務容器。您的類將看看這個:

use Symfony\Component\DependencyInjection\ContainerInterface; 

class MyTest 
{ 
    private $container; 

    public function __construct(ContainerInterface $container) 
    { 
     $this->container = $container; 
    } 

    public function myFunction() 
    { 
     $logger = $this->container->get('logger'); 
     $logger->err('testing out'); 
    } 
} 

然後,控制器或ContainerAware實例中:

$myinstance = new MyTest($this->container); 

如果你需要更多的解釋:http://symfony.com/doc/current/book/service_container.html

+0

我無法注入容器,因爲我創建的類是內核事件偵聽器。 http://symfony.com/doc/current/book/internals.html#kernel-exception-event – vinnylinux 2012-04-26 22:47:45

+1

在幾乎所有情況下注入整個容器都是一個壞主意。 – 2012-04-27 05:21:02

+0

@vinnylinux:活動聽衆可以註冊爲服務 – 2012-05-03 19:08:11

1

檢查this article,並使用@container

+0

這篇文章教你如何創建一個可以由控制器稱爲服務,而不是如何從我的類中調用服務。 – vinnylinux 2012-04-26 22:32:59

+0

http://symfony.com/doc/current/book/service_container.html#referencing-injecting-services – nucleartux 2012-04-26 22:35:13

+0

在大多數情況下,您應該只注入所需的服務,而不是整個服務容器。 – simshaun 2012-04-26 22:39:44

3

爲什麼不加僅@logger服務? e.g

arguments: [@logger] 

如果你想添加的容器(不推薦),那麼您可以在services.yml添加@service_container

+0

我已經添加了記錄器,但它沒有奏效。 – vinnylinux 2012-04-26 22:57:38

+0

嘗試添加[自定義日誌記錄通道](http://symfony.com/doc/current/reference/dic_tags.html#using-a-custom-logging-channel-with-monolog)。 – 2012-04-26 23:09:19

6

在大多數情況下注入整個容器是一個壞主意。單獨注入所需的服務。

namespace Vendor; 

use Symfony\Component\HttpKernel\Log\LoggerInterface; 

class MyTest 
{ 
    private $logger; 

    public function __construct(LoggerInterface $logger) 
    { 
     $this->logger = $logger; 
    } 

    public function myFunction() 
    { 
     $logger->err('testing out'); 
    } 
} 

services.yml註冊服務:

services: 
    my_test: 
     class: Vendor\MyTest 
     arguments: [@logger]