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:
You want reusable callable logic.
You want objects to act as a callback without needing separate functions.
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!
Please login or create new account to add your comment.