【问题标题】:use of returning $this inside a method在方法中使用返回 $this
【发布时间】:2019-04-21 01:29:45
【问题描述】:

我使用 Laravel 和 eclipse 作为我的 IDE。我正在使用 laravel-ide-helper 包进行自动补全。

我正在从一个雄辩的模型对象调用方法。

当我输入时

User::find

eclipse 为我提供了:

find($id, $columns) : \Illuminate\Database\Eloquent\Model.

这意味着“find”方法返回一个 \Illuminate\Database\Eloquent\Model 实例。

但是,当我输入

User::where

eclipse 为我提供了以下内容:

where($column, $operator, $value, $boolean) : $this

表示函数“where”返回

$this

现在,我真的不知道 $this 是什么意思,因为据我了解,“哪里”应该返回一个查询构建器实例。据我所知, $this 表示方法的对象调用者(在此上下文中,用户模型本身)。但它显然没有返回模型。我怀疑我不明白 $this 在这种情况下的含义。

我错过了什么?

【问题讨论】:

  • 在这种情况下,$this 是查询生成器。查看Laravel Queries 文档。
  • @Stephen Lake 好吧。但是,通知我特定方法将返回什么对象不是 ide 和自动完成的工作吗?奇怪的是 find 之类的方法,eclipse 说它返回Illuminate\database\eloquent\Model。为什么只有 $this 在哪里?
  • 我无法回答这个问题,我不使用第三方自动完成包,但我觉得它不够智能,无法为您提供这些信息。虽然......查询构建器类型也是模型实例,所以返回本身确实有意义,但最好你谷歌搜索更多关于查询构建器和模型继承的信息,因为这需要一段时间详细说明。

标签: php eclipse laravel laravel-5 autocomplete


【解决方案1】:

find()where() 方法在 Model 类中存在,因此对这些方法的调用最终会落入 Laravel 拥有的 PHP 魔术方法 __call() 定义。在这个神奇的方法中,Laravel 将方法调用转发给一个新的查询构建器对象,确实有这些方法。

查询构建器类的find() 方法返回一个模型,它的where() 方法返回一个对自身的引用($this),这样您就可以流畅地将更多的方法调用链接到构建器。

所有这些都会使 IDE 难以提供提示 (IntelliSense),这就是 laravel-ide-helper 等软件包的用武之地。它们基本上会生成充满接口的文件,您的 IDE 可以使用这些接口来了解哪些神奇的方法和属性存在于各种类中,但在某些情况下,这些方法签名仍然无法满足您可能想了解的代码结构。

在这种情况下,IntelliSense 建议显然是从\Illuminate\Database\Eloquent\Builder::where() 的文档块中填充的:

/**
 * Add a basic where clause to the query.
 *
 * @param  string|array|\Closure  $column
 * @param  mixed   $operator
 * @param  mixed   $value
 * @param  string  $boolean
 * @return $this
 */
public function where($column, $operator = null, $value = null, $boolean = 'and');

可以看到返回类型定义为$this。在这一点上,一些 IDE 可能足够聪明,可以理解其含义并为该类的实例提供建议。但是,如果您的 IDE 正在解析的方法定义是由 laravel-ide-helper 等包生成的,这可能会变得更加复杂。在这种情况下,它不仅取决于 IDE 的功能,还取决于帮助程序包的输出。

【讨论】:

    【解决方案2】:

    Eclipse 完全使用源代码中的方法 cmets 来获取它的提示,所以如果你查看 Builder 的源代码,它是 query() 的返回类型,它有 find...

    /**
         * Find a model by its primary key.
         *
         * @param  mixed  $id
         * @param  array  $columns
         * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|null
         */
        public function find($id, $columns = ['*'])
    

    对于where() 它是...

    /**
         * Add a basic where clause to the query.
         *
         * @param  string|\Closure  $column
         * @param  string  $operator
         * @param  mixed   $value
         * @param  string  $boolean
         * @return $this
         */
        public function where($column, $operator = null, $value = null, $boolean = 'and')
        {
    

    由于它只能添加一个类型提示,它使用来自find() 的第一个提示,即\Illuminate\Database\Eloquent\Model,而来自where() 的唯一选项是$this

    【讨论】:

      猜你喜欢
      • 2020-12-05
      • 2012-04-26
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-28
      • 2019-08-17
      相关资源
      最近更新 更多