Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 18 additions & 18 deletions Hooker.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,24 +35,24 @@ class Hooker {
* );
* @var array
*/
public static $events = array();
public static $events = [];

/**
* Contains all logged messages throughout Hooker execution.
* @var array
*/
public static $console = array();
public static $console = [];

/**
* Hooker settings and configuration.
* @var array
*/
public static $config = array(
public static $config = [
'hookerEnabled' => true, // Set to false to disable Hooker/to not execute any hooks
'hookFolderPath' => '', // Path to hooks folder
'cacheHooks' => true, // If Hook->enableCache is true, Hooker will cache the results and display
// the cache rather than executing the hook again.
);
];

/**
* @param $path
Expand All @@ -67,30 +67,30 @@ public static function setHookFolderPath($path) {
}

private function getConfigKey($configKey) {
if (isSet($this->config[$configKey])) {
$this->config[$configKey];
} else {
throw new HookerException('[Hooker::getConfigKey] Config key '. $configKey .' does not exist.');
if (isset($this->config[$configKey])) {
return $this->config[$configKey];
}

throw new HookerException('[Hooker::getConfigKey] Config key '. $configKey .' does not exist.');
}

public static function init() {
// Loop through hooks folder
foreach (new DirectoryIterator(self::$config['hookFolderPath']) as $item) {
if ($item->isDot() == false) {
if (!$item->isDot()) {
// Folders within the hooks folder are Event Folders
if ($item->isDir() == true) {
if ($item->isDir()) {
$eventName = $item->getFileName();
$eventHooksPath = $item->getPathName();

// Files within the Event Folders are Hooks
foreach (new DirectoryIterator($eventHooksPath) as $hookFile) {
if ($hookFile->isDot() == false) {
if (!$hookFile->isDot()) {
$hookFilePath = $hookFile->getPathName();
$hookObjectName = $hookFile->getBaseName('.php');

// Bind current hook to designated event
self::bind($eventName, array($hookFilePath, $hookObjectName));
self::bind($eventName, [$hookFilePath, $hookObjectName]);
}
}
}
Expand Down Expand Up @@ -123,10 +123,10 @@ public static function event($eventName, $use = null) {
self::consoleLog('[Hooker::event] [Event '. $eventName .'] encountered.');

// Fetch event hooks array
$eventHooksArray = (isSet(self::$events[$eventName]) ? self::$events[$eventName] : array());
$eventHooksArray = isset(self::$events[$eventName]) ? self::$events[$eventName] : [];

if (sizeOf($eventHooksArray) > 0) {
$hooksToExecute = array();
if (count($eventHooksArray) > 0) {
$hooksToExecute = [];

// Prepare and sort hooks
foreach ($eventHooksArray as $hookArray) {
Expand All @@ -144,10 +144,10 @@ public static function event($eventName, $use = null) {
}
}

$hooksToExecute[] = array(
$hooksToExecute[] = [
'hookArray' => $hookArray,
'priority' => $priority
);
];
}

// Sort by priority (ascending)
Expand All @@ -165,7 +165,7 @@ public static function event($eventName, $use = null) {

if (class_exists($className)) {
$hook = new $className;
call_user_func(array($hook, 'execute'), $use);
call_user_func([$hook, 'execute'], $use);
//$hook->execute($use);

self::consoleLog('[Hooker::event] [Event '. $eventName .'] Hook '. $className .' executed.');
Expand Down
103 changes: 100 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,101 @@
PHP Hooks
======
# php-hooks

Extends an application with hooks, triggered at user-defined events.
A small PHP hook system for extending an application at user-defined events.

The core idea is simple:
- your application declares events
- hook classes are organized into folders by event name
- `Hooker` scans the hook folder, binds matching hook classes, and executes them when an event is triggered

## What this project does
`php-hooks` lets you add plug-in style behavior to an existing PHP application without hard-coding every action directly into the main script.

This is useful when you want to:
- keep your main application logic simpler
- attach custom behavior to specific events
- extend a system without editing the same core file over and over

## How it works
The library uses a folder structure where each event has its own directory.

Example:

```text
hooks/
userLogInAttempt/
SendSalesEmail.php
LogAttempt.php
```

When `Hooker::init()` runs, it scans the hooks folder and binds each hook file to the event folder it lives under.

So in the example above:
- files inside `hooks/userLogInAttempt/` are attached to the `userLogInAttempt` event

Later, when this runs:

```php
Hooker::event('userLogInAttempt', $data);
```

all hooks bound to that event are executed.

## Basic usage
### 1. Include the core file

```php
require 'Hooker.php';
```

### 2. Point Hooker at your hooks directory

```php
Hooker::setHookFolderPath(__DIR__ . '/hooks');
```

### 3. Initialize hooks

```php
Hooker::init();
```

### 4. Trigger an event

```php
Hooker::event('userLogInAttempt', array('username' => 'ray'));
```

## Example hook class
A hook class must implement the `Hook` interface and define an `execute()` method.

```php
<?php

class LogAttempt implements Hook {
public static $priority = 10;

public function execute($use) {
echo 'User login attempt detected';
}
}
```

## Priorities
If a hook class defines a static `$priority` property, hooks are executed in ascending priority order.

Example:
- priority `10` runs before priority `50`
- if no priority is defined, the default is `50`

## Included files
- `Hooker.php` — core hook system
- `masterApp.php` — small example/demo entry point

## Notes
This project has the feel of an older lightweight PHP utility library.
A good next modernization pass could include:
- examples folder structure in the repo
- tests
- composer support
- a license
- clearer naming around hook discovery and configuration
22 changes: 0 additions & 22 deletions masterApp.php~

This file was deleted.