Note that there are some explanatory texts on larger screens.

plurals
  1. POPuzzled with Dependency Injection in PHP (chains of Classes)
    primarykey
    data
    text
    <p>I'm moving from Globals and Singletons (=bad?) to Dependency Injections (=good?) in PHP and I'm very new to it. </p> <p>I have read many related topics on Stack Overflow already but I still can't understand the main principles of DI.</p> <p>Please tell me if I'm doing it right (it's just shortened pseudo-code):</p> <pre><code>// first connect to DB $sql = new Sql(); // create logger (I'm writing logs to Database so I need to pass $sql to it) $log = new Log($sql); // restore logged in user, get info about user, unread messages... // class "User" needs access to Database and Logs: $user = new User($sql, $log); // now we need to collect all the data of current section of my Website // I'm using Model and Controller: $model = new FrontPageModel($sql, $user, $log); $pageController = new FrontPageController($model); </code></pre> <p>Though it may look OK at this step but what if I need to get access to more classes like Config, Session, etc.?</p> <p>Should my code transform to this?</p> <pre><code>$model = new FrontPageModel($sql, $user, $log, $config, $session); </code></pre> <p>Isn't it too much already?</p> <p>I know someone could advice to use a kind of big "Application" class and put Config, Session, Log, Db objects inside of this class but I feel that it isn't very good idea.</p> <p>Next question - what if I need to get logged User's ID inside of my FrontPageController? I did not pass an instance of "User" to FrontPageController, but it was passed before (in chain) to FronPageModel.</p> <pre><code>class FrontPageController{ private $model; function __construct($model){ $this-&gt;model = $model; } function getData(){ echo $this-&gt;model-&gt;user-&gt;id; // is it right way? } } </code></pre> <p>That "$this->model->user->id" seems like overkill to me.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload