服务容器如何创建在services.yml中声明的对象? [英] How Service Container create object declared in services.yml?

查看:49
本文介绍了服务容器如何创建在services.yml中声明的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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需要JobeetBundle:Category存储库才能工作.该存储库将传递给服务构造函数.所有这些都在services.yml

job_service need JobeetBundle:Category repository to work. The repository is passed to service constructor. It's all defined in services.yml

所以在这种情况下,我最终得到两个JobeetBundle:Category存储库类实例?

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.

因此您不必担心两个,只得到服务 job_service 的一个实例.

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

以下摘录自 Symfony2的书籍,《服务容器》 :

作为一项额外的奖励,Mailer服务仅创建一次,并且每次您请求该服务时都返回相同的实例.这几乎总是您所需要的行为(它更加灵活和强大).

As an added bonus, the Mailer service is only created once and the same instance is returned each time you ask for the service. This is almost always the behavior you'll need (it's more flexible and powerful).

希望有帮助!

这篇关于服务容器如何创建在services.yml中声明的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