swoft: 1.0.0 源码解读-1
//www.greatytc.com/p/fd3ecea1636e
-
self::$container->addDefinitions($definition);
// 将自启bootBean对象的definition添加到container的definition属性中
public function addDefinitions(array $definitions)
{
$resource = new DefinitionResource($definitions);
$this->definitions = array_merge($resource->getDefinitions(), $this->definitions);
}
// Swoft\Bean\Resource\DefinitionResource
public function __construct($definitions)
{
$this->definitions = $definitions;
$this->properties = $definitions['config']['properties']??[];
}
public function getDefinitions()
{
$definitions = [];
foreach ($this->definitions as $beanName => $definition) {
$definitions[$beanName] = $this->resolvedefinitation($beanName, $definition);
}
return $definitions;
}
public function resolvedefinitation(string $beanName, array $definition)
{
if (!isset($definition['class'])) {
throw new \InvalidArgumentException("definitions of bean 初始化失败,class字段没有配置,Data=" . json_encode($definition));
}
$className = $definition['class'];
unset($definition['class']);
// 初始化
$objDefinitation = new ObjectDefinition();
$objDefinitation->setName($beanName);
$objDefinitation->setClassName($className);
// ===========// 启动阶段没有作用=============
// 解析属性和构造函数
list($propertyInjections, $constructorInjection) = $this->resolverPropertiesAndConstructor($definition);
// 设置属性和构造函数
$objDefinitation->setPropertyInjections($propertyInjections);
if ($constructorInjection != null) {
$objDefinitation->setConstructorInjection($constructorInjection);
}
// ============================================
return $objDefinitation;
}
-
self::$container->initBeans();
// 初始化bean,只有包含了类注解的php类,并被扫描该类存在container对象的definitions属性上bean才会被初始化
public function initBeans()
{
// 获取配置autoInitBean 默认为true /config/app.php
$autoInitBeans = $this->properties['autoInitBean'] ?? false;
if (!$autoInitBeans) {
return;
}
// 循环初始化
foreach ($this->definitions as $beanName => $definition) {
$this->get($beanName);
}
}
总结: swoft服务启动流程如下
-
Swoft\Bean\Resource\ServerAnnotationResource
resource 对象
1.1resource->customComponents
绑定自定义组件resource->componentNamespaces
绑定所有组件命名空间resource->scanNamespaces
绑定swoft组件和自定义组件扫描的命名空间resource->annotation
解析扫描类之后,将class上的类注解、属性注解、方法注解依此绑定到annotation属性上resource->definitions
依据resource下annotation属性,每个注解都有wapper类,用来处理注入的注解是否符合规则,后续通过 注解parser 解析注解、注解collector搜集,将注入的bean对象和基本类型数据绑定到definitions属性上 Swoft\Bean\Container
container对象
2.1container->definitions
将通过resource上definitions和container对象的definitions属性合并并绑定到container对象上
2.2container->singletonEntries
通过之前definitions上定义的bean,在获取bean的过程中,如果是单例将会绑定到singletonEntries属性上