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.
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:
$this->getDoctrine()->getRepository(...)$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);
}
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With