Skip to content

Instantly share code, notes, and snippets.

@dtrenz
Created December 17, 2013 20:36
Show Gist options
  • Save dtrenz/8012171 to your computer and use it in GitHub Desktop.
Save dtrenz/8012171 to your computer and use it in GitHub Desktop.
Using traits to handle service container.
<?php
class AddressBook {
use ServiceConsumer;
public function findContactByEmail($email)
{
// get database connection
$db = $this->container['database'];
// use the db connection to query for contact by email address
}
}
<?php
require_once('/path/to/Pimple.php');
trait ServiceConsumer {
protected $container;
public function __construct()
{
$this->container = new Pimple();
$this->container['database'] = function () {
$host = '127.0.0.1';
$user = 'db_user';
$pass = 'db_pass';
return new DatabaseConnection($host, $user, $pass);
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment