Phorce
Phorce

Reputation: 4642

PHP - Method Chaining - Best Approach?

I need a way to have breadcrumbs that are not generated from the URL.

My thought process is to have a class, "Breadcrumbs" which will work as:

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

Which will generate an array, and with each method chain it will push back into the array, resulting in one array which I can then turn into a URL structure.

I have tried the following:

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);
    }
}

This, however, does not provide an accurate result, and get 'unexpected '->'' when trying to do the structure as I plan to do.

Any ideas to where I am going wrong?

Upvotes: 3

Views: 62

Answers (2)

deceze
deceze

Reputation: 522016

  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
    

Upvotes: 5

jeoj
jeoj

Reputation: 653

You need to return $this from crumb to be able to do method chaining.

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

Upvotes: 1

Related Questions