PHP - 方法链 - 最佳实践?

3

我需要一种不是根据URL生成面包屑导航的方法。

我的想法是创建一个名为“Breadcrumbs”的类,其作用如下:

$breadcrumbs = new BreadCrumb('<<')->crumb('www.google.com', 'Google')->crumb('www.youtube.com', 'Youtube');

这将生成一个数组,并随着每个方法链的执行,将内容添加到数组中,最终形成一个数组,我可以将其转换为URL结构。

我尝试了以下方法:

class Breadcrumbs {

    public $del; 
    public $breadcrumbs;

    public function __construct($del)
    {
        $this->breadcrumbs = array();
        $this->del = $del;  

    }

    public function crumb($uri, $name)
    {
         $this->breadcrumbs[] = array($uri => $name);
    }
}

然而,这并不能提供准确的结果,并且在尝试按照我的计划进行结构时会出现“unexpected '->''”。

你有任何想法我做错了哪里吗?

2个回答

5
  1. To do method chaining, you need to return an object from your method call. Typically you'll want:

    return $this;  // in function crumb()
    
  2. The correct syntax to instantiate an object and immediately call a method on it is:

    (new BreadCrumb('<<'))->crumb(..)
    

    Without the extra parentheses it's ambiguous to PHP what you want to do.

  3. Aside: you don't need to initialise your array inside the constructor, you can do that while declaring the array:

    public $breadcrumbs = array();
    
  4. Aside: this is pretty inefficient:

    .. = array($uri => $name)
    

    You'll have a hard time getting that $uri key back out of the array, which makes your code unnecessarily complicated. You should simply do:

    $this->breadcrumbs[$uri] = $name;
    

    Alternatively, if your URIs aren't guaranteed to be unique, use a structure that's easier to work with later:

    $this->breadcrumbs[] = array($uri, $name);  // $arr[0] is the URI, $arr[1] the name
    

2
+1。但请注意,第二点(对象解引用)需要 PHP 5.4 或更高版本。你现在应该使用 5.4+,但如果你没有的话,这是另一个升级的好理由。 - Simba

1

为了能够进行方法链接,您需要从crumb返回$this

public function crumb($uri, $name)
{
     $this->breadcrumbs[] = array($uri => $name);
     return $this;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接