Dependency injection - must the dependency be one of the class variables of the object into which it is injected?
All,
I am writing a little dynamic site in php, and am trying to use dependency injection rather than globals.
In my index, I create a $view
object which contains the various elements to be displayed in the UI. In the index, I also have a switch($action){}
structure that governs which controllers to require
based on which item the user clicks on a menu (and therefore the value of $action
). I then say something like $view=execute($view)
on the controller. Each execute()
function (1 per controller) ends with return $view;
. The idea is that I can keep in the index a $view
object which contains the accumulated info generated during a user's session.
My question is: do I need to make $view
a class variable of each controller? I just want to pass it via the execute()
function, modify it within the function, and return it, modified. I'm not sure whether this is still considered dependency injection, or what are the advantages of making it or not a class variable of the classes to which the object is passed.
Thanks,
JDelage
PS: A bit more code to help with understanding:
In Index.php:
require_once("Class_view.php"); // J'ai cree une classe separee pour la vue.
$view=new $view;
$view->addToViewArray("title", "projet JDelage");
(...)
switch($action){ // Creates instances of the appropriate controller under the name $command
(...)
}
$view=$command->ex开发者_如何学Cecute($view) // Each execute() function of each controller takes $view as a parameter, modifies it, and returns it.
do I need to make
$view
a class variable of each controller? I just want to pass it via theexecute()
function, modify it within the function, and return it, modified.
No, you do not have to make it a class/instance variable if it is only processed. It does not belong to the internal state of the controller in that case, which is what class/instance variable are for.
I'm not sure whether this is still considered dependency injection, or what are the advantages of making it or not a class variable of the classes to which the object is passed.
Yes, it is still considered Dependency Injection. DI is bloody simple. All you have to do is to pass dependencies into an object. How the dependency is processed inside the object is not important. You will have no advantage saving the object in the other object if you ain't gonna need it. In fact, it's a disadvantage, because it's adding bloat then.
精彩评论