Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin

tommcfarlin/00-container.php Secret

Last active Aug 31, 2016
Embed
What would you like to do?
[WordPress] Single Design Pattern and Dependency Injection, Part 1
<?php
/**
* An implementation of the Singleton Design Pattern. Ultimately, this code
* will be used to show how to leverage the pattern as a very, very simple
* container that can be used in dependency injection.
*
* @link https://tommcfarlin.com/single-design-pattern-1/
*/
class Container {
/**
* Maintains a private reference to an instance of this class.
*
* @access private
* @var Container
*/
private static $instance;
/**
* A private container used for the pattern implementation.
*
* @access private
*/
private function __construct() {}
/**
* The static method used to return an instance to this class.
*
* @return Container A reference to a static instance of this class.
*/
public static function get_instance() {
if ( ! isset( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
}
<?php
/**
* An implementation of the Singleton Design Pattern. Ultimately, this code
* will be used to show how to leverage the pattern as a very, very simple
* container that can be used in dependency injection.
*
* @link https://tommcfarlin.com/single-design-pattern-3/
*/
class Container {
/**
* Maintains a private reference to an instance of this class.
*
* @access private
* @var Container
*/
private static $instance;
/**
* An associative array of objects that are stored in this container.
*
* @access private
* @var array
*/
private static $registry;
/**
* The static method used to return an instance to this class.
*
* @return Container A reference to a static instance of this class.
*/
public static function get_instance() {
if ( ! isset( self::$instance ) ) {
self::$instance = new self();
self::$registry = array();
}
return self::$instance;
}
/**
* A private container used for the pattern implementation.
*
* @access private
*/
private function __construct() {}
/**
* Adds an object to this container.
*
* @param string $id How to uniquely identify the incoming object.
* @param Object $instance A reference to the instance of the object to store.
* @throws Exception If the specified key already exists in the registry.
*/
public function add( $id, $instance ) {
if ( array_key_exists( $id, self::$registry ) ) {
throw new \Exception( 'This class already exists in the registry.' );
}
self::$registry[ $id ] = $instance;
}
/**
* Retrieves the object represented and stored by the incoming ID.
*
* @param string $id The key representing the objected store in the registry.
* @return Object A reference to the instane of the object to use.
*/
public function get( $id ) {
return self::$registry[ $id ];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.