Created
December 6, 2013 21:06
-
-
Save usm4n/7832095 to your computer and use it in GitHub Desktop.
Dependency Injection in PHP
This file contains hidden or 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 | |
/** | |
* Product class | |
*/ | |
class Product { | |
/** | |
* database layer to be used | |
* @access protected | |
* @var DB | |
*/ | |
protected $db; | |
/** | |
* Creates Product | |
* @param string $db for example | |
* @param array $fields product fields | |
*/ | |
public function __construct($db,$fields) | |
{ | |
$this->db = $db; | |
$this->fields = $fields; | |
} | |
/** | |
* retreive products by id | |
* @param int $id product id | |
* @return mixed | |
*/ | |
public function getProductById($id) | |
{ | |
return $this->db->findById($id); | |
} | |
/** | |
* find product by executing a query | |
* @param array $query array of query options | |
* @return mixed | |
*/ | |
public function getProductByQuery($query) | |
{ | |
return $this->db->execQuery($query); | |
} | |
//other operations.... | |
} | |
$db = new DB($dbParams);// creating DB object | |
$product = new Product($db,$fields);//injecting DB object through constructor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment