• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

laravelmake方法的作用是什么意思

武飞扬头像
PHP中文网
帮助10

在laravel中,make方法用于从容器当中解析一个type,该type是源码当中定义的,解析后返回的结果就是type的一个实例,容器类调用make方法时,若没有已注册的key,会自动通过反射类实例化具体类。

学新通技术网

laravel中make方法的作用是什么

Laravel中的make方法是用来从容器当中解析一个type,这个type是源码当中定义的,不是很好翻译成中文。解析后返回的结果就是type的一个实例。

看过源码的同学应该知道在Illuminate\Foundation\Application这个类和它的父类Illuminate\Container\Container类中都有make方法,那么当执行如index.php中的这行代码,

1 $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

     /**
      * Resolve the given type from the container. 从容器当中解析给定的type
      *
      * (Overriding Container::make) 覆盖了父类中的make方法
      *
      * @param  string  $abstract 给定的type
      * @param  array  $parameters 指定一些参数 可选项
      * @return mixed
      */
     public function make($abstract, array $parameters = [])
     {
         $abstract = $this->getAlias($abstract);//调用父类中的getAlias方法
      //如果在deferredServices这个数组设置了这个type并且在instances数组中没有设置这个type
         if (isset($this->deferredServices[$abstract]) && ! isset($this->instances[$abstract])) {
             $this->loadDeferredProvider($abstract);//那么就执行这个方法:加载被定义为延迟的服务提供者
       }
 
         return parent::make($abstract, $parameters);//调用父类的make方法
     }

好,我们一步一步的来,先看看这个getAlias方法,这个方法的作用就是返回这个类的别名,如果给出的是一个完整的类名且在aliases中已经设置了那么就返回这个类名的别名,如果没有设置过就返回这个类名本身,大家在看这个方法的时候可以先var_dump一下$app,对照着看里面的aliases数组,框架作者写这个方法真的很巧妙,至少这种递归方式在我实际开发当中很少用到。

    /**
      * Get the alias for an abstract if available.
     *
     * @param  string  $abstract
     * @return string
    *
     * @throws \LogicException
     */
    public function getAlias($abstract)
    {
         if (! isset($this->aliases[$abstract])) {
            return $abstract;
         }
 
        if ($this->aliases[$abstract] === $abstract) {
            throw new LogicException("[{$abstract}] is aliased to itself.");
        }
        return $this->getAlias($this->aliases[$abstract]);
     }

接下来就是对deferredServices和instances这个两个数组进行判断,在本例 $kernel = $app->make(Illuminate\Contracts\Http\Kernel::class); 当中,判断的结果为false,因此不执行loadDeferredProvider方法。

再接下来就是调用父类Illuminate\Container\Container中的make方法了,

     /**
      * Resolve the given type from the container.
      *
      * @param  string  $abstract
      * @param  array  $parameters
      * @return mixed
     */
     public function make($abstract, array $parameters = [])
     {
      return $this->resolve($abstract, $parameters);//直接调用resolve方法
 }

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tangbhhhf
系列文章
更多 icon
同类精品
更多 icon
继续加载