Help:Hooks

From binaryoption
Jump to navigation Jump to search
Баннер1
  1. Help:Hooks

Hooks are a powerful, yet often misunderstood, feature of MediaWiki. They allow you to extend and customize the wiki’s functionality by executing custom code in response to specific events. This article provides a comprehensive introduction to hooks for beginners, covering their purpose, types, how to create them, and best practices. It assumes a basic understanding of PHP, as that is the language used for writing hooks. Understanding Manual:Configuration settings is also helpful.

== What are Hooks?

At its core, a MediaWiki hook is a defined point in the wiki’s execution flow where developers can "hook" into and add their own code. Think of it like a notification system. When a specific event happens (like a page being saved, a user logging in, or an article being viewed), the hook is triggered, and any code associated with that hook is executed. This is far more flexible than directly modifying the core MediaWiki code, which is discouraged as it makes upgrades difficult.

Hooks enable you to:

  • **Modify existing behavior:** Change how existing wiki features work.
  • **Add new functionality:** Integrate entirely new features into the wiki.
  • **Integrate with external systems:** Connect your wiki to external databases, APIs, or services.
  • **Automate tasks:** Perform actions automatically based on specific events.

== Types of Hooks

MediaWiki provides a wide variety of hooks, categorized by the event they respond to. Here’s a breakdown of some common hook categories:

  • **Maintenance Hooks:** Run during wiki maintenance tasks, like database updates or index rebuilding. These are less commonly used by everyday extension developers.
  • **Configuration Hooks:** Allow modifications to the wiki’s configuration settings during startup. Useful for dynamic configuration.
  • **Parser Hooks:** Modify the way wiki text is parsed and rendered. These are used to create custom Help:Magic words and extensions for special formatting.
  • **Action Hooks:** Triggered by user actions, such as saving a page, editing a page, or viewing a page. These are very common for extensions.
  • **API Hooks:** Allow modifications to the MediaWiki API, adding new API functions or modifying existing ones. Crucial for integrations with external applications.
  • **Security Hooks:** Used to enhance or modify security features, such as authentication and authorization.
  • **Output Hooks:** Modify the final HTML output of the wiki before it’s sent to the user’s browser.

A full list of available hooks can be found at Manual:Hooks. This page is *essential* for understanding what hooks are available and their parameters.

== Creating a Hook

To create a hook, you need to write a PHP function and register it with MediaWiki. The general process is as follows:

1. **Choose a Hook:** Identify the hook that best suits your needs. Consult Manual:Hooks for a comprehensive list. 2. **Write a PHP Function:** Create a PHP function that will be executed when the hook is triggered. This function will accept parameters specific to the hook. 3. **Register the Hook:** Use the `$wgHooks` global variable to register your function with the hook.

Here's a simple example:

```php <?php

/**

* A simple hook that logs a message when a page is saved.
*
* @param Title $title The title of the saved page.
* @param User $user The user who saved the page.
* @param Content $content The content of the saved page.
* @param Revision $rev The revision that was saved.
*/

function myHookSavePage( $title, $user, $content, $rev ) {

   wfDebug( "Page '" . $title->getText() . "' saved by user '" . $user->getName() . "'\n" );
   // You could add more complex logic here, like sending an email
   // or updating a database.
   return true; // Return true to indicate success.

}

$wgHooks['SavePage'][] = 'myHookSavePage'; ```

    • Explanation:**
  • `function myHookSavePage(...)`: This defines the PHP function that will be executed when the `SavePage` hook is triggered.
  • `$title, $user, $content, $rev`: These are the parameters passed to the function by MediaWiki. The specific parameters depend on the hook you're using. Refer to Manual:Hooks for details.
  • `wfDebug(...)`: This function logs a message to the MediaWiki debug log. It’s useful for testing and troubleshooting.
  • `return true;`: This indicates that the hook function executed successfully. Some hooks require a return value; others ignore it.
  • `$wgHooks['SavePage'][] = 'myHookSavePage';`: This line registers the `myHookSavePage` function with the `SavePage` hook. The `[]` appends the function to the array of functions associated with the hook. Multiple functions can be registered for the same hook.
    • Important Notes:**
  • **File Location:** Your hook code should be placed in an extension file (usually a `.php` file) within the `extensions/` directory of your MediaWiki installation. You'll need to enable the extension in `LocalSettings.php`.
  • **Extension Registration:** You need to create a valid extension info file (typically `extension.json`) to properly register your extension and its hooks with MediaWiki.
  • **Error Handling:** Always include error handling in your hook functions to prevent them from crashing the wiki. Use `wfDebug()` or the MediaWiki logging system to record errors.
  • **Performance:** Be mindful of performance. Hooks are executed on every relevant event, so avoid computationally expensive operations. Caching strategies can be helpful. Consider using tools like Xdebug for profiling.
  • **Global Variables:** MediaWiki provides many global variables that you can use within your hook functions. Refer to the Manual:Global variables for a complete list.

