Ejemplo n.º 1
0
 /**
  * Add a new instance or service in container
  *
  * @param string $key
  * @param $obj
  * @param callable|null $callback
  * @throws ContainerException
  * @throws Exception\RepositoryException
  */
 public function add(string $key, $obj, callable $callback = null)
 {
     // Check if key already exists
     if ($this->has($key)) {
         throw ContainerException::keyExists(__METHOD__, $key);
     }
     // Determine service type
     if (is_object($obj)) {
         // Saving instance, so same instance will be returned every time
         $this->repo->push($obj, $key);
     } elseif (is_string($obj)) {
         // Save path to class, new instance will be created and returned on retrieve
         $this->services[$key] = new Service($obj);
         // Callback with reference to service
         if (isset($callback)) {
             call_user_func_array($callback, [$this]);
         }
     } else {
         // Bad service
         throw ContainerException::badService(__METHOD__, gettype($obj));
     }
 }