Advertisement
Guest User

Shinoa\DIContainer

a guest
May 28th, 2017
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.43 KB | None | 0 0
  1. <?php
  2. namespace Shinoa\StudentsList;
  3.  
  4.  
  5. use Shinoa\StudentsList\Exceptions\DIContainerException;
  6.  
  7. /**
  8.  * Use DIContainer to define factories and get only those data and objects, that you need at the time.
  9.  * @package Shinoa\StudentsList
  10.  */
  11. class DIContainer
  12. {
  13.     /**
  14.      * Contains factories, used to create certain data or object.
  15.      *
  16.      * @var array
  17.      */
  18.     protected $services = array();
  19.    
  20.     /**
  21.      * Contains created objects, that need not to be recreated
  22.      * @var array
  23.      */
  24.     protected $objects = array();
  25.    
  26.     /**
  27.      * Memorizes callable factory with given name.
  28.      *
  29.      * @param string $name
  30.      * @param callable $factory
  31.      * @throws DIContainerException
  32.      */
  33.     public function register(string $name, callable $factory)
  34.     {
  35.         if ( !array_key_exists($name, $this->services) ) {
  36.             $this->services[$name] = $factory;
  37.         } else {
  38.             throw new DIContainerException('Service name already occupied');
  39.         }
  40.     }
  41.    
  42.     /**
  43.      * Returns data by name, if there is a defined factory to produce it.
  44.      *
  45.      * @param string $name
  46.      * @return mixed
  47.      * @throws DIContainerException
  48.      */
  49.     public function get(string $name)
  50.     {
  51.         if ( array_key_exists($name, $this->objects) ) {
  52.             $result = $this->objects[$name];
  53.         } else {
  54.             if (array_key_exists($name, $this->services)) {
  55.                 $result = $this->services[$name]($this);
  56.             } else {
  57.                 throw new DIContainerException('Trying to call nonexistant service');
  58.             }
  59.         }
  60.         return $result;
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement