Understanding PHP Invokable Classes: Examples, Use Cases, and Real-World Applications

Harish Kumar · · 515 Views
Understanding PHP Invokable Classes: Examples, Use Cases, and Real-World Applications

In PHP, an invokable class is a class you can call like a function. To make a class invokable, PHP provides a special magic method called __invoke(). Once implemented, this allows objects of the class to behave like callable functions.

Let’s explore why invokable classes exist, how to create them, and some of their practical use cases.

Why Do Invokable Classes Exist?

PHP does not treat functions as "first-class citizens" like some other programming languages. This means you can't directly pass functions around as arguments, return them from other functions, or store them in variables.

However, invokable classes bridge this gap by letting you define objects that act like functions. This allows more flexibility and makes PHP code cleaner in many situations, such as callbacks or closures.

How to Create an Invokable Class?

To create an invokable class, you need to define the __invoke() method inside the class. Here’s an example:

class GreetUser {
    public function __invoke($name) {
        return "Hello, $name!";
    }
}

// Creating an instance of the class
$greet = new GreetUser();

// Calling the object like a function
echo $greet("John"); // Output: Hello, John!

Here, the GreetUser class is invokable because it implements the __invoke() method. When you call the $greet object as if it’s a function, the __invoke() method is executed.

Practical Use Cases for Invokable Classes

Invokable classes are useful when:

  1. You want reusable callable logic.

  2. You want objects to act as a callback without needing separate functions.

  3. You need to encapsulate additional state or configuration.

Let’s look at some real-world examples.

Example 1: A Callback for Sorting Arrays

Imagine you have an array of products, and you need to sort it based on different keys, such as price or name. Using invokable classes, you can simplify this process.

class SortByKey {
    private $key;

    public function __construct($key) {
        $this->key = $key;
    }

    public function __invoke($a, $b) {
        return $a[$this->key] <=> $b[$this->key];
    }
}

$products = [
    ['name' => 'Laptop', 'price' => 1000],
    ['name' => 'Phone', 'price' => 500],
    ['name' => 'Tablet', 'price' => 700],
];

// Sort by price
usort($products, new SortByKey('price'));
print_r($products);

// Sort by name
usort($products, new SortByKey('name'));
print_r($products);

This approach is cleaner and avoids rewriting the sorting logic for each key.

Example 2: Middleware in a Web Application

In frameworks like Laravel, invokable classes are often used for middleware or tasks. Let’s implement a simple middleware:

class CheckAdmin {
    public function __invoke($request, $next) {
        if ($request->user()->role !== 'admin') {
            return "Access Denied!";
        }
        return $next($request);
    }
}

// Usage in a simple router
$request = (object)['user' => (object)['role' => 'user']];
$middleware = new CheckAdmin();
$response = $middleware($request, fn($req) => "Welcome, Admin!");
echo $response; // Output: Access Denied!

Real-World Example in Laravel

Laravel uses invokable classes extensively. For example, in the task scheduler, you can pass an invokable class to define a scheduled task:

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(new DeleteOldFiles)->daily();
    }
}

// Define the invokable class
class DeleteOldFiles {
    public function __invoke() {
        // Logic to delete old files
        echo "Old files deleted!";
    }
}

Here, DeleteOldFiles is an invokable class that is executed daily by the scheduler.

Wrapping Up

Invokable classes in PHP provide a simple way to mimic first-class functions. They are especially useful in scenarios like sorting, middleware, or scheduling tasks. By implementing the __invoke() method, you can make your classes callable and use them in creative and flexible ways.

Now it’s your turn to use invokable classes in your PHP projects and unlock their potential!

0

Please login or create new account to add your comment.

0 comments
You may also like:

What is PSR-6? A Beginner’s Guide to PHP Caching Standards

Is your PHP application slowing down because of repeated database queries or inefficient caching? Do you wish switching between caching libraries was simpler? That’s where PSR-6 (...)
Harish Kumar

Exploring Asymmetric Property Visibility in PHP 8.4

The release of PHP 8.4 introduces a powerful new feature: Asymmetric Property Visibility, enabling developers to define separate visibility rules for reading and writing properties. (...)
Harish Kumar

What's New in PHP 8.4: Key Enhancements and Updates

As PHP 8.4's release on November 21, 2024, approaches, it's clear that PHP continues to evolve and delight its developer community. For those who have been coding with PHP since (...)
Harish Kumar

Introducing Tools to Supercharge PHP-FPM Efficiency and Monitoring

PHP-FPM stands for PHP FastCGI Process Manager. It’s an improved way to manage PHP processes that makes web applications faster and more efficient. Instead of running each PHP (...)
Harish Kumar

PHP 8.4 Property Hooks: The Ultimate Guide for Developers

PHP 8.4, coming in November 2024, introduces a new feature called property hooks. This feature makes it easier to work with class properties by allowing you to define custom behavior (...)
Harish Kumar

PHP OPCache: The Secret Weapon for Laravel Performance Boost

OPCache, a built-in PHP opcode cache, is a powerful tool for significantly improving Laravel application speed. This guide will demonstrate how to effectively utilize OPCache to (...)
Harish Kumar