2016-08-02 60 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. 把你的代碼放在特徵中。