How does a service container create an object declared in services.yml?

Consider this code:

public function showActiveJobsAction($slug)
{
     $em = $this->getDoctrine()->getEntityManager();
     $category = $em->getRepository('JobeetBundle:Category')->findBySlug($slug);
     if (! $category) {
        throw $this->createNotFoundException('Unable to find Category entity.');
     }

     $jobService = $this->container->get('job_service');
     $category = $jobService->populateCategoryByItsActiveJobs($category);

     return $this->render('JobeetBundle:Category:jobs.html.twig', array(
        'category'      => $category,
    ));        
}

      

job_service needs JobeetBundle: category repository for work. The repository is passed to the constructor of the service. This is all defined in services.yml

So in this case I end up with two instances of the JobeetBundle class: Category repository?

If so, how can I change my design to make it better?

It might be better to code the same way:

$jobService->getCatetoryWithActiveJobsByItsSlug($slug)

      

but I'm still wondering if the container is looking for an object to exist before creating it?

0


source to share


2 answers


When you get a service from a container, you get the same instance by default. This is the same instance when this service is introduced into another.

So you don't have two problems, you only get one instance of the service job_service

.

Here is an excerpt from the Symfony2 book, chapter Service Container :



As an added bonus, the Mailer service is only created once and the same instance is returned every time you request this service. This is almost always the behavior you want (it is more flexible and powerful).

Hope it helps!

+2


source


In general, you won't get duplicate repos (or services) in Symfony2, so don't worry.

It:



$jobService->getCatetoryWithActiveJobsByItsSlug($slug)

      

This is the best approach, simply because it hides the entity manager / repository stuff from your controller. You could (at least in theory) change the entire Doctrine2 engine to something else and still work with your controller code.

+1


source







All Articles