php – Symfony2中依赖注入的最佳实践

在持久化实体之前,我需要在我的数据库的另一个表中复制和格式化一些数据.我希望此任务作为服务执行.
所以我在config.yml中描述了这个服务

services:
my_service:
    class: Acme\Bundle\AcmeBundle\DependencyInjections\MyService
    arguments: 
      entityManager: "@doctrine.orm.entity_manager"

我想知道拨打这项服务的最佳方式.我能弄清楚的唯一方法是来自控制器:

$entity = new Entity($this->get('my_service'));

这是最好的方法吗?

解决方法:

如果我的理解是好的,那么在坚持您的实体之前,您的服务my_service就是您想要做的事情.这是一项必须由prePersist活动触发的服务.

所以,我只是将这个服务转换为一个学说倾听者.

services:
    my_service:
        class: Acme\Bundle\AcmeBundle\DependencyInjections\MyService
        arguments: 
           entityManager: "@doctrine.orm.entity_manager"
        tags:
            - { name: doctrine.event_listener, event: prePersist }

在MyService类中,您现在可以使用您想要执行的所有操作来定义prePersist方法.

use Doctrine\ORM\Event\LifecycleEventArgs;

class MyService
{
     public function prePersist(LifecycleEventArgs $args)
     {
         $entity = $args->getEntity();
         $entityManager = $args->getEntityManager();
         (...)
    }
}

您甚至可以删除服务的参数,因为LifecycleEventArgs提供了获取实体管理器的方法.

最后,你有这个听众

services:
    my_service:
        class: Acme\Bundle\AcmeBundle\DependencyInjections\MyService
        tags:
            - { name: doctrine.event_listener, event: prePersist }

我希望这能回答你的问题

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...