你知道Laravel的$this->app以及app()是怎么来的吗?

2022-05-15 0 1,011

下面由laravel教程栏目给大家介绍Laravel的$this->app以及app()是怎么来的,希望对需要的朋友有所帮助!

断点调试寻找对应文件,忽略次要步骤,仅描述核心动作,‘/’表示index.php所在目录

地址:index.php

$app = require_once __DIR__.'/../bootstrap/app.php';

$app初始化

路径/…/bootstrap/app.php

$app = new Illuminate\\Foundation\\Application(    realpath(__DIR__.'/../'));//$app初始化工作

$app初始化的类及构造函数

class Application extends Container implements ApplicationContract,HttpKernelInterface{    //继承Container类,Container类实现应用契约接口与请求接口    public function __construct($basePath = null){       if ($basePath) {//$basePath = '/../'           $this->setBasePath($basePath);//路径绑定       }       $this->registerBaseBindings();//基础绑定       $this->registerBaseServiceProviders();//注册基础服务提供者       $this->registerCoreContainerAliases();//注册别名    }}

路径绑定

Application的setBasePath(’/…/’)方法调用Container的instance(a b s t r a c t , abstract,abstract,instance)方法赋值Contaienr类instancesinstances: array:9 [▼“path” => “\\var\\www\\app”“path.base” => “\\var\\www”“path.lang” => “\\var\\www\\resources\\lang”“path.config” => “\\var\\www\\config”“path.public” => “\\var\\www\\public”“path.storage” => “\\var\\www\\storage”“path.database” => “\\var\\www\\database”“path.resources” => “\\var\\www\\resources”“path.bootstrap” => “\\var\\www\\bootstrap”]

基础绑定

向Container的instances中添加绑定

    "app" => Application {#2}      "Illuminate\\Container\\Container" => Application {#2}      "Illuminate\\Foundation\\PackageManifest" => PackageManifest {#4 ▼            +files: Filesystem {#5}            +basePath: "\\var\\www"            +vendorPath: "\\var\\www\\vendor"            +manifestPath: "\\var\\www\\bootstrap\\cache\\packages.php"            +manifest: null        }

app与Container指向当前实例

PackageMainfest 为包管理实例,构造方法中files注册文件系统实例

注册基础服务提供者

//class Applicationprotected function registerBaseServiceProviders(){    $this->register(new EventServiceProvider($this));    $this->register(new LogServiceProvider($this));    $this->register(new RoutingServiceProvider($this));}

Event、Log、Routing基础服务继承ServiceProvider,初始化的时候将app属性赋值Application实例

//class ServiceProvider    public function __construct($app){    $this->app = $app;}

执行Application类register方法

//Applicationpublic function register($provider, $options = [], $force = false){    if (is_string($provider)) {        $provider = $this->resolveProvider($provider);    }    if (method_exists($provider, 'register')) {        $provider->register();//赋值bindings    }    //将服务提供者添加到serviceProviders属性队列    //将服务提供者类名添加到loaderProviders属性    $this->markAsRegistered($provider);    return $provider;}

为provider注册提供了两种方法;

一种是字符串类名直接实例,

一种是执行$$provider->register()方法注册,

当前执行第二种方法,

回看当前EventServiceProvider实例的register方法

public function register(){    $this->app->singleton('events', function ($app) {        return (new Dispatcher($app))->setQueueResolver(function () use ($app) {            return $app->make(QueueFactoryContract::class);        });    });}

调用Application实例的singleton方法

//class Continerpublic function singleton($abstract, $concrete = null){    $this->bind($abstract, $concrete, true);}

调用bind方法,赋值bindings

//class Containerpublic function bind($abstract, $concrete = null, $shared = false){    if (is_null($concrete)) {        $concrete = $abstract;    }    if (! $concrete instanceof Closure) {        $concrete = $this->getClosure($abstract, $concrete);    }    $this->bindings[$abstract] = compact('concrete', 'shared');}

回到Application类register方法中并执行markAsRegistered($provider)

//class Applicationprotected function markAsRegistered($provider){    $this->serviceProviders[] = $provider;    $this->loadedProviders[get_class($provider)] = true;}

LogServerProvider、RoutingServiceProvider与之类似

别名绑定

//class Applicationpublic function registerCoreContainerAliases(){    foreach ([        'app'                  => [self::class, \\Illuminate\\Contracts\\Container\\Container::class, \\Illuminate\\Contracts\\Foundation\\Application::class,  \\Psr\\Container\\ContainerInterface::class],        'auth'                 => [\\Illuminate\\Auth\\AuthManager::class, \\Illuminate\\Contracts\\Auth\\Factory::class],        'auth.driver'          => [\\Illuminate\\Contracts\\Auth\\Guard::class],        'blade.compiler'       => [\\Illuminate\\View\\Compilers\\BladeCompiler::class],        'cache'                => [\\Illuminate\\Cache\\CacheManager::class, \\Illuminate\\Contracts\\Cache\\Factory::class],        'cache.store'          => [\\Illuminate\\Cache\\Repository::class, \\Illuminate\\Contracts\\Cache\\Repository::class],        'config'               => [\\Illuminate\\Config\\Repository::class, \\Illuminate\\Contracts\\Config\\Repository::class],        'cookie'               => [\\Illuminate\\Cookie\\CookieJar::class, \\Illuminate\\Contracts\\Cookie\\Factory::class, \\Illuminate\\Contracts\\Cookie\\QueueingFactory::class],        'encrypter'            => [\\Illuminate\\Encryption\\Encrypter::class, \\Illuminate\\Contracts\\Encryption\\Encrypter::class],        'db'                   => [\\Illuminate\\Database\\DatabaseManager::class],        'db.connection'        => [\\Illuminate\\Database\\Connection::class, \\Illuminate\\Database\\ConnectionInterface::class],        'events'               => [\\Illuminate\\Events\\Dispatcher::class, \\Illuminate\\Contracts\\Events\\Dispatcher::class],        'files'                => [\\Illuminate\\Filesystem\\Filesystem::class],        'filesystem'           => [\\Illuminate\\Filesystem\\FilesystemManager::class, \\Illuminate\\Contracts\\Filesystem\\Factory::class],        'filesystem.disk'      => [\\Illuminate\\Contracts\\Filesystem\\Filesystem::class],        'filesystem.cloud'     => [\\Illuminate\\Contracts\\Filesystem\\Cloud::class],        'hash'                 => [\\Illuminate\\Contracts\\Hashing\\Hasher::class],        'translator'           => [\\Illuminate\\Translation\\Translator::class, \\Illuminate\\Contracts\\Translation\\Translator::class],        'log'                  => [\\Illuminate\\Log\\Writer::class, \\Illuminate\\Contracts\\Logging\\Log::class, \\Psr\\Log\\LoggerInterface::class],        'mailer'               => [\\Illuminate\\Mail\\Mailer::class, \\Illuminate\\Contracts\\Mail\\Mailer::class, \\Illuminate\\Contracts\\Mail\\MailQueue::class],        'auth.password'        => [\\Illuminate\\Auth\\Passwords\\PasswordBrokerManager::class, \\Illuminate\\Contracts\\Auth\\PasswordBrokerFactory::class],        'auth.password.broker' => [\\Illuminate\\Auth\\Passwords\\PasswordBroker::class, \\Illuminate\\Contracts\\Auth\\PasswordBroker::class],        'queue'                => [\\Illuminate\\Queue\\QueueManager::class, \\Illuminate\\Contracts\\Queue\\Factory::class, \\Illuminate\\Contracts\\Queue\\Monitor::class],        'queue.connection'     => [\\Illuminate\\Contracts\\Queue\\Queue::class],        'queue.failer'         => [\\Illuminate\\Queue\\Failed\\FailedJobProviderInterface::class],        'redirect'             => [\\Illuminate\\Routing\\Redirector::class],        'redis'                => [\\Illuminate\\Redis\\RedisManager::class, \\Illuminate\\Contracts\\Redis\\Factory::class],        'request'              => [\\Illuminate\\Http\\Request::class, \\Symfony\\Component\\HttpFoundation\\Request::class],        'router'               => [\\Illuminate\\Routing\\Router::class, \\Illuminate\\Contracts\\Routing\\Registrar::class, \\Illuminate\\Contracts\\Routing\\BindingRegistrar::class],        'session'              => [\\Illuminate\\Session\\SessionManager::class],        'session.store'        => [\\Illuminate\\Session\\Store::class, \\Illuminate\\Contracts\\Session\\Session::class],        'url'                  => [\\Illuminate\\Routing\\UrlGenerator::class, \\Illuminate\\Contracts\\Routing\\UrlGenerator::class],        'validator'            => [\\Illuminate\\Validation\\Factory::class, \\Illuminate\\Contracts\\Validation\\Factory::class],        'view'                 => [\\Illuminate\\View\\Factory::class, \\Illuminate\\Contracts\\View\\Factory::class],    ] as $key => $aliases) {        foreach ($aliases as $alias) {            $this->alias($key, $alias);        }    }}

为alias属性赋值

$app核心类绑定

/…/bootstrap/app.php/** *核心类绑定 */$app->singleton(    Illuminate\\Contracts\\Http\\Kernel::class,    App\\Http\\Kernel::class);$app->singleton(    Illuminate\\Contracts\\Console\\Kernel::class,    App\\Console\\Kernel::class);$app->singleton(    Illuminate\\Contracts\\Debug\\ExceptionHandler::class,    App\\Exceptions\\Handler::class);

调用bind函数

//class Containerpublic function singleton($abstract, $concrete = null){    $this->bind($abstract, $concrete, true);}

对字符串类名进行默认回调函数绑定

//class Containerpublic function bind($abstract, $concrete = null, $shared = false){    // If the factory is not a Closure, it means it is just a class name which is    // bound into this container to the abstract type and we will just wrap it    // up inside its own Closure to give us more convenience when extending.    if (! $concrete instanceof Closure) {        $concrete = $this->getClosure($abstract, $concrete);    }    $this->bindings[$abstract] = compact('concrete', 'shared');}

getClosure返回默认回调函数

//class Containerprotected function getClosure($abstract, $concrete){    return function ($container, $parameters = []) use ($abstract, $concrete) {        if ($abstract == $concrete) {            return $container->build($concrete);        }        return $container->make($concrete, $parameters);    };}

最终:返回$app

/…/bootstrap/app.phpreturn $app;

相关推荐:最新的五个Laravel视频教程

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

【声明:根据2013年1月30日《计算机软件保护条例》2次修订第17条规定: 为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存 储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬! 鉴于此,也希望大家按此说明研究软件!】
本站所有源码尽量保证原汁原味,如有特殊情况会作出声明及标注,网站资源不做任何二次加密(原版加密除外,不影响程序使用的不会做解密处理),方便您更好的学习参考。 在您的能力范围内,为了大环境的良性发展,请尽可能的选择正版资源。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

即刻码站__国内靠谱的站长资源下载平台 php教程 你知道Laravel的$this->app以及app()是怎么来的吗? https://www.jike1995.com/36484.html

常见问题
  • 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用
查看详情
  • 最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度
查看详情

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务