Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Last active December 22, 2017 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/b550a5aab788b05e2e7bef9b953275dd to your computer and use it in GitHub Desktop.
Save kobus1998/b550a5aab788b05e2e7bef9b953275dd to your computer and use it in GitHub Desktop.
Php manager container instances
<?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);
}
}
@kobus1998
Copy link
Author

kobus1998 commented Dec 22, 2017

use App\Utill\Request;
use App\Utill\Pipe;
use App\Utill\Container;
use App\Another;

$url = 'https://google.com/';
$request = new Request();
$pipe = new Pipe();
$another = new Another();

new Container('AppServices', [
  'Request' => $request
]);

$app = Container::getInstance('AppServices');

$app->add([
  'Pipe' => $pipe
]);

$app->add('Another', $another);

$app->getService('Request')->get($url);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment