2016-08-02 54 views
0

我是symfony 2.8的新手。 我做同样的代码模式在我的每一个控制器来获得相同的数据,放在不同的看法,以下这种模式:Symfony集中代码

public function someMethod(Request $request){ 
    //1) instanciate entity manager 
    $em = $this->getDoctrine()->getManager(); 

    //2) Fetch some datas .. 
    $datas = $em->getRepository('MyCustomBundle:Entity')->findAll(); 
    $otherDatas = $em->getRepository('MyCustomBundle:AnotherEntity')->findAll(); 

    //3) Inject datas into view 
    return $this->render('MyCustomBundle:Views:myview.html.twig', array('data'=>$datas,'otherDatas'=>$otherDatas)); 
    } 

是否有可能因式分解所有getRepositories电话和阵列注入一个分隔的类?

感谢您的帮助,

+0

当然。熟悉依赖注入和服务http://symfony.com/doc/current/service_container.html。将您的存储库定义为服务并使用$ this-> get('my.repository') - > findAll()。接下来,考虑将您的控制器定义为服务,以便即使get也可以消失。很多其他的东西你也可以做。 – Cerad

回答

0

我不认为有Symfony方式。我更喜欢2),并将你的代码放在版本库中,然后在控制器中添加一些获取器。

  1. 使您从中继承的抽象控制器类。
  2. 我会做一些冗余代码。把你的版本库getter放入一个方法中。干净但多余。如果你有一些复杂的数据库处理,把你的代码放入仓库。
  3. 使用您的代码构建服务并将其关联到您的Controller-Service中。 Take a look here
  4. 把你的代码放在特征中。