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 need JobeetBundle:Category repository to work. The repository is passed to service constructor. It’s all defined in services.yml
So in this case I end up with two instance of JobeetBundle:Category repository class?
If yes how can I change my design to do it better?
Probably it’s better to create code just like:
$jobService->getCatetoryWithActiveJobsByItsSlug($slug)
but I still wonder if container looks for object existance before create it?
When you get a service from the container, by default, you get always the same instance. It is also the same instance when this service is injected into another one.
So you don’t have two worry, you get only one instance of the service
job_service.Here is an extract from the Symfony2 book, chapter Service Container:
Hope that helps!