2016-11-30 58 views
0

由於我使用某些類的方式,我無法進行服務注入,但我需要訪問其中的服務容器。在控制器外部訪問容器但無法注入服務

namespace DocumentsUploadSystem; 

use Symfony\Component\DependencyInjection\ContainerAwareInterface; 
use Symfony\Component\DependencyInjection\ContainerAwareTrait; 

class DocumentsUpload implements ContainerAwareInterface 
{ 
    use ContainerAwareTrait; 

     public function getData() 
    { 
     var_dump($this->container); 
    } 

} 

如果我像這樣從控制器調用此方法。

use DocumentsUploadSystem\DocumentsUpload 
... 

$x = new DocumentsUpload($request)->getData(); 

和我沒有得到任何錯誤,但容器回來爲空。這是實施ContainerAwareInterface的錯誤方法嗎?我正在使用Symfony 3.1

+0

解釋如何使用某些類與您一起做無法進行服務注入。原則上,服務注入總是可能的。 – inaliahgle

+0

,因爲我在控制器中將這些類實例化爲一個變量,並使用__construct將變量傳遞給這些類。 – user1529918

回答

0

實現接口不會執行任何操作。接口是類的構建者和類的用戶之間的一種保證某些方法存在的合同 - 就是這樣。在這種情況下,ContainerAwareInterface保證setContainer()方法可用。然後您必須USE它爲了設置您的容器。

// MyController extends Symfony\Bundle\FrameworkBundle\Controller\Controller 
use DocumentsUploadSystem\DocumentsUpload 
... 

$x = new DocumentsUpload($request); 
$x->setContainer($this->container); 
$xData = $x->getData(); 

爲了記錄,我不建議注入整個容器 - 只有完成您的任務所需的實際服務。

KnpMenuBundle這樣的庫似乎正在使用這個,但實際上它們會自動創建菜單併爲您注入容器。見https://github.com/KnpLabs/KnpMenuBundle/blob/master/Provider/BuilderAliasProvider.php#L122-L124

祝好!

+0

但有沒有辦法在不注入的情況下訪問類中的容器? – user1529918

+1

沒有。你不能訪問你沒有放在那裏的東西。 – craigh

+0

詛咒你可以在不注入的情況下訪問容器。但如何做到這是一個很大的祕密。即使您搜索「訪問控制器外部的容器」,即使谷歌也不會給你答案。我認爲這是分類或什麼的。 – Cerad

0

但在這個例子中[https://symfony.com/doc/current/bundles/KnpMenuBundle/index.html]他們使用相同的技術和訪問容器罰款,它在那裏工作,是服務調用其他地方呢?

// src/AppBundle/Menu/Builder.php 
namespace AppBundle\Menu; 

use Knp\Menu\FactoryInterface; 
use Symfony\Component\DependencyInjection\ContainerAwareInterface; 
use Symfony\Component\DependencyInjection\ContainerAwareTrait; 

class Builder implements ContainerAwareInterface 
{ 
    use ContainerAwareTrait; 

    public function mainMenu(FactoryInterface $factory, array $options) 
    { 
     $em = $this->container->get('doctrine')->getManager(); 
    } 
} 
+0

這是可行的,因爲KnpMenuBundle自動創建菜單併爲您注入容器。看到https://github.com/KnpLabs/KnpMenuBundle/blob/master/Provider/BuilderAliasProvider.php#L122-L124 – craigh

+0

好的,這是有道理的。謝謝你,這段代碼實際上幫了我很多。 – user1529918

+0

我已經更新了我的答案。你會很高興接受它。謝謝。 – craigh