/** * Return an instance of a class after resolving its dependencies. * * @param string $class The class name or interface name to load. * @param string $name The alias given to this class for namespacing the configuration. * @return mixed */ public static function get($class, $name = Name::ANY) { try { return static::container()->getInstance($class, $name); } catch (NotCompiled $e) { $compiler = new DiCompiler(self::$modules, TMP); $compiler->compile(); return $compiler->getInstance($class, $name); } }
/** * {@inheritdoc} * @return \Ray\Di\DiCompiler */ public function get($extraCacheKey = '') { $contextKey = is_array($this->context) ? implode('_', $this->context) : $this->context; $saveKey = $this->appName . $contextKey; if (isset(self::$compiler[$saveKey])) { return self::$compiler[$saveKey]; } $apps = $this->apps; $moduleProvider = function () use($saveKey, $apps) { // avoid infinite loop if (isset(self::$module[$saveKey])) { return self::$module[$saveKey]; } $appModule = "{$this->appName}\\Module\\AppModule"; self::$module[$saveKey] = new $appModule($this->context, $apps); return self::$module[$saveKey]; }; $cacheKey = $this->appName . $contextKey . $extraCacheKey; $cache = function_exists('apc_fetch') ? new ApcCache() : new FilesystemCache($this->tmpDir); self::$compiler[$saveKey] = $compiler = DiCompiler::create($moduleProvider, $cache, $cacheKey, $this->tmpDir); return $compiler; }
} $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; require $fileName; }); use Ray\Di\Config; class Module extends \Ray\Di\AbstractModule { public function configure() { } } //Either use the injector directly, which works for the test but uses 19mb of RAM on this test and 203mb on Test 3 $injector = Ray\Di\Injector::create([new Module()]); //or use a compiled injector, which cannot be tested because it always returns the same instance. $cache = new \Doctrine\Common\Cache\MemcachedCache(); $m = new Memcached(); $m->addServer('localhost', 11211); $cache->setMemcached($m); $injector = \Ray\Di\DiCompiler::create($injector, $cache, 'ray', './tmp'); $a = $injector->getInstance('A'); $a1 = $injector->getInstance('A'); if ($a === $a1) { throw new Exception('Container returned the same instance'); } $t1 = microtime(true); for ($i = 0; $i < 10000; $i++) { $a = $injector->getInstance('A'); } $t2 = microtime(true); $results = ['time' => $t2 - $t1, 'files' => count(get_included_files()), 'memory' => memory_get_peak_usage() / 1024 / 1024]; echo json_encode($results);