Back

Is it appropriate to use the Container as a factory?


Dan Jones posted 1 year ago

I'm working on a Lumen API, and my current task involves a service that involves multiple possible implementations. So, something like this:

interface MyService {
    // code
}
class ServiceA implements MyService {
    //
}
class ServiceB implements MyService {
    //
}

My first thought was to create a factory class, something like:

class ServiceFactory {
    public static function make(string $name): MyService {
        switch ($name) {
            case 'a':
                return new ServiceA;
            case 'b':
                return new ServiceB;
        }
    }
}

So, I would call ServiceFactory::make('a') to get ServiceA.

But then I thought that I could instead use the Container to do the same thing. I would register it like:

$app->bind(MyService::class, function ($app, array $params) {
    $name = head($params);
    switch {
        case 'a':
            return new ServiceA;
        case 'b':
            return new ServiceB;
    }
});

And then, call it app()->make(MyService::class, ['a']), which feels a bit cleaner to me.

But I'm not sure if that's a good practice or not.

Thoughts?


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us