/** * Tests creating an instance of the given class * @param string $class * @param array|null $args * @param bool $valid * @return void * * @dataProvider instanceProvider */ public function testCreateInstance($class, array $args = null, $valid = true) { if (!$valid) { $this->setExpectedException('Nimbles\\Core\\Util\\Exception\\CreateInstanceFailure'); } $instance = Instance::getInstance($class, $args); $this->assertInstanceOf($class, $instance); }
/** * Gets an instance of the class based on arguements. * @return object */ public static function getInstance() { static $instances; if (null === $instances) { $instances = array(); } $args = func_get_args(); $key = serialize($args); if (!array_key_exists($key, $instances)) { $instances[$key] = \Nimbles\Core\Util\Instance::getInstance(get_class(), $args); } return $instances[$key]; }
/** * Gets an instance of the defined class * @return object * @throws \Nimbles\Core\Container\Exception\CreateInstanceFailure */ public function getInstance() { $id = $this->getId(); if ($this->isShared()) { if (!is_array(static::$_instance)) { static::$_instance = array(); } if (array_key_exists($id, static::$_instance)) { return static::$_instance[$id]; } } $parameters = $this->getParameters(); $class = $this->getClass(); try { $instance = Instance::getInstance($class, $parameters); } catch (\Exception $ex) { throw new Exception\CreateInstanceFailure('Failed to create an instance of : ' . $class, 0, $ex); } if (!$this->isShared()) { return $instance; } static::$_instance[$id] = $instance; return static::$_instance[$id]; }
/** * Sets the adapter * * If the adapter passed in is a string, then the method will automatically * attempt to create an instance of the class within the provided options * * @param string|object $adapter * @return \Nimbles\Core\Pattern\Adapter * @throws \Nimbles\Core\Pattern\Adapter\Exception\InvalidAdapter * @throws \Nimbles\Core\Pattern\Adapter\Exception\CreateInstanceFailure */ public function setAdapter($adapter) { if (is_string($adapter)) { $class = $this->_getMappedClass($adapter); if (!class_exists($class)) { throw new Adapter\Exception\InvalidAdapter('Cannot set adapter by a string because the given class does not exist'); } $args = func_get_args(); array_shift($args); try { $adapter = Instance::getInstance($class, $args); } catch (\Exception $ex) { throw new Adapter\Exception\CreateInstanceFailure('Failed to create an instance of : ' . $class, 0, $ex); } } // check type is valid if (null !== ($type = $this->getType()) && !is_a($adapter, $type)) { throw new Adapter\Exception\InvalidAdapter('Provided adapter is not of given type: ' . $this->getType()); } $this->_adapter = $adapter; return $this; }