How do I use hooks in a plugin?
avatar
Señor FAQ

¡Hola, amigos! I’m Señor FAQ, the mustached maestro of questions and answers! With my trusty glasses and a book of endless wisdom, I turn dudas into solutions. Soy el héroe de los curiosos and the champion of clarity.


How to Use Hooks in a JScms Plugin

Hooks are powerful tools in JScms that allow plugins to modify or extend the functionality of the system at specific points. By leveraging hooks, you can seamlessly integrate custom logic into your plugin.

1. What Are Hooks?

Hooks are predefined points in the system where you can attach custom functionality. JScms uses the DynamicHooks class to manage hooks. Refer to the Hook Category FAQ for a list of available hooks.

2. Using DynamicHooks::addHook()

The DynamicHooks::addHook() method registers your custom function to a specific hook. Here's the syntax:

DynamicHooks::addHook($hookName, $callback, $namespace, $priority);

Parameters explained:

  • $hookName: The name of the hook (e.g., before_render).
  • $callback: A callable function or anonymous function to execute.
  • $namespace: A unique identifier for your plugin.
  • $priority: (Optional) Execution order. Lower numbers execute first. Default is 10.

3. Example: Adding a Message to the Footer

Let's create a plugin that adds a custom message to the footer using the after_render hook:

<?php

use JScms\Class\DynamicHooks;

// Ensure the file is only accessed internally
if (!defined('JSCMS_PREVENT_PLUGIN_ACCESS')) {
    die('Direct access not allowed.');
}

// Hook to add a footer message
DynamicHooks::addHook('after_render', function () {
    echo "<p>This message is added by my custom plugin.</p>";
}, 'my_plugin', 10);

?>

In this example:

  • after_render: The hook name where the function is attached.
  • The anonymous function outputs the message to the footer.
  • my_plugin: The namespace ensures no conflicts with other plugins.
  • 10: The priority determines the execution order of hooks at the same point.

4. Accessing Parameters

Some hooks pass parameters to the callback function. Here's an example:

DynamicHooks::addHook('before_render', function ($pageData, $jkv) {
    // Modify the page title
    $pageData['title'] .= " - Powered by My Plugin";
}, 'my_plugin', 5);

This hook modifies the page title before rendering. Refer to the Function Category FAQ for related utility functions.

5. Best Practices

  • Use unique namespaces to avoid conflicts with other plugins.
  • Always test your hooks in a development environment.
  • Refer to the JScms documentation for a complete list of available hooks.
  • Use the JSCMS_PREVENT_PLUGIN_ACCESS constant to prevent direct file access.

6. Debugging Tips

  • Use error_log() or a debugger to trace issues with your hook callbacks.
  • Ensure the priority value does not conflict with other hooks.
  • Verify the hook name matches exactly as defined in the JScms documentation.
Was this article helpful?
0 out of 0 found this helpful