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
是的,我喜欢那样。 –