3

While completing CRUD-stuff I often repeat these lines:

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

My thought was to define the $entityManager and $repository within the __construct(), but as far as I know, I'd have to define a service for my class. That feels overstated.

How could I reduce my code in a useful way?

Thanks in advance

B.

Community
  • 1
  • 1
Mr. B.
  • 8,041
  • 14
  • 67
  • 117
  • 1
    I think you can do a CRUD Controller and maybe extend from this one, but I'm not sure is the recommended way since it involves Routing configuration. Of course this will work only if the entities where you do Create/ Edit and Delete have similar needs. If you like the idea I can extend myself more. – Martin Fasani Nov 14 '14 at 08:16

1 Answers1

2

Actually, you should only need the manager when you're persisting entities. If this action of your controller only needs to fetch them, then you could either:

  • retrieve only the repository, e.g. $this->getDoctrine()->getRepository(...)
  • wrap the repository itself into a service, so it'd be accessible via $this->container->get('my_bundle.my_entity.repository')

Depending on your use case, you could use the method that fits better.

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

If you want to factor out all the persistence logic from your controllers, then managers are the way. Basically, you'd implement a class that handles persistence and fetching, maybe delegated to its dependencies. Take a look at FOSUserBundle's UserManager to get the idea. And the use case for this pattern would look pretty much 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);
    }

    // ...
}
kix
  • 3,290
  • 27
  • 39