Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







What Is Method Chaining In PHP?


PHP METHOD CHAINING PHP
18th May 2020 3 mins read
Share Article     Share On WhatsApp   Buy Me Coffee | StackCoder Buy Coffee


Hi folks in this article I would like to share what is Method Chaining in PHP. I would like to tell my how I got fascinated to it and started to implement as much as possible in my daily life.


You will learn


  1. What Is Method Chaining
  2. Why Do You Use It?
  3. Lets Built With Example
  4. Advantages & DisAdvantages

What The Hell Is Method Chaining


Hope you might have come across the code like the following which is very fluent and simple to chain the method callbacks. Nowadays in most of the frameworks then do use it.


Example: Larvel - Eloquent, Codeigniter - ActiveRecords to mention some.


$rss->siteName('SiteName')
    ->siteUrl('https://siteurl.com')
    ->description('Some random description of the site')
    ->language('en-US') /** Default is en-Us you can set any of yours */
    ->lastUpdated($feedItems[0]['updatedAt']) /** Just pass datetime string or date string */
    ->generate($path, $rssItems, $filename);


OMG! Yes. Yup this is what method chaining is, basically you chain the output of one method and add it as input to upcoming methods context.

Why Do I Need It?


Without method chaining you would have to keep it in many intermediate variables.

For example


$rss = new RSS();

$siteName = $rss->siteName('StackCoder');
$siteUrl = $rss->siteUrl('https://stackcoder.in');


Which may not be very wise. But there are also downsides of using Method Chaining stay tuned till last.


Lets Build It Then (return $this)


Hope your now super excited to learn it. Lets start then with an example


class RSS{

    public function siteName($siteName)
    {
        $this->siteName = $siteName;
        /** Return the current context with $this */
        return $this;
    }

    public function siteUrl($siteUrl)
    {
        $this->siteUrl = $siteUrl;
        /** Return the current context with $this */
        return $this;
    }
    
}


In my RSS class I have siteName & siteUrl which I want to chain as follows


$rss = new RSS();

$rss->siteName('SiteName')
    ->siteUrl('https://siteurl.com');


This can be achieved by simply returning $this in RSS class methods siteName() & siteUrl() as shown in the above example.


Advantages & DisAdvantages


Advantages


  1. Very simple & easy to understand
  2. Overcome unnecessary intermediate variables
  3. Type less do more kind of thing (DRY approach)



DisAdvantages


  1. Debugging can be harder
  2. If written in a single line then can be harder to read
  3. User will be confused to know what does the chained method may return

Conclusion


Use method when you want simpler code. Never use between different classes, as it may increase the complexity for debugging.


WHATS NEXT?


You might be interest to learn more on composer please find my whole article on it


Send Email In PHP With PHPMailer

How To Upload Image In PHP?

How To Uploads Files In PHP?

How To Install Packages Parallel For Faster Development In Composer

What Is Composer? How Does It Work? Useful Composer Commands And Usage

composer.json v/s composer.lock

Composer Install v/s Composer Update

Route Model Binding In Laravel & Change Default Column id To Another Column

How To Run Raw Queries Securely In Laravel

Laravel 7.x Multiple Database Connections, Migrations, Relationships & Querying

How To Install Apache Web Server On Ubuntu 20.04 / Linux & Manage It

How To Create / Save / Download PDF From Blade Template In PHP Laravel

How To Add Free SSL Certificate In cPanel With ZeroSSL & Certbot

How To Securely SSH Your Server & Push Files With FileZilla

How To Push Files To CPanel / Remote Server using FTP Software FileZilla

How To Install Linux, Apache, MYSQL, PHP (LAMP Stack) on Ubuntu

How To Cache Static Files With NGINX Server

Redirect www to a non-www website or vice versa

How To Create Free SSL Certificate With Lets Encrypt/Certbot In Linux (Single / Multiple Domains)

How To Install Linux, NGINX, MYSQL, PHP (LEMP Stack) on Ubuntu

PHP Built-In Web Server & Testing Your Development Project In Mobile Without Any Software

How To Do Google reCAPTCHA Integration In PHP Laravel Forms


Happy Coding :)








Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing