Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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?

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

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.

Comments?