99 lines
1.9 KiB
PHP
99 lines
1.9 KiB
PHP
<?php
|
|
|
|
use common\Config;
|
|
use common\Progaram;
|
|
|
|
/**
|
|
* Class Container
|
|
*/
|
|
class Container
|
|
{
|
|
|
|
/** @var Container */
|
|
private static $_instance;
|
|
|
|
/** @var \common\Config */
|
|
private $config;
|
|
|
|
private $container = [];
|
|
|
|
const QQ_SMALL_PROGRAM = 'QQ_SMALL_PROGRAM';
|
|
const QQ_LITTLE_GAME = 'QQ_LITTLE_GAME';
|
|
const WX_LITTLE_GAME = 'WX_LITTLE_GAME';
|
|
const WX_SMALL_PROGRAM = 'WX_SMALL_PROGRAM';
|
|
const WX_OFFICIAL_ACCOUNT = 'WX_OFFICIAL_ACCOUNT';
|
|
|
|
/**
|
|
* @param $class
|
|
* @param $config
|
|
* @return mixed|object|ReflectionClass
|
|
* @throws ReflectionException
|
|
*/
|
|
public static function newInstance($class, $config)
|
|
{
|
|
if (!(static::$_instance instanceof Container)) {
|
|
static::$_instance = new Container();
|
|
}
|
|
static::$_instance->generate($config);
|
|
|
|
if (static::$_instance->exists($class)) {
|
|
return static::$_instance->get($class);
|
|
} else {
|
|
return static::$_instance->createObject($class);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param \common\Config $config
|
|
* @return $this
|
|
*/
|
|
public function generate(Config $config)
|
|
{
|
|
$this->config = $config;
|
|
return $this;
|
|
}
|
|
|
|
|
|
/**
|
|
* @param $class
|
|
* @return object|ReflectionClass
|
|
* @throws ReflectionException
|
|
* @throws Exception
|
|
*/
|
|
private function createObject($class)
|
|
{
|
|
$newInstance = new \ReflectionClass($class);
|
|
if (!$newInstance->isInstantiable()) {
|
|
throw new Exception('Class Con\'t instance.');
|
|
}
|
|
$newInstance = $newInstance->newInstance();
|
|
if (method_exists($newInstance, 'initConfig')) {
|
|
$newInstance->initConfig($this->config);
|
|
}
|
|
|
|
$this->container[$class] = $newInstance;
|
|
return $newInstance;
|
|
}
|
|
|
|
|
|
/**
|
|
* @param $name
|
|
* @return mixed|object|ReflectionClass
|
|
* @throws ReflectionException
|
|
*/
|
|
public function get($name)
|
|
{
|
|
return $this->container[$name];
|
|
}
|
|
|
|
/**
|
|
* @param $name
|
|
* @return bool
|
|
*/
|
|
public function exists($name)
|
|
{
|
|
return array_key_exists($name, $this->container) && $this->container[$name] instanceof Progaram;
|
|
}
|
|
|
|
}
|