Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Simple container
- // Простая реализация контейнера.
- namespace System\Container;
- use Psr\Container\ContainerInterface;
- use ReflectionClass;
- use ReflectionException;
- /**
- * Class Container
- * @package System\Container
- */
- class Container implements ContainerInterface
- {
- /**
- * @var array
- */
- private $instances = [];
- /**
- * @var array
- */
- private $bindings = [];
- /**
- * @var Container
- */
- private static $instance;
- /**
- * Container constructor.
- */
- private function __construct()
- {
- }
- /**
- * Get container instance
- *
- * @return Container
- */
- public static function getInstance()
- {
- if (static::$instance === null) {
- static::$instance = new static();
- }
- return static::$instance;
- }
- /**
- * Added bind with the name
- *
- * @param string $name
- * @param mixed $source
- * @param mixed $params
- * @return $this
- */
- public function bind($name, $source, $params = [])
- {
- if (($source instanceof \Closure) || is_string($source)) {
- $this->bindings[$name] = [$source, $params];
- } else {
- $this->instances[$name] = $source;
- }
- return $this;
- }
- /**
- * @param string $name
- * @return mixed
- * @throws NotFoundException
- * @throws ReflectionException
- */
- public function get($name)
- {
- if ($this->has($name)) {
- if ($this->hasInstance($name)) {
- $instance = $this->instances[$name];
- } else {
- $instance = $this->binding($name);
- $this->instances[$name] = $instance;
- }
- return $instance;
- }
- throw new NotFoundException();
- }
- /**
- * Binding instance to the name
- *
- * @param string $name
- * @return mixed
- * @throws NotFoundException
- * @throws ReflectionException
- */
- private function binding($name)
- {
- list($source, $params) = $this->bindings[$name];
- if (is_string($source) || class_exists($source)) {
- $reflector = new ReflectionClass($source);
- return $reflector->newInstanceArgs($params);
- } elseif ($source instanceof \Closure) {
- return call_user_func_array($source, $params);
- }
- throw new NotFoundException();
- }
- /**
- * Check exist instance with the name
- *
- * @param string $name
- * @return bool
- */
- private function hasInstance($name)
- {
- return isset($this->instances[$name]);
- }
- /**
- * Check exist bind with the name
- *
- * @param string $name
- * @return bool
- */
- private function hasBinding($name)
- {
- return isset($this->bindings[$name]);
- }
- /**
- * @param string $name
- * @return bool
- */
- public function has($name)
- {
- return $this->hasBinding($name) || $this->hasInstance($name);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement