Skip to content

Instantly share code, notes, and snippets.

@icambridge
Created June 5, 2014 18:07
Show Gist options
  • Save icambridge/fa0cd7160709ac6b6218 to your computer and use it in GitHub Desktop.
Save icambridge/fa0cd7160709ac6b6218 to your computer and use it in GitHub Desktop.
Dependency Injection Examples
<?php
class Notify
{
/**
* @var SenderInterface
*/
protected $sender;
public function __construct(SenderInterface $sender)
{
$this->sender = $sender;
}
public function email($message)
{
$this->sender->send($message);
}
}
<?php
interface ContainerInterface
{
public function get($name);
public function set($name, $service);
}
class Container implements ContainerInterface
{
protected $services = [];
public function get($name)
{
if (!isset($this->services[$name])) {
return;
}
return $this->services[$name];
}
public function set($name, $service)
{
$this->services[$name] = $service;
}
}
class Controller
{
/**
* @var ContainerInterface
*/
protected $container;
public function setContainer(ContainerInterface $container)
{
$this->container = $container;
}
public function indexAction()
{
$render = $this->container->get("render");
return $render->display("index");
}
}
<?php
class Entity
{
}
interface EntityFactoryInterface
{
public function getEntity($data);
}
class EntityFactory implements EntityFactoryInterface
{
public function getEntity($data)
{
return new Entity($data);
}
}
class Model
{
/**
* @var EntityFactoryInterface
*/
protected $factory;
public function __construct(EntityFactory $factory)
{
$this->factory = $factory;
}
public function getById($id)
{
$data = ['id' => 1];
$entity = $this->factory->getEntity($data);
return $entity;
}
}
<?php
class Entity
{
}
class Model
{
/**
* @var Entity
*/
protected $entity;
public function __construct(Entity $entity)
{
$this->entity = clone $entity;
}
public function getById($id)
{
$data = ['id' => 1];
$entity = clone $this->entity;
$entity->setData($data);
return $entity;
}
}
<?php
class CalendarDay
{
// ... pretend there is a dependency injection for a database connection.
public function getDaySchedule(DateTimeInterface $datetime)
{
$date = $datetime->format("Y-m-d");
return $this->connection->prepare(
"SELECT * FROM `days` WHERE date = ?", $date
);
}
}
<?php
class ExampleModel
{
/**
* @var ConnectionInterface
*/
protected $connection;
public function setConnection(ConnectionInterface $connection)
{
$this->connection = $connection;
}
public function getAll()
{
return $this->connection->query("SELECT * FROM `table`");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment