MageWork

Back to home

Hooks

The hooks system allows you to modify or extend the application behavior without altering existing source code. A hook is an anchor point where custom processing can be inserted.

Creating a hook

1. Register the hook

Declare the hook in packages/{Package}/etc/hooks.php:

<?php

$config = [
    Core_Hook_Interface::TYPE => [
        '{hook.name}' => [
            '{unique_name}' => '{hook_identifier}',
        ],
    ],
];
Element Description
{hook.name} Anchor point name (e.g., custom.hook.demo)
{unique_name} Unique key for this hook
{hook_identifier} The Hook identifier (e.g., demo = {Package}_Hook_Demo)

2. Implement the interface

Create a class in the Hook directory of your package:

<?php

declare(strict_types=1);

class Acme_Hook_Demo implements Core_Hook_Interface
{
    public function process(array &$data): void
    {
        $data['foo'] = 'bar';
    }
}

The $data parameter is passed by reference. Any modification will be reflected in the original data.

Example

<?php

$config = [
    Core_Hook_Interface::TYPE => [
        'checkout.cart.add' => [
            'log_cart_add' => 'cart_logger', // Acme_Hook_Cart_Logger
        ],
    ],
];

Triggering a hook

Use App::hook() where needed:

<?php

$data = [
    'product_id' => 123,
    'quantity' => 2,
];

App::hook('checkout.cart.add', $data);