0

I'm trying to inject an object into one of my services, as well as another service. The second argument is just an object, however when declaring it in the services.yml file, I receive an exception staying that its expecting an object, but a string was given.

services.yml

parameters:
    app.my_class.class: AppBundle\MyClass
    app.object_to_inject.class: AppBundle\InjectObject

services:
    app.my_service:
        class: %app.my_class.class%
        arguments: [@app.another_service, %app.object_to_inject.class%]

Which results in:

Catchable Fatal Error: Argument 2 passed to AppBundle\MyClass::__construct() must be an instance of AppBundle\InjectObject, string given

I've tried quoting, unquoting and using new lines instead of square brackets:

arguments
    - @app.another_service
    - %app.object_to_inject.class%

1 Answer 1

1

Parameters are just strings, so you you trying to inject the string of your class name, not the actual class.
You need to define AppBundle\InjectObject as a service, then inject that.

Example:

parameters:
    app.my_class.class: AppBundle\MyClass
    app.object_to_inject.class: AppBundle\InjectObject

services:
    app.my_object:
        class: "%app.object_to_inject.class%"
    app.my_service:
        class: %app.my_class.class%
        arguments: [@app.another_service, @app.my_object]
Sign up to request clarification or add additional context in comments.

4 Comments

Is this only the case when using multiple arguments? Because I have a service just using the %class% syntax as a single argument and that injects the object, not a string
I have only ever added classes as arguments and variables as parameter string in my services. I might depend if the class you are trying to inject has any arguments itself. If I get time later I'll run some tests and find out.
The class I was trying to inject as the second argument didn't have any constructor arguments. Guessing you just can't do it the way I tried.Cheers, this works anyway
Just wanted to point out that for Symfony 3.0, the practice of using parameters to hold class names is being discouraged. Everything will still work but you really should only use parameter class names if changing the class is a common occurrence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.