== Hook Parameters

Understanding the parameters passed to your hook function is crucial. Each hook provides different parameters, which contain information about the event that triggered the hook. The Manual:Hooks page provides detailed documentation for each hook, including a list of its parameters.

For example, the `SavePage` hook passes the following parameters:

  • `$title`: A Title object representing the title of the saved page. You can use `$title->getText()` to get the page name.
  • `$user`: A User object representing the user who saved the page. You can use `$user->getName()` to get the username.
  • `$content`: A Content object representing the content of the saved page.
  • `$rev`: A Revision object representing the revision that was saved.

Accessing these parameters allows you to perform actions based on the specific details of the event.

== Best Practices

  • **Keep it Simple:** Hooks should be focused and perform a specific task. Avoid creating overly complex hooks that try to do too much.
  • **Document Your Code:** Clearly document your hook functions, including their purpose, parameters, and return values. This makes it easier for others (and your future self) to understand and maintain your code.
  • **Use Namespaces:** Organize your hook code within namespaces to avoid naming conflicts with other extensions.
  • **Test Thoroughly:** Test your hooks thoroughly to ensure they function as expected and don't introduce any regressions. Use a development environment before deploying to a production wiki.
  • **Consider Performance:** Minimize the performance impact of your hooks. Avoid expensive operations and use caching where appropriate.
  • **Follow Coding Standards:** Adhere to the MediaWiki coding standards to ensure your code is consistent and maintainable. See Manual:Coding conventions.
  • **Check Return Values:** When a hook requires a return value, always return the appropriate value to indicate success or failure.
  • **Use `wfDebug()` for Troubleshooting:** Use `wfDebug()` to log messages and help you debug your hook code. Remember to disable debugging in production.
  • **Consider using Extension:Scribunto**: For more complex logic, consider using Scribunto to write your hooks in Lua, which can offer better performance and maintainability.

== Common Use Cases

  • **Adding Custom Buttons to the Editor:** Use the `EditPage::showEditForm` hook to add custom buttons to the wiki editor.
  • **Modifying Page Content:** Use parser hooks to modify the content of pages as they are displayed.
  • **Sending Notifications:** Use action hooks to send notifications (e.g., email, Slack messages) when specific events occur.
  • **Integrating with External APIs:** Use API hooks to integrate with external APIs and services.
  • **Implementing Custom Security Checks:** Use security hooks to implement custom security checks and authorization rules.
  • **Tracking User Activity:** Use action hooks to track user activity and generate reports.

== Resources

== Advanced Concepts

  • **Hook Priorities:** You can specify a priority for your hooks. Hooks with higher priorities are executed before hooks with lower priorities. This allows you to control the order in which hooks are executed.
  • **Hook Conditions:** You can specify conditions that must be met for your hook to be executed. This allows you to execute hooks only in specific situations.
  • **Dependency Injection:** Consider using dependency injection to make your hook code more testable and maintainable.
  • **Asynchronous Hooks:** For long-running tasks, consider using asynchronous hooks to avoid blocking the wiki’s main thread.

== Technical Analysis & Trading Strategies Related Links (for context – hooks could be used to integrate these!)

  • **Moving Averages:** [3]
  • **MACD (Moving Average Convergence Divergence):** [4]
  • **RSI (Relative Strength Index):** [5]
  • **Bollinger Bands:** [6]
  • **Fibonacci Retracements:** [7]
  • **Candlestick Patterns:** [8]
  • **Trend Lines:** [9]
  • **Support and Resistance Levels:** [10]
  • **Day Trading:** [11]
  • **Swing Trading:** [12]
  • **Scalping:** [13]
  • **Position Trading:** [14]
  • **Elliott Wave Theory:** [15]
  • **Ichimoku Cloud:** [16]
  • **Volume Analysis:** [17]
  • **Chart Patterns:** [18]
  • **Head and Shoulders Pattern:** [19]
  • **Double Top/Bottom:** [20]
  • **Triangles:** [21]
  • **Flag and Pennant:** [22]
  • **Gap Analysis:** [23]
  • **Average True Range (ATR):** [24]
  • **Parabolic SAR:** [25]
  • **Stochastic Oscillator:** [26]
  • **Heikin Ashi:** [27]
  • **Donchian Channels:** [28]

Help:Extension development Help:PHP Help:Manual:Configuration settings Help:Magic words Help:Templates Help:Categories Help:Linking Help:Editing Help:Formatting Manual:Hooks

Start Trading Now

Sign up at IQ Option (Minimum deposit $10) Open an account at Pocket Option (Minimum deposit $5)

Join Our Community

Subscribe to our Telegram channel @strategybin to receive: ✓ Daily trading signals ✓ Exclusive strategy analysis ✓ Market trend alerts ✓ Educational materials for beginners

Баннер