symfonysymfony2

Service (uses service factory) to return objects of different types


I need to create a service, which uses another factory service, and return objects of different types.
Here's a definitions of my services:

services:
    games.search_factory:
        class: %games.search_factory.class%
        calls:
           - [ setContainer, ["@service_container"] ]

    games.search:
        class: %games.search.base.class%
        factory_service: games.search_factory
        factory_method: get

My %games.search_factory.class% get method returns different objects depending on the request parameters.
My %games.search.base.class% is abstract.
My goal is - when I call

$this->get("games.search");  

I want to get the result of factory method. But when I run the code, I get an error: FatalErrorException: Error: Cannot instantiate abstract class.

So I have two questions:

  1. Why does DI system try to instantiate my class, instead of returning the result of my factory method?
  2. Is there a way to implement what I need (nicely and concisely)?

Update: I had a bug in the part of code, which is not shown here. Besides these two services for search, I had a service for each search type, and returned these services from a factory. But in the definition of these services, I've used my base class (which is abstract) as a class.

So nice conclusion is that it is possible to return an objects of different types from a factory.


Solution

  • From here: http://symfony.com/doc/current/components/dependency_injection/factories.html

    When you specify the class to use for the factory (via factory_class) the method will be called statically. If the factory itself should be instantiated and the resulting object's method called (as in this example), configure the factory itself as a service

    In order to inject the container into your factory you will either need to make the factory instantionable (not abstract) or pass the container as an argument to the static get method. I'm not aware of any way to declare a service as being static.