1. Go to this page and download the library: Download kristos80/hook library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kristos80 / hook example snippets
use Kristos80\Hook\Hook;
$hook = new Hook();
// Add a filter
$hook->addFilter('format_title', function(string $title) {
return strtoupper($title);
});
// Apply the filter
$result = $hook->applyFilter('format_title', 'hello world');
echo $result; // HELLO WORLD
// Different priority per hook: 'init' gets priority 1, 'save' gets priority 20
$hook->addFilter(['init', 'save'], function(string $data) {
return $data;
}, [1, 20]);
// Partial array: 'init' gets priority 5, 'save' and 'cleanup' fall back to index 0 (priority 5)
$hook->addAction(['init', 'save', 'cleanup'], function() {
// ...
}, [5]);
// Single int still works as before — all hooks get the same priority
$hook->addFilter(['init', 'save'], $callback, 10);
// Closure
$hook->addFilter('my_filter', function(string $value) {
return strtoupper($value);
});
// Function name (string)
$hook->addFilter('my_filter', 'strtoupper');
// Static method (string)
$hook->addFilter('my_filter', 'MyClass::transform');
// Static method (array)
$hook->addFilter('my_filter', [MyClass::class, 'transform']);
// Instance method (array)
$formatter = new TextFormatter();
$hook->addFilter('my_filter', [$formatter, 'format']);
// Invokable object
class MyTransformer {
public function __invoke(string $value): string {
return strtoupper($value);
}
}
$hook->addFilter('my_filter', new MyTransformer());
$hook->addFilter('process_data', function(array $data): array {
return array_map('strtoupper', $data);
});
// This will work - callback has typed parameters
$result = $hook->applyFilter('process_data', ['hello'], s: true);
use Kristos80\Hook\HookInterface;
// Guaranteed to run before any other callback
$hook->addFilter('process', function(string $data) {
return trim($data);
}, HookInterface::FIRST);
// Guaranteed to run after any other callback
$hook->addFilter('process', function(string $data) {
return htmlspecialchars($data);
}, HookInterface::LAST);
use Kristos80\Hook\HookException;
use Kristos80\Hook\CircularDependencyException;
use Kristos80\Hook\InvalidPriorityException;
use Kristos80\Hook\MissingTypeHintException;
// Type-hint against the interface for better architecture
class UserService {
public function __construct(
private HookInterface $hooks
) {}
public function createUser(array $data): User {
$data = $this->hooks->applyFilter('user_data', $data);
// ...
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.