Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\DI;
- use Closure;
- use App\DI\ServiceProviderInterface;
- //use olifant\exceptions\AppException;
- class Container implements \ArrayAccess
- {
- protected $aliases = [];
- protected $freezed = [];
- protected $instances = [];
- protected $shared = [];
- public function set($key, $entity)
- {
- if (null === $key) {
- throw new Appexception('Key cannot be null');
- }
- $this->instances[$key] = $entity;
- }
- public function singleton($key, $entity)
- {
- $this->shared[$key] = $entity;
- }
- public function has($key)
- {
- $key = $this->resolveAlias($key);
- return (
- isset($this->instances[$key]) or
- isset($this->shared[$key])
- );
- }
- public function alias($alias, $key)
- {
- $this->aliases[$alias] = $key;
- return $this;
- }
- protected function resolveAlias($key)
- {
- if (isset($this->aliases[$key])) {
- return $this->aliases[$key];
- }
- return $key;
- }
- public function extend($key, \Closure $callable)
- {
- $store = $this->get($key);
- $closure = function ($container) use($callable, $store) {
- return $callable($store->get($container), $container);
- };
- $this->set($key, $closure, $store->isShared());
- return $this;
- }
- public function fork($key, $newkey)
- {
- }
- public function get($key)
- {
- $key = $this->resolveAlias($key);
- if(isset($this->instances[$key])){
- if($this->instances[$key] instanceof Closure)
- return call_user_func_array(
- $this->instances[$key],
- array($this)
- );
- return $this->instances[$key];
- }
- if(isset($this->shared[$key])){
- if($this->shared[$key] instanceof Closure)
- $this->shared[$key] = call_user_func_array(
- $this->shared[$key],
- array($this)
- );
- return $this->shared[$key];
- }
- }
- public function offsetSet($offset, $value)
- {
- $this->set($offset,$value);
- }
- public function offsetExists($offset)
- {
- return $this->has($offset);
- }
- public function offsetGet($offset)
- {
- return $this->get($offset);
- }
- public function offsetUnset($offset)
- {
- //$offset = $this->resolveAlias($offset);
- unset(
- $this->instances[$offset],
- $this->shared[$offset]
- );
- }
- public function keys()
- {
- return array_unique(
- array_merge(
- array_keys($this->instances),
- array_keys($this->shared),
- array_keys($this->aliases)
- )
- );
- }
- public function register(ServiceProviderInterface $provider)
- {
- $provider->register($this);
- return $this;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement