dousui6193 2012-07-10 14:50
浏览 74
已采纳

从Symfony DI组件获取新的实体实例

I'm having a little trouble understanding how to implement best DI practices in this scenario.

I have a ZF1 project with the Symfony2 DI container implemented. All my service classes etc are created through the DI container and i'm now refactoring the dependencies of my service classes themself. So far so good but now I've stumbled upon a problem where I need to create X instances of a Doctrine Entity, yet I don't know how to abstract the dependency out of the service class into the container. It isn't a real single class instance so it can't be injected at construction time.

There are several scenario's that come to mind and i'm looking for advice what is the preferred road to take.

  1. Get a reference to the DI container and fetch new instances from it whenever needed, this has the disadvantage that now my Service class will depend on the DI container which imho is fixing evil with more evil.

  2. Call a factory, I've read about the factory implementation in the symfony DI container but fail to see how this could help me. Maybe I'm missing something?

  3. Injecting the entity className and instantiating the instance dynamically. Thus instead of doing new \My\Entity() doing new $this->entityClass, this smells too to be honest but could work.

  4. ??

Can anyone tell my how these scenario's are commonly solved using the symfony2 DI container?

  • 写回答

1条回答 默认 最新

  • dou11655853 2012-07-10 17:39
    关注

    You shouldn't need to inject anything into a service class to create entities other than the entity manager itself.

    Because unless I misunderstand you, you're just talking about importing the proper namespace and doing the whole

    $e = new Entity();
    $em->persist( $e );
    $em->flush();
    

    dance. No?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab