Skip to content

Instantly share code, notes, and snippets.

@usm4n
Created December 6, 2013 21:06
Show Gist options
  • Save usm4n/7832095 to your computer and use it in GitHub Desktop.
Save usm4n/7832095 to your computer and use it in GitHub Desktop.
Dependency Injection in PHP
<?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