zend framework2 code analysis
Zend\Mvc\Application::init(require 'config/application.config.php')->run();
Init passes in an array of parameters, and the distribution of modules is set in confi/application.config.php
Application's init
public static function init($configuration = array())
{
$smConfig = isset($configuration['service_manager']) ? $configuration['service_manager'] : array();
$listeners = isset($configuration['listeners']) ? $configuration['listeners'] : array();
$serviceManager = new ServiceManager(new Service\ServiceManagerConfig($smConfig));
$serviceManager->setService('ApplicationConfig', $configuration);
$serviceManager->get('ModuleManager')->loadModules();
return $serviceManager->get('Application')->bootstrap($listeners);
}
1. Put the incoming configuration parameters into the ApplicationConfig of the serviceManager2. Load the module
3. Service\ServiceManagerConfig registers events and module factories
protected $factories = array( 'EventManager' => 'Zend\Mvc\Service\EventManagerFactory', 'ModuleManager' => 'Zend\Mvc\Service\ModuleManagerFactory', );
The following is when ServiceManger is constructed, set itself through config, and the factory set in $config is injected into serviceManger,
public function __construct(ConfigInterface $config = null) { if ($config) { $config->configureServiceManager($this); } } }
public function configureServiceManager(ServiceManager $serviceManager)
{
foreach ($this->invokables as $name => $class) {
$serviceManager->setInvokableClass($name, $class);
}
foreach ($this->factories as $name => $factoryClass) {
$serviceManager->setFactory($name, $factoryClass);
}
foreach ($this->abstractFactories as $factoryClass) {
$serviceManager->addAbstractFactory($factoryClass);
}
foreach ($this->aliases as $name => $service) {
$serviceManager->setAlias($name, $service);
}
foreach ($this->shared as $name => $value) {
$serviceManager->setShared($name, $value);
}
$serviceManager->addInitializer(function ($instance) use ($serviceManager) {
if ($instance instanceof EventManagerAwareInterface) {
if ($instance->getEventManager() instanceof EventManagerInterface) {
$instance->getEventManager()->setSharedManager(
$serviceManager->get('SharedEventManager')
);
} else {
$instance->setEventManager($serviceManager->get('EventManager'));
}
}
});
$serviceManager->addInitializer(function ($instance) use ($serviceManager) {
if ($instance instanceof ServiceManagerAwareInterface) {
$instance->setServiceManager($serviceManager);
}
});
$serviceManager->addInitializer(function ($instance) use ($serviceManager) {
if ($instance instanceof ServiceLocatorAwareInterface) {
$instance->setServiceLocator($serviceManager);
}
});
$serviceManager->setService('ServiceManager', $serviceManager);
$serviceManager->setAlias('Zend\ServiceManager\ServiceLocatorInterface', 'ServiceManager');
$serviceManager->setAlias('Zend\ServiceManager\ServiceManager', 'ServiceManager');
}
serviceManager->get("ModuleManger") brings a lot of operations, as follows
public function get($name, $usePeeringServiceManagers = true)
{
// inlined code from ServiceManager::canonicalizeName for performance
if (isset($this->canonicalNames[$name])) {
$cName = $this->canonicalNames[$name];
} else {
$cName = $this->canonicalizeName($name);
}
$isAlias = false;
if (isset($this->aliases[$cName])) {
$isAlias = true;
do {
$cName = $this->aliases[$cName];
} while ($this->hasAlias($cName));
}
$instance = null;
if ($usePeeringServiceManagers && $this->retrieveFromPeeringManagerFirst) {
$instance = $this->retrieveFromPeeringManager($name);
if (null !== $instance) {
return $instance;
}
}
if (isset($this->instances[$cName])) {
return $this->instances[$cName];
}
if (!$instance) {
if (
isset($this->invokableClasses[$cName])
|| isset($this->factories[$cName])
|| isset($this->aliases[$cName])
|| isset($this->instances[$cName])
|| $this->canCreateFromAbstractFactory($cName, $name)
) {
$instance = $this->create(array($cName, $name));
} elseif ($usePeeringServiceManagers && !$this->retrieveFromPeeringManagerFirst) {
$instance = $this->retrieveFromPeeringManager($name);
}
}
// Still no instance? raise an exception
if ($instance === null) {
if ($isAlias) {
throw new Exception\ServiceNotFoundException(sprintf(
'An alias "%s" was requested but no service could be found.',
$name
));
}
throw new Exception\ServiceNotFoundException(sprintf(
'%s was unable to fetch or create an instance for %s',
get_class($this) . '::' . __FUNCTION__,
$name
));
}
if (
($this->shareByDefault && !isset($this->shared[$cName]))
|| (isset($this->shared[$cName]) && $this->shared[$cName] === true)
) {
$this->instances[$cName] = $instance;
}
return $instance;
}
protected function createFromFactory($canonicalName, $requestedName)
{
$factory = $this->factories[$canonicalName];
if (is_string($factory) && class_exists($factory, true)) {
$factory = new $factory;
$this->factories[$canonicalName] = $factory;
}
if ($factory instanceof FactoryInterface) {
$instance = $this->createServiceViaCallback(array($factory, 'createService'), $canonicalName, $requestedName);
} elseif (is_callable($factory)) {
$instance = $this->createServiceViaCallback($factory, $canonicalName, $requestedName);
} else {
throw new Exception\ServiceNotCreatedException(sprintf(
'While attempting to create %s%s an invalid factory was registered for this instance type.',
$canonicalName,
($requestedName ? '(alias: ' . $requestedName . ')' : '')
));
}
return $instance;
}
After creating the factory, you need to create an instance
protected function createServiceViaCallback($callable, $cName, $rName)
{
static $circularDependencyResolver = array();
$depKey = spl_object_hash($this) . '-' . $cName;
if (isset($circularDependencyResolver[$depKey])) {
$circularDependencyResolver = array();
throw new Exception\CircularDependencyFoundException('Circular dependency for LazyServiceLoader was found for instance ' . $rName);
}
try {
$circularDependencyResolver[$depKey] = true;
$instance = call_user_func($callable, $this, $cName, $rName);
unset($circularDependencyResolver[$depKey]);
} catch (Exception\ServiceNotFoundException $e) {
unset($circularDependencyResolver[$depKey]);
throw $e;
} catch (\Exception $e) {
unset($circularDependencyResolver[$depKey]);
throw new Exception\ServiceNotCreatedException(
sprintf('An exception was raised while creating "%s"; no instance returned', $rName),
$e->getCode(),
$e
);
}
if ($instance === null) {
throw new Exception\ServiceNotCreatedException('The factory was called but did not return an instance.');
}
return $instance;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.