【问题标题】:What do this called in PHP这在 PHP 中叫什么
【发布时间】:2014-04-11 17:26:00
【问题描述】:

中可能会找到如下代码:

return View::make('hello')->with('name', $name);

我知道的是:

  • View 是一个类
  • makeView 类的一种方法
  • 'hello' 是传递给方法make 的参数

我不知道的是:with 是不是一种方法的方法?!它是 PHP 关键字吗?还是在make 方法中定义了一些东西(如果是,它的定义是什么?)?

【问题讨论】:

  • 在我看来像视图对象的方法
  • makewith 方法返回一些东西(我认为 make 返回新视图)
  • @JohnConde 如果是一个方法,那么在面向对象编程中有什么叫做方法的方法吗?
  • @JohnConde 根据wiki pedia Fluent interface 和 Method Chaining 不同,那么这个场景是 Fluent interface 还是 Method Chaining?
  • 这其实都是

标签: laravel php oop laravel fluent-interface method-chaining


【解决方案1】:
class View() {
  protected $name;
  public function __construct($name){$this->name = $name;}
  public function with($s, $p){return $this;}
  public static function make($name){
    return new self($name);
  }
}

make - 类的静态方法
with - View 对象的方法

View::make('hello')->with('name', $name);如下:

$view = View::make('hello');
$view->with('name', $name);

return $thisin with 方法允许我们跟随:

View::make('hello')->with('name1', $name1)
                   ->with('name2', $name2)
                   ->with('name3', $name3);

这种模式名为chaining

【讨论】:

    【解决方案2】:

    这是method chainingwith 也只是 View 类的一个函数。可链接的类函数返回对类本身的引用,因此您可以在同一行中调用其他方法。因此,您可以这样做,而不是为类实例创建变量并在新行中调用每个函数:

    View::make('view')
        ->with('id', $id)
        ->with('title', $title)
        ->with('name', $name);
    

    如果没有方法链接,它会是这样的:

    $view = View::make('view');
    $view->with('id', $id);
    $view->with('title', $title);
    $view->with('name', $name);
    

    此外,当您执行 View::make 时,您实际上调用了 View 类的 make 函数而没有实例化该类,因此您不必这样做:

    $view = new View();
    $view->make('view');
    

    但是,由于make() 创建了一个类实例化,您仍然会得到一个类实例化,但我们的目标是让事情变得简单。我们希望通过丢弃明显增加代码噪音的行来创建一个具有最少可读代码的视图,但由于 PHP 的性质,我们不得不编写它们。这种理念让 Laravel 变得如此美丽。

    【讨论】:

      【解决方案3】:

      根据documentation,ViewComposers 使用 with 方法,将 with 方法中传递的变量绑定到要显示的视图

      【讨论】:

        猜你喜欢
        • 2011-06-18
        • 1970-01-01
        • 2011-05-18
        • 2022-06-17
        • 2019-06-26
        • 1970-01-01
        • 2023-03-05
        • 2013-05-08
        • 2011-04-12
        相关资源
        最近更新 更多