Advertisement
Guest User

Untitled

a guest
Aug 12th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.80 KB | None | 0 0
  1. class Database
  2. {
  3.     // Let's pretend we have boatloads of code here
  4. }
  5.  
  6. // Now, the model class NEEDS database class in order to work, we can say
  7. // that the model DEPENDS on the database class, since the class needs
  8. // database instance to work, we INJECT the database object to the model
  9. // class via constructor, this is called constructor injection IIRC
  10.  
  11. class BlogModel
  12. {
  13.     protected $db;
  14.    
  15.     // Inject a database instance via constructor
  16.     public function __constructor(Database $db)
  17.     {
  18.         $this->db = $db;
  19.     }
  20. }
  21.  
  22. // Create an instance of database
  23. $db = new Database('localhost', 'root', 'dkjfkf', 'db_name');
  24.  
  25. // Whenever we need the BlogModel, inject Database instance via the constructor
  26. $blogmodel = new BlogModel($db);
  27.  
  28. // That's dependency injection in a nutshell
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement