Symfony 2: how to minify this code?

When doing CRUD , I often repeat these lines:

// ../myBundle/Controller/MyController.php
$entityManager = $this->getDoctrine()->getManager();
$repository    = $entityManager->getRepository('myBundle:myEntity');

      

My thought was to define $entityManager

and $repository

in __construct()

, but as far as I know I would need to define service

for myclass

. It seems overpriced.

How can I minify my code in a useful way?

Thank you in advance

IN.

+3


source to share


1 answer


You only really need a manager when you are saving entities. If your controller action only needs to get them, you can either:

  • only fetches the repository, eg. $this->getDoctrine()->getRepository(...)

  • wrap the repository itself into a service, so it will be accessible via $this->container->get('my_bundle.my_entity.repository')

Depending on your use case, you can use the method that works best.



Ideologically, however, all of your selection logic should be implemented in your repositories, so you never have to put your repository into a local variable. You should be able to $this->getDoctrine()->getRepository('MyBundle:MyEntity')->findBySomething($args...)

, where $args

are your criteria.

If you want to strip all persistence logic from your controllers, then managers are the way to go. Basically, you should implement a class that handles persistence and fetch, can be delegated to its dependencies. Take a look at the FOSUserBundle UserManager to get this idea. And an example of using this template would look something like this:

<?php

class CatsController extends Controller 
{
    public function list()
    {
        return $this->get('my_bundle.cats_manager')->findAll();
    }

    public function get($name)
    {
        return $this->get('my_bundle.cats_manager')->findOneByName($name);
    }

    public function create(Request $request)
    {
        $cat = new Cat(
            'Micky',
            'siamese'
        );

        $this->get('my_bundle.cats_manager')->persist($cat);
    }

    // ...
}

      

+2


source







All Articles