user3544352
user3544352

Reputation: 49

Symfony Factory class

I would like to use a ResultFactory class as a service in my Symfony 2 application:

My Result factory class will be responsible to create a BaseResult instance. Depending on the type passed to the get factory method, the ResultFactory will create the right ResultObject.

Here's what could be the code:

class ResultFactory
{

    protected $translator;

    public function __construct(Translator $translator) 
    { 
        $this->translator = $translator;
    } 

    public function get($type, $param)
    {
        $instance = null;

        switch ($type) {

            case 'Type1':
                $instance = new Type1Result($param);
                break;

            case 'Type2':
                $instance = new Type2Result($param);
                break;

        }

        return $instance;
    }
}

My question is:

I would like to use a service in my ResultObject. How do i inject this service to my ResultObject?

Thanks!

Upvotes: 1

Views: 3638

Answers (1)

shacharsol
shacharsol

Reputation: 2342

You are not using your service inside a result object. your factory is generating the result object. You can define your factory service in services.yml of your bundle as:

result.factory:
    class: ResultFactory
    arguments: ["@translator"]

And in your controller you can call the service:

 $resultObject = $this->get('result_factory')->get($type, $param);

Also you have core example how to create factory service using symfony2 in [the docs].(http://symfony.com/doc/current/components/dependency_injection/factories.html)

Upvotes: 1

Related Questions