在实体中查询的 Symfony2 方法

Symfony2 method with query in entity

我有实体:Menu 和 TypeMenu。在菜单中是方法

public function setTypeId(\Cms\AdminBundle\Entity\TypMenu $typeId = null)
    {
        $this->type_id = $typeId;

        return $this;
    }

当我添加一条新记录时,我必须在参数中给出方法setTypeId,结构。

$Menu = new Menu();
...
$TypMenu=$em->getRepository('CmsAdminBundle:TypMenu')->findOneById($form->get('typmenu_id')->getData());

$Menu->setTypeId($TypMenu);

很累。在 class 菜单中,我想创建功能,它会做到这一点。

public function setTypeMenu($id){
         $TypMenu=$em->getRepository('CmsAdminBundle:TypMenu')->findOneById($id);
         return $this->setTypeId($TypeMenu);
     }

我读到实体学说不是最优的。

如何实现?

对不起我的英语。

为自己创建一个 MenuFactory,注入必要的存储库,然后将创建代码移至其中。

// In a controller
$menuFactory = $this->get('menu.factory');
$menu = $menuFactory->createForTyp($typId);

// The factory
class MenuFactory
{
    $typMenuRepository;

    public function __construct($typMenuRepository)
    {
        $this->typMenuRepository = $typMenuRepository;
    }
    public createFromTypMenu($typId)
    {
        $menu = new Menu();
        $typMenu = $this->typMenuRepository->findOneById($typId);
        $menu->setTyp($typMenu);
        return $menu;
    }
}

// Wire it up in services.yml
services:
  typmenu.repository
    class Bundle\Entity\TypMenuRepository
    factory_service: 'doctrine.orm.entity_manager'
    factory_method:  'getRepository'
    arguments:  
        - 'Bundle\Entity\TypMenu'

  menu.factory:
    class: Bundle\MenuFactory
    arguments: ['@typmenu.repository]

一旦掌握了窍门,这些东西就会成为第二天性。 http://symfony.com/doc/current/book/service_container.html

我对你在问题中使用 $form 以及 typ_id 感到有点困惑。使用 Doctrine 2,你主要处理对象。您很少需要控制器级别的 ID。可能还想查看文档中有关 Doctrine 和 Forms 的章节。

不建议像这样从存储库中请求整个实体,如果您不使用最好使用的 TypMenu 实体的任何字段,它会无缘无故占用资源:

 $Menu->setTypeId($em->getReference('CmsAdminBundle:TypMenu', $id));

这已经是最佳选择了,我不知道还有什么更好的方法,如果您不使用 TypMenu 中的任何数据,请不要使用存储库,请使用参考。