今天我们来开始编辑整个框架核心Container,对于Container,之前有一篇文章有所介绍,文章底部我会附上链接。
在第一章节中我们介绍了需要用到的哪个包,那Container就是用的Laravel框架的包Container。
首先执行命令:
leiyu@leiyu-MacBook-Air > ~/data/Fine#> composer require illuminate/container
![2605b1f237d434d629d550f474694140.png](https://img-blog.csdnimg.cn/img_convert/2605b1f237d434d629d550f474694140.png)
这里我们发现下面有很多suggests(可选的包),其它有一个 friendsofphp/php-cs-fixer,这个包是用来修复代码格式的,当我们写代码的时候,不用时刻注意是否少换行,少空格括号不规范的问题,直到代码写完我们执行 `composer phpcs` 直接就会修复代码格式。
这样会自动下载所对应的包,下载完之前我们就要真开始写代码了。
创建Foundation目录及Application文件,这个类将会贯穿整个框架,通过继承Container来组织和融合整个框架和众多包之间的关系
![10d4e53be11dd4be5fbdcd889d48869f.png](https://img-blog.csdnimg.cn/img_convert/10d4e53be11dd4be5fbdcd889d48869f.png)
当我们使用了laravel的包,就意味着很多特性需要和laravel框架一样,比如:面向接口编程,ServiceProvider,Facade,类的别名,等等,下面来看看我们的Application到底该怎么写。
<?php
namespace FineFoundation;
use IlluminateContainerContainer;
use IlluminateContractsFoundationApplication as ContractsApplication;
class Application extends Container implements ContractsApplication {
const VERSION = 'alpha-0.0.1';
public function __construct($basePath = null) {
$this->registerBaseBindings();
}
protected function registerBaseBindings() {
static::setInstance($this);
$this->instance('app', $this);
$this->instance('IlluminateContainerContainer', $this);
}
/**
* Get the version number of the application.
* @return string
*/
public function version() {
return static::VERSION;
}
....//这里还有很多是接口里面必须实现的方法我就不一一写出来了,到时根据框架需要实现相应方法即可
}
在这里可以给大家提个小技巧,因为laravel已经实现过 IlluminateContractsFoundationApplication ,所以可以在IlluminateFoundation包里找到相应的代码,来看看自己实现的跟别人实现的有什么差别,然后再根据自己的实践情况作出改变。
对于这节我们主要是讲Container,至于怎么用,还是需要大概自己去理解和做测试
Laravel 核心对象之 Container
原文https://baijiahao.baidu.com/s?id=1618343807441221434&wfr=spider&for=pc