Last active
December 22, 2017 15:25
-
-
Save kobus1998/b550a5aab788b05e2e7bef9b953275dd to your computer and use it in GitHub Desktop.
Php manager container instances
This file contains 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 | |
namespace App\Utill; | |
class Container { | |
/** | |
* @var Array container instances | |
*/ | |
public static $instances = []; | |
/** | |
* @var String unique container id | |
*/ | |
private $id; | |
/** | |
* Constructor | |
* @param String unique id | |
* @param Array services | |
* @return self | |
*/ | |
function __construct (String $id, Array $services = []) | |
{ | |
$this->id = $id; | |
$this->services = $services; | |
self::_addInstance($this); | |
} | |
/** | |
* Get an instance | |
* @param String id | |
* @return Array | |
*/ | |
public static function getInstance (String $id) | |
{ | |
if (isset(self::$instances[$id])) | |
{ | |
return self::$instances[$id]; | |
} | |
return false; | |
} | |
/** | |
* Add a new container to instances | |
* @param String id | |
* @param Array services | |
* @return void | |
*/ | |
private static function _addInstance ($instance) | |
{ | |
self::$instances[$instance->id] = $instance; | |
} | |
/** | |
* Get service from container | |
* @param String id | |
* @param String service name | |
* @return Class | |
*/ | |
private static function _getService ($id, $service) | |
{ | |
return self::$instances[$id]->services[$service]; | |
} | |
/** | |
* Add service to instance | |
* @param String id | |
* @param Array service | |
* @return void | |
*/ | |
private static function _addServices ($id, $services) | |
{ | |
foreach ($services as $key => $val) { | |
self::$instances[$id]->services[$key] = $val; | |
} | |
} | |
/** | |
* Add service to this instance | |
* @param Array|String id or services | |
* @param Array services (optional) | |
* @return self | |
*/ | |
public function add ($name, $services = null) | |
{ | |
if (is_array($name)) { | |
$services = $name; | |
self::_addServices($this->id, $services); | |
} else { | |
self::_addServices($this->id, [ | |
$name => $services | |
]); | |
} | |
return $this; | |
} | |
/** | |
* Get a service from this instance | |
* @param String service | |
* @return Class | |
*/ | |
public function getService ($service) | |
{ | |
return self::_getService($this->id, $service); | |
} | |
} |
Author
kobus1998
commented
Dec 22, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment