Last active
March 7, 2023 14:43
-
-
Save jovialcore/008329a263ab7b5e4150b039664c0be0 to your computer and use it in GitHub Desktop.
dependency injection with interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace DemoPhpframework; | |
/** | |
* Dependency Injection from a bible Base Creation 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 | |
* | |
*/ | |
//another instance. Lets implement interfaces with dependecny injection | |
//interface | |
interface CreationInterface | |
{ | |
public function spokenWord(); | |
} | |
// Day one of creation, what did God say ? What is the word God spoke ? | |
class DayOne implements CreationInterface | |
{ | |
public function spokenWord() | |
{ | |
echo " Let there be Light !!!!"; | |
} | |
} | |
// Day five of creation, what did God say ? What is the word God spoke ? | |
class DayFive implements CreationInterface | |
{ | |
public function spokenWord() | |
{ | |
echo " Lets create man in our own image and in our likeness"; | |
} | |
} | |
// dependency injection here: | |
class beginCreation | |
{ | |
private $whatGodSaid; | |
public function __construct(CreationInterface $whatGodSaid) | |
{ | |
$this->whatGodSaid = $whatGodSaid; | |
} | |
public function execute() | |
{ | |
return $this->whatGodSaid->spokenWord(); | |
} | |
} | |
$dayOne = new dayFive(); // change/instantiate dayOne class | |
$beginCreation = new beginCreation($dayOne); | |
echo $beginCreation->execute(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment