Refactoring conditionals to callables in PHP
Recently, I came across a very handy tip by Nuno Maduro where you can refactor some of the conditionals in your code to callables to make your code more elegant and readable.
So, take the following code for example.
$cart = new Cart();
if (
!empty($cart->items)
&& now()->subMinutes(4)->lte($cart->updated_at)
) {
// do something
}
As you can tell, the above code is pretty straightforward. We instantiated an object of the Cart
class. And there’s a conditional based on the properties of this class.
Refactor to a callback method
Now, the idea is to refactor this conditional to a class method that can execute whatever is passed to it as a callable. If we want to do it, we can do something like this.
class Cart
{
// code commented for brevity
public function whenExpired(Closure $callback)
{
if (
!empty($this->items)
&& now()->subMinutes(4)->lte($this->updated_at)
) {
$callback();
}
}
}
As you can tell, we defined a public
method called whenExpired
for the Cart
class that accepts a callback as its only argument. And then inside the method, we can use the same condition of the previous example and execute the callback if the condition is true
. And that’s it!
The usage
So, the previous example can be rewritten using this method like so.
$cart = new Cart();
$cart->whenExpired(function() {
// do something
})
Pretty neat, no?
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.