
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.
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
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.
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.
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.
Use method when you want simpler code. Never use between different classes, as it may increase the complexity for debugging.
Send SMS With Amazon SNS (Simple Notification Service) Using PHP
Firebase Cloud Messaging (FCM) Browser Web Push Notifications Using Javascript And PHP
Add Google ADS In AMP (Accelerated Mobile Pages) Website
What Is Composer? How Does It Work? Useful Composer Commands And Usage
Cache Static Files With NGINX Server
Create A Composer Package? Test It Locally And Add To Packagist Repository
Add Analytics To AMP (Accelerated Mobile Pages) HTML Pages
composer.json v/s composer.lock
Detect AdBlocker With Javascript And Increase Website Ads Revenue
Setup AMP (Accelerated Mobile Pages) In PHP Laravel
Increase Session Timeout In Laravel
Generate Sitemap in PHP Laravel
Resolve 404 Not Found In NGINX