Ajout d'un hook d'événement dans Plugin.php

VérifiéSûr

Ajoute un nouveau point d'ancrage d'événement dans src/Plugin.php, enregistre dans getHooks() et crée le gestionnaire GenericEvent statique.

Spar Skills Guide Bot
DeveloppementIntermédiaire
22/07/2026
Claude CodeCursorWindsurfCopilotCodex
#php#event-hooks#plugin-development#symfony-eventdispatcher#unit-testing

Recommandé pour

Synthèse automatique

Ajoute un nouveau hook d'événement dans src/Plugin.php en l'enregistrant dans getHooks() et en créant le gestionnaire statique GenericEvent correspondant.

Points forts

  • Décrit précisément les contraintes de signature (public static, un seul paramètre GenericEvent) imposées par les tests existants
  • Impose le garde-fou de catégorie et l'appel à stopPropagation comme dernière instruction
  • Couvre la convention de clé self::$module.'.event_name' et l'exception 'function.requirements'
  • Inclut la mise à jour de tests/PluginTest.php (clés attendues et compteur de méthodes) avec vérification via composer test

Limites

  • Très spécifique à un plugin PHP particulier avec GenericEvent, get_service_define et myadmin_log
  • Ne traite pas la modification de gestionnaires existants ni l'ajout de fonctions inc, explicitement hors périmètre
  • Suppose que l'import GenericEvent est déjà présent et ne fournit pas de contexte sur le reste de l'architecture
Quand l'utiliser

Utilisez cette compétence lorsqu'il faut brancher un nouvel événement du cycle de vie (activation, désactivation, changement d'IP, réactivation) sur le plugin.

Quand l'éviter

Ne l'utilisez pas pour modifier un gestionnaire existant ou pour ajouter une fonction dans les fichiers inc.

Analyse de sécurité

Sûr
Score qualité90/100

The skill provides concrete, narrow instructions for editing a PHP plugin file and its tests. It does not instruct destructive commands, network exfiltration, secret handling, obfuscated payloads, or disabling safety mechanisms.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Log IP change
Add a hook for licenses.change_ip that logs the old and new IP address.
Reactivate reuses activate handler
Add a hook for the reactivate lifecycle event and point it at the existing getActivate handler instead of creating a new method.
Hook calling an inc function
Add a new change_ip hook whose handler calls an inc function, register the requirement in getRequirements(), and update the tests.

name: plugin-hook description: Adds a new event hook to src/Plugin.php — registers in getHooks() and creates the static GenericEvent handler. Use when user says 'add hook', 'handle event', 'new plugin event', or adds a lifecycle action (activate/deactivate/change IP/reactivate). Do NOT use for modifying existing handlers or adding inc functions.

plugin-hook

Critical

  • All handler methods MUST be public static and accept exactly one GenericEvent $event parameter — testHookMethodsArePublicAndStatic and testEventHandlerMethodSignatures will fail otherwise.
  • Always guard the handler body with if ($event['category'] == get_service_define('PARALLELS')) before any logic.
  • Always call $event->stopPropagation() as the last statement inside the category guard.
  • Hook keys use self::$module . '.event_name' (e.g. 'licenses.change_ip') — never hardcode the module string.
  • The one exception is 'function.requirements' which uses a literal key, not the module prefix.
  • Run composer test after every change — a missing method or wrong signature will break testAllHookMethodsExist and testClassMethodCount.

