加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 17:39:41 所属栏目:PHP教程 来源:网络整理
导读:在持久化实体之前,我需要在我的数据库的另一个表中复制和格式化一些数据.我希望此任务作为服务执行. 所以我在config.yml中描述了这个服务 services:my_service: class: AcmeBundleAcmeBundleDependencyInjectionsMyService arguments: entityManager: "@
在持久化实体之前,我需要在我的数据库的另一个表中复制和格式化一些数据.我希望此任务作为服务执行.
所以我在config.yml中描述了这个服务

services:
my_service:
    class: AcmeBundleAcmeBundleDependencyInjectionsMyService
    arguments: 
      entityManager: "@doctrine.orm.entity_manager"

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

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

这是最好的方法吗?

解决方法

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

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

services:
    my_service:
        class: AcmeBundleAcmeBundleDependencyInjectionsMyService
        arguments: 
           entityManager: "@doctrine.orm.entity_manager"
        tags:
            - { name: doctrine.event_listener,event: prePersist }

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

use DoctrineORMEventLifecycleEventArgs;

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

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

最后,你有这个听众

services:
    my_service:
        class: AcmeBundleAcmeBundleDependencyInjectionsMyService
        tags:
            - { name: doctrine.event_listener,event: prePersist }

我希望这能回答你的问题

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读