Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Dependency injection is a big word for "I have some more parameters in my constructor".</p> <p>It's what you did before the awfull Singleton wave when you did not like globals :</p> <pre><code>&lt;?php class User { private $_db; function __construct($db) { $this-&gt;_db = $db; } } $db = new Db(); $user = new User($db); </code></pre> <p>Now, the trick is to use a single class to manage your dependencies, something like that :</p> <pre><code>class DependencyContainer { private _instances = array(); private _params = array(); public function __construct($params) { $this-&gt;_params = $params; } public function getDb() { if (empty($this-&gt;_instances['db']) || !is_a($this-&gt;_instances['db'], 'PDO') ) { $this-&gt;_instances['db'] = new PDO( $this-&gt;_params['dsn'], $this-&gt;_params['dbUser'], $this-&gt;_params['dbPwd'] ); } return $this-&gt;_instances['db']; } } class User { private $_db; public function __construct(DependencyContainer $di) { $this-&gt;_db = $di-&gt;getDb(); } } $dependencies = new DependencyContainer($someParams); $user = new User($dependencies); </code></pre> <p>You must think you just another class and more complexity. But, your user class may need something to log messages like lot of other classes. Just add a getMessageHandler function to your dependency container, and some <code>$this-&gt;_messages = $di-&gt;getMessageHandler()</code> to your user class. Nothing to change in the rest of your code.</p> <p>You'll get lot of infos on <a href="http://components.symfony-project.org/dependency-injection/trunk/book/00-Introduction" rel="noreferrer">symfony's doc</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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