Method Chaining vs. Direct Method Calls in WordPress Plugins
When making a WordPress plugin, you can write your code in different ways. Two common ways are:
We will explain both methods with examples, talk about the good and bad things about each, and see if one is faster than the other.
Method Chaining (Object Chain)
What Is It?
Method chaining is when you call several functions (methods) on an object in one line. Each method returns $this, which is the object itself, so you can keep adding more method calls.
Example Code:
class MyPlugin {
public function __construct() {
// Setup code here
}
public function register_post_types() {
// Code to add custom post types
return $this;
}
public function register_taxonomies() {
// Code to add custom taxonomies
return $this;
}
public function add_shortcodes() {
// Code to add shortcodes
return $this;
}
public function add_hooks() {
// Code to add hooks
return $this;
}
}
// Using the class
$plugin = new MyPlugin();
$plugin->register_post_types()
->register_taxonomies()
->add_shortcodes()
->add_hooks();
Good Things (Pros):
Bad Things (Cons):
Direct Method Calls
What Is It?
This means calling each method one by one, without chaining them together. Each method does its job and doesn't need to return $this.
Example Code:
class MyPlugin {
public function __construct() {
// Setup code here
}
public function register_post_types() {
// Code to add custom post types
}
public function register_taxonomies() {
// Code to add custom taxonomies
}
public function add_shortcodes() {
// Code to add shortcodes
}
public function add_hooks() {
// Code to add hooks
}
}
// Using the class
$plugin = new MyPlugin();
$plugin->register_post_types();
$plugin->register_taxonomies();
$plugin->add_shortcodes();
$plugin->add_hooks();
Good Things (Pros):
Bad Things (Cons):
Speed Test (Benchmark)
Let's see if one method is faster than the other.
Test Code:
$iterations = 100000;
// Method Chaining Test
$startTime = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$plugin = new MyPlugin();
$plugin->register_post_types()
->register_taxonomies()
->add_shortcodes()
->add_hooks();
}
$chainTime = microtime(true) - $startTime;
// Direct Method Calls Test
$startTime = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$plugin = new MyPlugin();
$plugin->register_post_types();
$plugin->register_taxonomies();
$plugin->add_shortcodes();
$plugin->add_hooks();
}
$directTime = microtime(true) - $startTime;
echo "Method Chaining Time: $chainTime seconds\n";
echo "Direct Method Calls Time: $directTime seconds\n";
What We Found: