关于app()方法的疑问

例如:

这里有一个app方法调用,传入hash

app('hash')->make('password');<br></br>

找到app的源码,这里提示如果有关键字,就会return Container::getInstance()->make($make, $parameters)

function app($make = null, $parameters = [])
{
    if (is_null($make)) {
        return Container::getInstance();
    }
    return Container::getInstance()->make($make, $parameters);
}<br></br>

然后我再找到container的静态方法getInstance()的源码

public static function getInstance()
{
    return static::$instance;
}<br></br>

这里就有疑问了,这个静态调用虽然能够实时解析出当前的类,但是为什么就能够直接返回一个hash的container实例呢?这里也没看到他读取container的东西啊,为什么就能够实例出关键字hash的container呢,谢谢

Peter_Yuan_辉

代码没办法格式化- -

JellyBool

有了Container实例之后,执行make()方法就可以返回hash这个key对应的实例了,你看看Container类中make()的具体代码:

public function make($abstract, array $parameters = []){
    //看看这里
}

具体的视频可以看这个:
https://laravist.com/series/peak-into-laravel-core-components/episodes/2
https://laravist.com/series/peak-into-laravel-core-components/episodes/3

Peter_Yuan_辉

看了container的源码大概明白是怎么回事了,不过还有一个疑问,我之前是直接从app看源码(comm+B),去了helpers.php,那么是怎么转到container的源码去了呢?是怎么理解应该什么时候去看哪些源码?

Peter_Yuan_辉

视频已经看过了,看了好几次,不过还是没有说明清楚这里面之间的关系,例如,comm+B app()的话,那么是去了helpers.php那里,然后就突然说到了container的源码了,这里面是怎么连接的呢?

Tomoe

@Peter_Yuan_辉 可以在說得清楚些嗎?因為你最上面文中已經說出了為啥會這樣跳的原因了。

app() 這個方法算是 Laravel 這邊提供一個比較方便操作 Container 的方式,放在 helper 中並暴露給全局,其實你直接跳過 app() 使用 Container::getInstance()->make() 也是一樣的操作

Peter_Yuan_辉

@Tomoe 主要我是不明白application这个类是怎么来的,然后这个类是怎么变成Container的,其实这个是laravel启动的时候自动加载出来的,并且在application.php里面写了他是怎么完成这个转换的

`
protected function registerBaseBindings()
{
static::setInstance($this);

    $this->instance('app', $this);

    $this->instance('Illuminate\Container\Container', $this);
}

`
都在说怎么使用,但是并没有说这个是怎么来的,所以我来请教,不过问题已经解决了,谢谢大家。

airylinus

@Peter_Yuan_辉

class Application extends Container implements ApplicationContract, HttpKernelInterface

继承来的