PHPackages                             magdicom/hooks - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. magdicom/hooks

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

magdicom/hooks
==============

A lightweight PHP action hooks package.

v1.1.0(4y ago)0185[2 PRs](https://github.com/magdicom/hooks/pulls)1MITPHPPHP ^8.0

Since Dec 31Pushed 2y ago1 watchersCompare

[ Source](https://github.com/magdicom/hooks)[ Packagist](https://packagist.org/packages/magdicom/hooks)[ Docs](https://github.com/magdicom/hooks)[ GitHub Sponsors](https://github.com/magdicom)[ RSS](/packages/magdicom-hooks/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (3)Versions (10)Used By (1)

PHP Action Hooks
================

[](#php-action-hooks)

[![Latest Version on Packagist](https://camo.githubusercontent.com/3d1074c5217026d8411c053aa06adb3ef7463e65efc152c77891203233096200/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d61676469636f6d2f686f6f6b732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/magdicom/hooks)[![Tests](https://github.com/magdicom/hooks/actions/workflows/run-tests.yml/badge.svg?branch=main)](https://github.com/magdicom/hooks/actions/workflows/run-tests.yml)[![Total Downloads](https://camo.githubusercontent.com/a4b89e3b28423d3fe47c0f11cc5d12837e9de86c33501c6cced56774d8c2be96/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d61676469636f6d2f686f6f6b732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/magdicom/hooks)

Inspired by WordPress, action hooks are functions that you define to be triggered in specific places of your code, it helps you maintain an organized code by slicing giant code blocks into separated files and/or classes.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require magdicom/hooks
```

Usage
-----

[](#usage)

### Quick Start

[](#quick-start)

```
use Magdicom\Hooks;

$hooks = new Hooks();

# Register our functions
$hooks->register("Greetings", function($vars){
    return "Hi There,";
}, 1);

$hooks->register("Greetings", function($vars){
    return "This is the second line of greetings!";
}, 2);

# Later we run it
echo $hooks->all("Greetings")->toString("");
```

The above example will output

```
Hi There,
This is the second line of greetings!

```

### Output

[](#output)

When you call any of [`all`](#all), [`first`](#first) or [`last`](#last) methods, the corresponding hook functions will be executed and their output will be saved in a special property to be exported later using [`toString`](#tostring) or [`toArray`](#toarray) methods.

### Callbacks

[](#callbacks)

#### Closure

[](#closure)

```
$hooks->register("Callback", function($vars) {
    return "Closure";
});
```

#### Function Name

[](#function-name)

```
function simple_function_name($vars){
    //
}

$hooks->register("Callback", "simple_function_name");
```

#### Object Method

[](#object-method)

```
class FooBar {
    public function methodName($vars){
        //
    }
}

$object = new FooBar;

$hooks->register("Callback", [$object, 'methodName']);
```

or

```
$hooks->register("Callback", [(new FooBar), 'methodName']);
```

#### Static Method

[](#static-method)

```
class FooBar {
    public static function staticMethodName($vars){
        //
    }
}

$hooks->register("Callback", ['FooBar', 'staticMethodName']);
```

in case this is not a static method, an object will be created and the provided method will be called.

### Parameters

[](#parameters)

With each of hook callback functions execution an array of parameters could be passed to it to help it perform the required action.

#### Global Parameters

[](#global-parameters)

Global parameters could be defined using [`setParameter`](#setparameter) and [`setParameters`](#setparameters) methods and these parameters will be available across all hook points and callbacks.

#### Scoped parameters

[](#scoped-parameters)

The opposite of global parameters, the scoped parameters only available for the specified action hook point, and could be provided as the second argument of [`all`](#all), [`first`](#first) and [`last`](#last) methods.

When you provide it as an array, the values of scoped parameters will temporarily replace (similar key entries) global parameters and passed to the [`register`](#register) methods' callback as a merged array.

When the parameter provided as a class object it will be accessible from the [`register`](#register) method as the first argument, and the global parameters will be accessible via the second argument.

```
class FooBarBaz {
    public $id;

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

$hooks = new Hooks();

$hooks->setParameters([
    "name" => "Bar",
]);

$hooks->register("ParameterAsObject", function ($fooBarBaz, $params) {
    return [$fooBarBaz->id, $params['name']];
});

echo $hooks->all("ParameterAsObject", (new FooBarBaz(100))->toString("\n");

// Output will be
100
Bar
```

### Priority

[](#priority)

When you need to ensure that certain hook functions should be executed in sequence order, here it comes `$priority` which is the 3rd and last argument of [`register`](#register) method.

### Methods

[](#methods)

#### \_\_construct

[](#__construct)

```
$hooks = new Hooks(?array $parameters);
```

The class constructor method will optionally accept a name, value pair array.

#### register

[](#register)

```
$hooks->register(string $hookName, array|callable $callback, ?int $priority): self
```

Register all your hook functions via this method:

- `$hookName` this can be anything you want, its like a group name where all other related action hook functions will be attached to.
- `$callback` only accepts [callable](https://www.php.net/manual/en/language.types.callable.php) functions.
- `$priority` (optional) used to sort callbacks before being executed.

#### all

[](#all)

```
$hooks->all(string $hookName, array|object|null $parameters): self
```

Will execute all callback functions of the specified hook name, by default it will return the output as string, check [output](#output) section for more options.

- `$hookName` the hook name you want to execute its callback functions.
- `$parameters` optional key, value pair array (or object) that you want to provide for all callback functions related to the same hook point.

Please Note: parameters provided via this method will be available only in the scope of the specified hook point, to specify global parameters use [`setParameter`](#setparameter), [`setParameters`](#setparameters) methods instead.

#### first

[](#first)

```
$hooks->first(string $hookName, array|object|null $parameters): self
```

Similar to [`all`](#all) method in every aspect with the exception that only the first callback (after sorting) will be executed.

#### last

[](#last)

```
$hooks->last(string $hookName, array|object|null $parameters): self
```

Similar to [`all`](#all) method in every aspect with the exception that only the last callback (after sorting) will be executed.

#### toArray

[](#toarray)

```
$hooks->toArray(): array
```

Will return output of the last executed hook name functions as an array.

#### toString

[](#tostring)

```
$hooks->toString(?string $separator): string
```

Will return output of the last executed hook name functions as one string.

- `$separator` could be used to separate the output as you need (e.g: "\\n", "&lt;br&gt;").

#### setParameter

[](#setparameter)

```
$hooks->setParameter(string $name, mixed $value): self
```

Use this method to define a parameter that will be accessible from any hook function.

- `$name` name of the parameter.
- `$value` value of the parameter could be string, array or even an object.

P.S: if the parameter already defined then its old value will be replaced by the value provided here.

#### setParameters

[](#setparameters)

```
$hooks->setParameters(array $parameters): self
```

Same as [`setParameter`](#setparameter) but here it accepts a name, value pair array as its only argument.

#### setSourceFile

[](#setsourcefile)

```
$hooks->setSourceFile(?string $path): self
```

Used in conjunction with the [`debug`](#debug) method.

#### debug

[](#debug)

```
$hooks->debug(callable|null $callback): self
```

To enable the debug feature you need to call this method by providing a callback function, this function should accept a single argument that will be the debug info/message.

```
$hooks->debug(function($message){
    // Will print debug message(s)
    echo $message . PHP_EOL;
});

$hooks->setSourceFile("/path/to/file/filename.php");

$hooks->register("Greetings", "FooBar::log");

$hooks->all("Greetings");
```

will output

```
+ Added Source File: /path/to/file/filename.php
+ Hook Point: Greetings, New Callback Defined:
        -- Source: /path/to/file/filename.php
        -- Callback: FooBar::log
        -- Priority: 1
+ Hook Point: Greetings, Callback Functions Sorted!
+ Hook Point: Greetings, Output Generated For All Callback Functions!

```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Mohamed Magdi](https://github.com/magdicom)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 60.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

7

Last Release

1579d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/40920709?v=4)[momagdi](/maintainers/momagdi)[@momagdi](https://github.com/momagdi)

---

Top Contributors

[![magdicom](https://avatars.githubusercontent.com/u/91500450?v=4)](https://github.com/magdicom "magdicom (34 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (11 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (11 commits)")

---

Tags

hooksmagdicom

###  Code Quality

TestsPest

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/magdicom-hooks/health.svg)

```
[![Health](https://phpackages.com/badges/magdicom-hooks/health.svg)](https://phpackages.com/packages/magdicom-hooks)
```

###  Alternatives

[tormjens/eventy

The WordPress filter/action system in Laravel

438912.9k16](/packages/tormjens-eventy)[larapack/hooks

A Laravel Hook system

2171.5M21](/packages/larapack-hooks)[larapack/voyager-hooks

Hooks integrated in Voyager

2031.5M27](/packages/larapack-voyager-hooks)[bainternet/php-hooks

A fork of the WordPress filters hook system rolled in to a class to be ported into any PHP-based system

27621.3k2](/packages/bainternet-php-hooks)[voku/php-hooks

A fork of the WordPress filters hook system rolled in to a class to be ported into any PHP-based system

7637.3k3](/packages/voku-php-hooks)[wcm/git-php-hooks

Write git hooks with PHP, organize them on a per-project base and automatically add them

6441.1k3](/packages/wcm-git-php-hooks)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
