Symfony2 framework, how do I invoke a service outside of the controller?

Source: Internet
Author: User
For example, I defined a public service a named Service.one.
In the controller, we can directly
$this->get (' Service.one ')->xxxxx
But what am I supposed to do if I'm not in the controller?

Reply content:

For example, I defined a public service a named Service.one.
In the controller, we can directly
$this->get (' Service.one ')->xxxxx
But what am I supposed to do if I'm not in the controller?

You must use the method container to container pass in a service or to be called. In fact controller , the get method in the call is also container the get method. Can inherit from ContainerAware , using setContainer method incoming container .

If it's not the controller, where are you? If it is another service, you can pass a service as a parameter when defining the service.

In the controller $this->get (' serviceName ') actually calls the Container container, so the call Service needs to be Container container, in Symfony, whether it is not in the controllers, Con Tainer container ID is called Servicecontainer, and wherever you are, you only need to injectservice container to get services:

Configuration in Services.yml:

service.id:     class: AppBundle\Form\YourServiceNamespace     arguments:         # 注入一个 **服务** (service)         - @service_container         # 注入一个 **参数** (parameter)         - %parameterkey%         # 注入一个 **字符串** (string)         - "string"
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.