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.
| Hook | Passed data | Purpose |
|---|---|---|
app.page.init | identifier | Change the resolved page identifier (route) before it is loaded |
app.asset.read | file | Change the static asset file about to be sent |
app.page.render | page (object) | Replace or tweak the page object before rendering |
app.page.complete | page (rendered HTML) | Alter the final HTML output |
app.page.error | exception | React to an uncaught exception |
template.include | template, path, type, identifier | Swap the template file being included |
app.cli.init | identifier | Change the console command identifier |
app.cli.complete | identifier, exit | Change 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}',
],
],
];
| 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
$dataparameter 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);
- Installation
- Configuration
- Add a new package
- Add a new HTML page
- Templating best practices
- Add a new block
- Assets
- Serve any type of file
- Rewrite a route
- Data assignment
- Objects and class fallback
- Models
- Database
- Forms
- Session messages
- Send emails
- Captcha
- Framework tools
- Console Commands
- Hooks
- Custom shared libraries
- External libraries with composer
- Write content in Markdown
- Static Site Generator