我是 Symfony2 的新手,并且已经构建了一个自定义 CMS,其中包含用户管理、页面管理、图像库等各个部分。我想记录 CMS 中的所有活动,因此认为最好创建一个集中的类存储活动,以便我可以从任何部分调用它。
我一直在看依赖注入和服务容器,但很难弄清楚有什么区别?如果有的话?
我已经设置了以下服务,但想要反馈这是否是最好的方法:
# 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...');
- 这是最好的方法吗?
- 该类是否应该像我所做的那样位于捆绑包中的“服务”目录中?
- DependencyInjection 文件夹有什么用?
谢谢