2

我是 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...');
  1. 这是最好的方法吗?
  2. 该类是否应该像我所做的那样位于捆绑包中的“服务”目录中?
  3. DependencyInjection 文件夹有什么用?

谢谢

4

1 回答 1

3

Dependency Inction 意味着您将对象传递到类中,而不是在类中对其进行初始化。服务容器是一个类,它可以帮助您管理所有这些服务(具有依赖关系的类)。

你的问题:

这是最好的方法吗?

是的,除了命名空间。

该类是否应该像我所做的那样位于捆绑包中的“服务”目录中?

不,它可以存在于任何命名空间中。您应该将它放在一个逻辑命名空间中,例如MyBundle\Logger.

DependencyInjection 文件夹有什么用?

它适用于 3 种类型的类:ExtensionConfigurationCompiler 通行证。

于 2013-05-15T17:00:09.553 回答