0

I am new to symfony 2.8. I do the same code pattern in each of my controllers to get the same data, put in different views, following this pattern:

 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));
   }

Is it possible to factorize all the getRepositories calls and arrays injection into a separated class ?

thanks for your help,

1
  • 1
    Sure. Get familiar with dependency injection and services symfony.com/doc/current/service_container.html. Define your repositories as services and use $this->get('my.repository')->findAll(). Next, consider define your controllers as services so even the get can go away. Lots of other things you can do as well. Commented Aug 2, 2016 at 17:28

1 Answer 1

1

I dont think there is a Symfony-way. I would prefer 2.) and put your Code in the repository and just put some getters in the controller.

  1. Make an abstract Controller class from which you inherit from.
  2. I would do it with some redundant code. Put your repository getters in a method. Clean but redundant. If you have some complicated DB-Handling, put your code in the reposistory.
  3. Build a service with your code and associate it in your Controller-Service. Take a look here
  4. Put your code in a trait.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.