/** * Build service cache block * * @return string Service cache block */ public function buildServiceCacheBlock() { $cacheContent = ''; $this->serviceDefinitionChain->each(function (ServiceDefinition $serviceDefinition) use(&$cacheContent) { $serviceName = $serviceDefinition->getName(); $serverClass = $serviceDefinition->getClass(); $cacheArgumentsStack = array(); $serviceDefinition->getArgumentChain()->each(function (Argument $argument) use(&$cacheDefinition, &$cacheArgumentsStack) { $argumentValue = $argument->getValue(); if ($argument instanceof ServiceArgument) { $method = $this->getCachedServiceMethodName($argumentValue); $cacheArgumentsStack[] = "\$this->{$method}()"; } elseif ($argument instanceof ParameterArgument) { $cacheArgumentsStack[] = "\$this->parameters[\"{$argumentValue}\"]"; } else { $cacheArgumentsStack[] = var_export($argumentValue, true); } }); $serviceCacheableMethod = self::getCachedServiceMethodName($serviceName); $cacheArguments = ''; if ($cacheArgumentsStack) { $cacheArguments = "\n " . implode(', ', $cacheArgumentsStack) . "\n "; } $cacheContent .= "/**\n * Return instance of service {$serviceName}\n *\n * @return {$serverClass} Service instance\n */\n public function {$serviceCacheableMethod}()\n {\n return new {$serverClass}({$cacheArguments});\n }\n\n "; }); return $cacheContent; }
/** * Get service instance * * @param string $serviceName Service Name * * @return mixed Service instance * * @throws DoppoNotCompiledException Container not compiled yet * @throws DoppoServiceNotExistsException Service not found */ public function get($serviceName) { if (!$this->compiled) { throw new DoppoNotCompiledException('Container should be compiled before being used'); } /** * The service is found as an instance, so we can be ensured that the * value inside this position is a valid Service instance */ if (isset($this->serviceInstances[$serviceName])) { return $this->serviceInstances[$serviceName]; } /** * Otherwise, we must check if the service defined with its name has * been compiled */ if (!$this->services->has($serviceName)) { throw new DoppoServiceNotExistsException(sprintf('Service "%s" not found', $serviceName)); } return $this->serviceInstances[$serviceName] = $this->buildExistentService($serviceName); }