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.

Native hooks

MageWork triggers the following hooks during a request. The $data array passed to process() contains the keys listed below; modifying them changes what the framework does next.

HookPassed dataPurpose
app.page.initidentifierChange the resolved page identifier (route) before it is loaded
app.asset.readfileChange the static asset file about to be sent
app.page.renderpage (object)Replace or tweak the page object before rendering
app.page.completepage (rendered HTML)Alter the final HTML output
app.page.errorexceptionReact to an uncaught exception
template.includetemplate, path, type, identifierSwap the template file being included
app.cli.initidentifierChange the console command identifier
app.cli.completeidentifier, exitChange the console exit code

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}',
        ],
    ],
];
ElementDescription
{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);