Skip to content

Instantly share code, notes, and snippets.

@jovialcore
Last active March 7, 2023 12:33
Show Gist options
  • Save jovialcore/8801ff41aff144f06b97761b3b0b9cb1 to your computer and use it in GitHub Desktop.
Save jovialcore/8801ff41aff144f06b97761b3b0b9cb1 to your computer and use it in GitHub Desktop.
Dependency Injection in php explained
<?php
declare(strict_types=1);
namespace DemoPhpframework;
/**
* Dependency Injection from a bible Base Creation Story Example
*
* First what is Dependency Injection:
* Dependency injection says that instead of a class accessing other dependencies (say class, or objects of a class, etc) instead that dependency ( class, object, etc) is supplied or provided to it. In otherwords, a classdoesn't need to reachout but it is supplied with what ever neccesary class, object, etc it will be needing.
*
*
* For further reading : https://php-di.org/doc/understanding-di.html
*
*/
// God begins Creation
class God
{
public function speakTheWord()
{
echo " Let there be Light !!!!";
}
public function createMan()
{
echo " Lets create man in our own image and in our likeness";
}
}
///without dependcy injection
class creationWithoutDi
{
public function manifest()
{
$God = new God();
$God->speakTheWord();
}
//here we can seee that we are creating a new instance of this over and over again
public function createMan()
{
$God = new God();
$God->createMan();
}
}
// with dependency injection
class creation
{
private $wordSpoken;
//more like injecting the other classes objects, properties easily
public function __construct(God $wordSpoken)
{
$this->wordSpoken = $wordSpoken;
}
// now i have access to the methods, properties in the God class
public function manifestWord()
{
return $this->wordSpoken->speakTheWord();
}
public function manifestFlesh()
{
return $this->wordSpoken->createMan();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment