Reputation: 1500
I have this little dependency injection container which I instantiate like:
$services = new Services();
and if I need to add parameters to it I just do:
$services->setParameter($name, $value);
and I pass this instance of $services
through the constructors of some my objects and if I need something like the database handle I just go $this->services->getService('db');
and it returns an instance of the database handle and if I call that method again later it will return the same instance of the database handle it did earlier.
The thing I want to know is are dependency injection containers only for single instance objects like your $dbh, $config, $user, $auth
objects?
For example, I need to create multiple instances of a Products
class but if I go:
$services->setParameter('product.id', $productId);
$product[] = $services->getService('product');
It will obviously create a new instance of Product
but then if I repeat that code again it will just give me back the same instance as earlier, I can obviously modify the getService()
method a bit so that it can return as many new instances as I need but is that using a DIC for something it's not made for?
So basically should a DIC only return single instances of a class like $dbh, $user etc
? and not be creating objects like Orders, Products, Invoices
?
Upvotes: 1
Views: 598
Reputation: 532
For the product case: the service itself is only one. The service has some methods that allow you to create multiple products, but those are most likely data objects, not services. So basicly you could have $this->getContainer->getService('product')->createNew()
which should return a new product instance.
There are cases in which you would need to return multiple service instances, but these are probably not applicable in your example. As @camus mentioned before, Pimple is a great example of such implementation, and also very easy to implement and understand.
Upvotes: 0
Reputation: 20155
Look at pimple's code :
https://github.com/fabpot/Pimple
You can define different methods that either return a single instance , or return multiple instances depending on how the services are defines in the container.
Pimple uses $container->share method to define shared services. then it doesnt matter how you call your services , it only matters how you define them.
Or you could just use pimple that has everything you need already.
Upvotes: 1