我对 Symfony2 还很陌生,并且已经构建了一个自定义 CMS,其中包含用户管理、页面管理、图像库等各个部分。我想记录 CMS 中的所有事件,因此认为最好创建一个集中的类来存储事件,以便我可以从任何部分调用它。
我一直在研究依赖注入(inject)和服务容器,但很难找出区别是什么?如果有的话?
我已经设置了以下服务,但希望获得有关这是否是最佳方法的反馈:
# app/config/config.yml
# AdminLog Configuration
services:
admin_log:
class: xyz\Bundle\CoreBundle\Service\AdminLogService
arguments: [@doctrine.orm.entity_manager]
下面是我的类(class):
<?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 内的任何 Controller 调用此函数:
$this->get('admin_log')->logActivity('Website', 'index', 'Test', 'Note here...');
- 这是最好的方法吗?
- 该类是否应该像我一样位于包内的“Service”目录中?
- DependencyInjection 文件夹有什么用?
谢谢
最佳答案
依赖指令意味着您将对象传递到类中,而不是在类中初始化它。服务容器是一个类,可帮助您管理所有这些服务(具有依赖关系的类)。
您的问题:
Is this the best method?
是的,除了命名空间。
Should the class be inside a 'Service' directory within the bundle as I have done?
不,它可以存在于任何命名空间中。您应该将其放在逻辑命名空间中,例如 MyBundle\Logger
。
What is the DependencyInjection folder for?
它适用于 3 种类型的类:扩展
、配置
和编译器 channel 。
关于class - Symfony2 依赖注入(inject)/服务容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16570815/