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...');
- 這是最好的方法嗎?
- 像我這樣做過,該類是否應該在bundle中的'Service'目錄中?
- 什麼是DependencyInjection文件夾?
感謝
服務只是放在服務容器中的正常claasea。所以你應該把它作爲普通的類來處理,因此你應該把它們放在一個描述性的命名空間 –
OK你能舉個例子來證實嗎? xyz \ Bundle \ CoreBundle \ Logger是否合適? – user1961082
是的,我喜歡那樣。 –