我有实体:Menu和TypeMenu。在菜单中是方法
public function setTypeId(\Cms\AdminBundle\Entity\TypMenu $typeId = null)
{
$this->type_id = $typeId;
return $this;
}
当我添加新记录时,我必须在参数中给出方法setTypeId,structure。
$Menu = new Menu();
...
$TypMenu=$em->getRepository('CmsAdminBundle:TypMenu')->findOneById($form->get('typmenu_id')->getData());
$Menu->setTypeId($TypMenu);
很累人。在类菜单中,我想创建函数,它将执行它。
public function setTypeMenu($id){
$TypMenu=$em->getRepository('CmsAdminBundle:TypMenu')->findOneById($id);
return $this->setTypeId($TypeMenu);
}
我读到实体中的学说不是最优的。
我如何实现它?
抱歉我的英文。
答案 0 :(得分:0)
让自己成为一个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的章节。
答案 1 :(得分:0)
不建议从这样的存储库请求整个实体,如果你不使用你最好使用的TypMenu实体的任何字段,它会毫无理由地获取资源:
$Menu->setTypeId($em->getReference('CmsAdminBundle:TypMenu', $id));
这是最佳的,我不知道更好的方法,如果你没有使用TypMenu的任何数据,请不要使用存储库使用参考。