Instructions

  1. Decide the event name and handler name. Event name is snake_case (e.g. change_ip). Handler is PascalCase prefixed with get (e.g. getChangeIp). Verify no existing entry in getHooks() already covers this event.

  2. Register the hook in getHooks() inside src/Plugin.php. Add one line to the returned array:

    self::$module.'.change_ip' => [__CLASS__, 'getChangeIp'],
    

    If the new event should share an existing handler (like reactivate → getActivate), point to the existing method name instead of creating a new one. Verify the array key is unique before proceeding.

  3. Add the handler method to src/Plugin.php after the last existing handler, before the closing }:

    /**
     * @param \Symfony\Component\EventDispatcher\GenericEvent $event
     */
    public static function getChangeIp(GenericEvent $event)
    {
        if ($event['category'] == get_service_define('PARALLELS')) {
            $serviceClass = $event->getSubject();
            myadmin_log(self::$module, 'info', 'Parallels <Action Description>', __LINE__, __FILE__, self::$module, $serviceClass->getId());
            // ... call function_requirements() then the inc function ...
            $event->stopPropagation();
        }
    }
    

    The use Symfony\Component\EventDispatcher\GenericEvent; import is already present at the top — do not add it again.

  4. If the handler calls an inc function, add function_requirements('your_function') before the call and register the function path in getRequirements():

    $loader->add_requirement('your_function', '/../src/parallels.inc.php');
    

    Verify the function exists in src/parallels.inc.php before registering.

  5. Update tests/PluginTest.php — add the new hook key to the $expectedKeys array in testGetHooksContainsExpectedKeys() and bump the count in testClassMethodCount() if a new method was added. Run composer test to confirm all tests pass.

Examples

User says: "Add a hook for licenses.change_ip that logs the old and new IP"

Actions taken:

getHooks() addition in src/Plugin.php:

self::$module.'.change_ip' => [__CLASS__, 'getChangeIp'],

New handler method in src/Plugin.php:

public static function getChangeIp(GenericEvent $event)
{
    if ($event['category'] == get_service_define('PARALLELS')) {
        $serviceClass = $event->getSubject();
        myadmin_log(self::$module, 'info', 'IP Change - (OLD:'.$serviceClass->getIp().") (NEW:{$event['newip']})", __LINE__, __FILE__, self::$module, $serviceClass->getId());
        // perform IP change logic here
        $event['status'] = 'ok';
        $event['status_text'] = 'The IP Address has been changed.';
        $event->stopPropagation();
    }
}

Result: composer test passes; testGetHooksContainsExpectedKeys and testAllHookMethodsExist both green.

Common Issues

  • testClassMethodCount fails with "Expected 7, got 8": You added a new handler but did not update the count assertion in tests/PluginTest.php. Change the assertCount(7, ...) to the new total.
  • testAllHookMethodsExist fails: The method name string in getHooks() does not exactly match the declared method name. Check spelling and PascalCase — getChangeIp ≠ getChangeIP.
  • testEventHandlerMethodSignatures fails with "parameter should be GenericEvent": The handler is missing the GenericEvent $event type hint, or the use statement is absent (it lives at the top of src/Plugin.php — do not remove it).
  • stopPropagation not called: Event will continue dispatching to other plugins and produce duplicate side-effects. Always place $event->stopPropagation() as the final statement inside the category guard.
  • function_requirements not registered: If activate_parallels or a new inc function is called but not registered in getRequirements(), it will throw a fatal error at runtime. Verify $loader->add_requirement('fn_name', '...') is present.

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/add-event-hook-to-plugin-php-mrwakdo8/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/add-event-hook-to-plugin-php-mrwakdo8/download' --output '.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8/SKILL.md.part' && mv '.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8/SKILL.md.part' '.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8/SKILL.md' && test -s '.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/plugin-hook' && cp -R '.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8' '.claude/skills/plugin-hook'

Cursor
test -f '.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8/SKILL.md' && test -s '.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/plugin-hook' && cp -R '.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8' '.cursor/skills/plugin-hook'

Codex
test -f '.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8/SKILL.md' && test -s '.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/plugin-hook' && cp -R '.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8' '.agents/skills/plugin-hook'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/add-event-hook-to-plugin-php-mrwakdo8'

openskills read 'add-event-hook-to-plugin-php-mrwakdo8'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/add-event-hook-to-plugin-php-mrwakdo8/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires