Files
kiri-wchat/Container.php
T

103 lines
2.0 KiB
PHP
Raw Normal View History

2019-11-11 18:14:47 +08:00
<?php
2020-03-05 12:41:49 +08:00
use wchat\common\Config;
use wchat\common\Progaram;
2019-11-11 18:14:47 +08:00
/**
* 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';
/**
2019-12-12 12:05:22 +08:00
* @param $class
* @param $config
* @return mixed|object|ReflectionClass
* @throws ReflectionException
2019-11-11 18:14:47 +08:00
*/
public static function newInstance($class, $config)
{
if (!(static::$_instance instanceof Container)) {
static::$_instance = new Container();
}
static::$_instance->generate($config);
if (static::$_instance->exists($class)) {
2020-01-07 12:13:58 +08:00
$newInstance = static::$_instance->get($class);
if (method_exists($newInstance, 'initConfig')) {
$newInstance->initConfig($config);
}
return $newInstance;
2019-11-11 18:14:47 +08:00
} else {
2019-12-12 12:05:22 +08:00
return static::$_instance->createObject($class);
2019-11-11 18:14:47 +08:00
}
}
/**
* @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
2019-12-12 12:04:25 +08:00
* @return mixed|object|ReflectionClass
* @throws ReflectionException
2019-11-11 18:14:47 +08:00
*/
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;
}
}