2013-05-15 153 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

是的,我喜欢那样。 –