2013-05-15 146 views
2

我是Symfony2的新手,已經構建了一個包含用戶管理,頁面管理,圖像庫等各個部分的自定義CMS。我想記錄CMS內的所有活動,因此認爲最好創建一個集中的類來存儲活動,以便我可以從任何部分調用它。Symfony2依賴注入/服務容器

我一直在看依賴注入和服務容器,但努力弄清楚是什麼區別是什麼?如果有的話?

我設置了以下服務,但想上,如果這是最好的方法反饋:

# app/config/config.yml 
# AdminLog Configuration 
services: 
    admin_log: 
     class:  xyz\Bundle\CoreBundle\Service\AdminLogService 
     arguments: [@doctrine.orm.entity_manager] 

下面是我的課:

<?php 
namespace xyz\Bundle\CoreBundle\Service; 
use xyz\Bundle\CoreBundle\Entity\AdminLog; 

class AdminLogService 
{ 
    protected $em; 

    public function __construct(\Doctrine\ORM\EntityManager $em) 
    { 
     $this->em = $em; 
    } 

    public function logActivity($controller, $action, $entityName, $note) 
    { 
     $adminLog = new AdminLog(
      1, 
      $controller, 
      $action, 
      $entityName, 
      $note 
     ); 
     $this->em->persist($adminLog); 
     $this->em->flush(); 
    } 

} 

那麼我就要從任何控制器調用此在CMS內使用以下內容:

$this->get('admin_log')->logActivity('Website', 'index', 'Test', 'Note here...'); 
  1. 這是最好的方法嗎?
  2. 像我這樣做過,該類是否應該在bundle中的'Service'目錄中?
  3. 什麼是DependencyInjection文件夾?

感謝

回答

3

依賴Inction意味着你傳遞對象爲一類,而不是在類初始化。 Service Container是一個幫助您管理所有這些服務(具有依賴性的類)的類。

您的問題:

這是最好的方法是什麼?

是的,命名空間除外。

這個類應該像我一樣在bundle中的'Service'目錄中嗎?

不,它可以存在於任何命名空間中。你應該把它放在一個邏輯命名空間中,比如MyBundle\Logger

什麼是DependencyInjection文件夾?

這是3種類型的代碼:Extension,Configuration和編譯器通行證。

+0

服務只是放在服務容器中的正常claasea。所以你應該把它作爲普通的類來處理,因此你應該把它們放在一個描述性的命名空間 –

+0

OK你能舉個例子來證實嗎? xyz \ Bundle \ CoreBundle \ Logger是否合適? – user1961082

+0

是的,我喜歡那樣。 –