2014-09-11 28 views
2

我想通過下面的實體訪問服務容器,但是如何實現?注入或訪問實體對象內的服務容器

檢查了這一點,但是當我正在讀聽者時,我迷了路;

控制器

public function indexAction() 
{ 
    $orders = $this->getDoctrine()->getManager()->getRepository('MyAdminBundle:Orders')->findAll(); 
    ..... 
} 

實體

namespace My\AdminBundle\Entity; 

class Orders 
{ 
    private $container; 

    public function __constructor() 
    { 
     $this->container = ?????? 
    } 

    public function getCurrency() 
    { 
     return $this->container->getParameter('currency'); 
    } 
} 

回答

6

@修正是正確的,你不應該注入到實體的容器。在你的情況下,你可能會這樣做:

// Controller 
$order = ...find($orderId); 
$currency = $this->getContainer()->getParameter('currency'); 
$price = $order->calculatePrice($currency); 

因此,貨幣作爲方法參數傳遞。

我完全理解這是一個困難的概念,特別是如果用於活動記錄和大量的全局變量。但最終它會有意義併產生更好的代碼。

但是,只要您不卡住,我會向您透露從任何地方訪問容器的祕密。原來應用程序內核是一個全局變量。所以:

class Orders 
{ 
    public function getCurrency() 
    { 
     global $kernel; 
     $container = $kernel->getContainer(); 
     return $container->getParameter('currency'); 
    } 
+0

'global $ kernel;'正是我想要的:)謝謝 – BentCoder 2014-09-11 21:03:28

1

the link you shared解釋:An entity is a data model and should only hold data (and not have any dependencies on services)。然後,你應該找到另一種乾淨的方式來做你想做的事情。

根據您的代碼,可能會認爲currency的值是在您的配置中定義的(除非您以其他方式將其注入到container中)。這絕對是不相關將其限制到您的實體之一。

+0

問題是我該怎麼做呢?有沒有你知道的例子,以便我可以穿過? – BentCoder 2014-09-11 09:25:49

+0

使用貨幣作爲配置參數,(如果需要,將其注入到服務中,...等)。這裏的問題是你爲什麼認爲你需要將它添加到你的實體?什麼是用例? – 2014-09-11 09:31:30

+0

我有一些數據存儲在一個app/config/site_globals.yml中,需要在上面的實體中讀取。這是完整的目的。 – BentCoder 2014-09-11 09:52:19