我独自走进 Laravel5.5 的❤(八)

laravel 配置文件原理
一、用法
1.1创建配置文件

在 config 下建立一个 fun.php 文件,然后在编辑文件

return [
    'hobby' => 'football'
];

1.2 使用

在框架中使用

$myhobby = config('fun.hobby');
详细介绍请看文档介绍 https://learnku.com/docs/laravel/5.7/configuration/2243

二、实现源码

2.1 当http请求进入框架,

//生成一个 Illuminate\Foundation\Application 实例
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
//使用容器处理请求
$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

2.3 容器处理请求

Illuminate\Foundation\Http\Kernel.php

/**
* Handle an incoming HTTP request.
*
* @param  \Illuminate\Http\Request  $request
* @return \Illuminate\Http\Response
*/
public function handle($request)
{
    try {
        $request->enableHttpMethodParameterOverride();

        $response = $this->sendRequestThroughRouter($request);
    } catch (Exception $e) {
        $this->reportException($e);

        $response = $this->renderException($request, $e);
    } catch (Throwable $e) {
        $this->reportException($e = new FatalThrowableError($e));

        $response = $this->renderException($request, $e);
    }

    $this->app['events']->dispatch(
        new Events\RequestHandled($request, $response)
    );

    return $response;
}

2.4 向容器注入依赖并过滤请求

Illuminate\Foundation\Http\Kernel.php

/**
* Send the given request through the middleware / router.
* 通过中间件和路由器发送指定的请求
* @param  \Illuminate\Http\Request  $request
* @return \Illuminate\Http\Response
*/
protected function sendRequestThroughRouter($request)
{
    $this->app->instance('request', $request);
    Facade::clearResolvedInstance('request');

    $this->bootstrap(); //注入依赖
    return (new Pipeline($this->app))
                ->send($request)
                ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
                ->then($this->dispatchToRouter());
}

2.5 注入依赖
Illuminate\Foundation\Http\Kernel.php


/**
* Bootstrap the application for HTTP requests.
*为 http 请求启动应用
* @return void
*/
public function bootstrap()
{
    if (! $this->app->hasBeenBootstrapped()) {
        $this->app->bootstrapWith($this->bootstrappers());

    }
}

2.5.1 引入依赖

/**
* Get the bootstrap classes for the application.
* 为应获取启动类(就是依赖)
* @return array
*/
protected function bootstrappers()
{
    return $this->bootstrappers;
}

2.5.2 启动类

Illuminate\Foundation\Http\Kernel.php

 /**
* The bootstrap classes for the application.
* 应用的启动类
* @var array
*/
protected $bootstrappers = [
    \Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables::class,  //环境变量
    \Illuminate\Foundation\Bootstrap\LoadConfiguration::class,  //配置
    \Illuminate\Foundation\Bootstrap\HandleExceptions::class,  //异常处理
    \Illuminate\Foundation\Bootstrap\RegisterFacades::class,  //门面
    \Illuminate\Foundation\Bootstrap\RegisterProviders::class,  //服务提供者
    \Illuminate\Foundation\Bootstrap\BootProviders::class,  //触发服务提供者
];

2.6 加载配置

Illuminate\Foundation\Bootstrap\LoadConfiguration::class

/**
* Bootstrap the given application.
* 
* @param  \Illuminate\Contracts\Foundation\Application  $app
* @return void
*/
public function bootstrap(Application $app)
{
    $items = [];

    // First we will see if we have a cache configuration file. If we do, we'll load
    // the configuration items from that file so that it is very quick. Otherwise
    // we will need to spin through every configuration file and load them all.
    // 首先我们将看到我们是否有缓存配置文件,如果有,我们将直接从缓存文件拉去,因为这样速度飞快。
   //否则,我们将需要循序加载所有的配置文件
    if (file_exists($cached = $app->getCachedConfigPath())) {
        $items = require $cached;

        $loadedFromCache = true;
    }

    // Next we will spin through all of the configuration files in the configuration
    // directory and load each one into the repository. This will make all of the
    // options available to the developer for use in various parts of this app.
   //接着我们会循序将所有的配置文件加载到依赖库中。这样可以让所有的选项可提供开发者在应用中不同部分使用。
    $app->instance('config', $config = new Repository($items));

    if (! isset($loadedFromCache)) {
        $this->loadConfigurationFiles($app, $config);
    }

    // Finally, we will set the application's environment based on the configuration
    // values that were loaded. We will pass a callback which will be used to get
    // the environment in a web context where an "--env" switch is not present.
    //最后,我们会设置基于已经加载的配置参数的应用的环境。
    //我们会通过一个经常用于在web语义的”--env“选项获得环境
    $app->detectEnvironment(function () use ($config) {
        return $config->get('app.env', 'production');
    });

    date_default_timezone_set($config->get('app.timezone', 'UTC'));

    mb_internal_encoding('UTF-8');
}

2.6.1 获取配置单元

/**
* Load the configuration items from all of the files.
*
* @param  \Illuminate\Contracts\Foundation\Application  $app
* @param  \Illuminate\Contracts\Config\Repository  $repository
* @return void
* @throws \Exception
*/
protected function loadConfigurationFiles(Application $app, RepositoryContract $repository)
{
    $files = $this->getConfigurationFiles($app); //获取配置文件

    if (! isset($files['app'])) {
        throw new Exception('Unable to load the "app" configuration file.');
    }

    foreach ($files as $key => $path) {
        $repository->set($key, require $path);
    }
}

2.6.2 获取配置文件

/**
* Get all of the configuration files for the application.
* 为应用获取所有的配置文件
* @param  \Illuminate\Contracts\Foundation\Application  $app
* @return array
*/
protected function getConfigurationFiles(Application $app)
{
    $files = [];

    $configPath = realpath($app->configPath());

    foreach (Finder::create()->files()->name('*.php')->in($configPath) as $file) {
        $directory = $this->getNestedDirectory($file, $configPath);

        $files[$directory.basename($file->getRealPath(), '.php')] = $file->getRealPath();
    }

    ksort($files, SORT_NATURAL);

    return $files;
}

通过 Finder 获得 config 下的所有配置文件

2.6.3 为依赖库注入配置

Illuminate\Config\Repository::class

/**
* Set a given configuration value.
* 根据数组获取其指定的配置
* @param  array|string  $key
* @param  mixed   $value
* @return void
*/
public function set($key, $value = null)
{
    $keys = is_array($key) ? $key : [$key => $value];

    foreach ($keys as $key => $value) {
        Arr::set($this->items, $key, $value);
    }
}

2.6.4 helpers->config()

/**
* Get / set the specified configuration value.
*
* If an array is passed as the key, we will assume you want to set an array of values.
*
* @param  array|string  $key
* @param  mixed  $default
* @return mixed|\Illuminate\Config\Repository
*/
function config($key = null, $default = null)
{
    if (is_null($key)) {
        return app('config');
    }

    if (is_array($key)) {
        return app('config')->set($key);
    }

    return app('config')->get($key, $default);
}

2.6.5 根据字符串获取配置

Illuminate\Config\Repository

/**
* Get the specified configuration value.
* 获取指定的配置值
* @param  array|string  $key
* @param  mixed   $default
* @return mixed
*/
public function get($key, $default = null)
{
    if (is_array($key)) {
        return $this->getMany($key);
    }

    return Arr::get($this->items, $key, $default);
}

<--------------------- End ---------------------->
以上便是 lara 配置涉及到的流程,如果有啥不对,请指出,互相学习。

至此,

致敬知识。

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!