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?
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.