Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony service injection syntax

Tags:

php

symfony

I am working on a Symfony 2 app implemented by another company and came across the following service definition:

service_id:
    class: 'path\to\class'
    calls:
       - [setRequest, ['@?request=']]

I know what the question mark in @?request= means (if the service does not exist, setRequest does not get called), but what does the equal sign at the end of mean?

Thanks!

like image 263
medowlock Avatar asked Oct 06 '17 09:10

medowlock


People also ask

What is @inject in Symfony?

It is official. Symfony 5.1 adds property injection to public properties . Now, @inject or @required annotation above property or setter method is the fastest way to get any dependency on any service in your Symfony or Nette project. Use it everywhere you can... or not?

How do Symfony type-hints work?

When you use these type-hints in your controller methods or inside your own services, Symfony will automatically pass you the service object matching that type. Throughout the docs, you'll see how to use the many different services that live in the container.

Do I need to register Symfony dependency injection as a service?

Yes. With Symfony Dependency Injection, every service is instantiated by Symfony. So I need to register it as any other service I create. We have some Report page that requires some ReportingCustomRepository to fetch some complex massaged data. However, Report entity does not exist, neither needs to be as t's not a table.

How do I ask for a service in Symfony?

The moment you start a Symfony app, your container already contains many services. These are like tools: waiting for you to take advantage of them. In your controller, you can "ask" for a service from the container by type-hinting an argument with the service's class or interface name.


1 Answers

The equal sign was used to tell the container to ignore scope violations. request is in a special scope and the container throws an exception if you use it in a different scope.

Scopes were deprecated in Sf 2.8 and removed in Sf 3.0. See https://symfony.com/doc/2.8/service_container/scopes.html

Also, as of Symfony 2.4 you should use the request_stack: http://symfony.com/blog/new-in-symfony-2-4-the-request-stack

like image 102
prehfeldt Avatar answered Oct 11 '22 09:10

prehfeldt