Ok so I have my dependency injection container and a DAO that I use like this to get an order for example:
$container = new DIContainer();
$orderDAO = $container->get('orderDAO');
$order = $orderDAO->fetchById($someId);
and then I have my order object which is easy to use.
The thing is what if my $order object has dependencies on a Logger, Config and one or two more objects like that, since my $orderDAO instantiates the object wouldn’t it have to have access to or be able to create those additional objects and I am pretty sure the $orderDAO object should definitely not know anything about those additional objects, especially not know how to create them.
I know I could inject the dependency injection container into the DAO when it is being instantiated (from within the DIC) and that way I would have access to any dependency my objects have from within the DAO but something about doing it that way doesn’t feel right to me for some reason and I definitely don’t want to be doing static calls all over the place either so that method is out the window.
What’s the best way to go about doing this?
Any help would be great thanks.
Allow DI container to manage internal object dependencies, like assigning Logger, Config and stuff like that inside the object you instantiating – is the normal way to do the things. If for some reason you don’t want to allow DI container to do that, then you could just create default constructor and assigning this values in it.
Actually it’s looks like you need to put inside some infrastructural things, things in that way it’s better to do that as simple as possible without some additional things, because it will get you to the unnecessary complexity.
UPD:
So productDAO does not have access to Config, etc… But you want that product have that. I think it’s pretty wrong from the design point of view. Because normally entities which main goal is store the data shouldn’t have any functions except their business logic. if you wan’t to do logging and configuration – you should do it inside DAO, but not in product. But anyway, if want, then just create wrapper for the things which could be changed in future (let’s say Logger) and then simply assign this value in constructor by hand.