Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Refactoring conditionals to callables in PHP

March 16, 2022 ·

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 (includes 8.1 and 8.2), 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-read 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.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?