Use PHP Method Chaining to Build Breadcrumbs for Your Website

Created by josh
July 12, 2016 11:53:48 PM PDT


Learn how to build a series of "breadcrumbs" using a PHP object to chain methods.

Breadcrumbs visually help users navigate through levels of a website. This type of navigation is a visual hierarchy of the user's current location in reference to the main landing page (homepage).

Creating these on each page is generally easy if your website is organized well. Using PHP, we can build an object that makes this process intuitive.

Chaining methods in PHP realistically means to invoke the object (class in this case), run a method within the object, and using the syntax to compose/run another method within the class, keep running methods in a series called "method chaining."

It looks something like:

<?php

class ChainMe
{

    public $item;

    public function __construct(){}

    public function subject($var)
    {

        $this->item = 'Subject: ' . $var;

        return $this;

    }

    public function message($var)
    {

        $this->item = 'Message: ' . nl2br($var);

        return $this;

    }

}

 

Since each of these public methods return "$this" (the object itself), you can "chain" these methods together like:

<?php

$chain = new ChainMe();

$message = $chain->subject('Hello')->message("Hey,\n\nI am just a test message");

 

Let's use a practical example.

So now that you're here looking at this blog post, you probably also noticed the big green nav bar and menu up top, followed by the big "title" for this post... then just below that, the "breadcrumbs" that illustrate which page/level you are currently at within the website. Having this simple little added touch on your site's pages is a GREAT way to improve your website's SEO. Search engines and users love having a relevant trail of where they are when viewing a web page. 

PHP makes it easy to build a class object and mark-up these tags on whatever page you'd like. Let me show you!

The class object is setup like this:

<?php

namespace View\SEO;

class Breadcrumbs
{

    public $crumbs = array();

    /**
     * Create the "first" crumb that all pages will use
     *
     * Breadcrumbs constructor.
     */
    public function __construct()
    {

        $this->crumb('Home', WEB_URL);

    }

    /**
     * A single crumb - becomes an array
     *
     * @param $label
     * @param bool $url
     * @return $this
     */
    public function crumb($label, $url = false)
    {

        // if no URL is specified, use current URI so url is "self"
        $url = $url ? filter_var($url, FILTER_SANITIZE_URL) : $_SERVER['REQUEST_URI'];

        $this->crumbs[] = Array(
            'label' => strip_tags(trim($label)),
            'url' => $url,
        );

        return $this;

    }

    /**
     * A magic method of awesomeness that will be used to determine how this
     * object will output when treated (or "typecasted") as a string.
     *
     * @return null|string
     */
    public function __toString()
    {

        // sanity check - shouldnt happen because the very first crumb is set in the constructor
        if(empty($this->crumbs)) return null;

        $crumb_display = null;

        foreach ($this->crumbs as $key => $value)
        {

            // first crumb_display does not get arrow before-hand
            // the double-arrow-head character that looks like ">>" (without quotes) and wrapped with non-breaking spaces
            $crumb_display .= $key == (int) 0 ? null : '&#160;&#187;&#160;';
            $crumb_display .= '<a href="' . $value['url'] . '">' . $value['label'] . '</a>';

        }

        return '<div class="breadcrumbs">' . $crumb_display . '</div>';

    }

}

 

In the controller of this blog, I have logic that assembles the breadcrumbs based on the blog you are viewing right now. The page "up one level" from this, in this example, is a page that shows a list of blogs - that list includes the link to the blog right here.

<?php

// invoke object
$breadcrumbs = new \View\SEO\Breadcrumbs();

// $breadcrumb looks like "Home >> Blog >> Use Php Method Chaining to Build Breadcrumbs for Your Website"
$breadcrumbs = $breadcrumbs->crumb('Blog', '/blog.html')->crumb('Use Php Method Chaining to Build Breadcrumbs for Your Website');

 

That's pretty much it! Just echo out the "$breadcrumbs" on the part of the page you'd like to see breadcrumbs.