Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2: how to reduce this code?

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.

like image 666
Mr. B. Avatar asked Mar 04 '26 08:03

Mr. B.


1 Answers

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

    // ...
}
like image 112
kix Avatar answered Mar 06 '26 22:03

kix