From eaebee7879e0fbab13e3d11f7d2b98375e43aad9 Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Wed, 21 Aug 2024 12:36:57 +0200 Subject: [PATCH] add docs related to new events hook --- en/appendices/5-1-migration-guide.rst | 2 ++ en/core-libraries/events.rst | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/en/appendices/5-1-migration-guide.rst b/en/appendices/5-1-migration-guide.rst index dc9f173acd..791f17908b 100644 --- a/en/appendices/5-1-migration-guide.rst +++ b/en/appendices/5-1-migration-guide.rst @@ -88,6 +88,8 @@ Core - The ``toString``, ``toInt``, ``toBool`` functions were added. They give you a typesafe way to cast request data or other input and return ``null`` when conversion fails. - ``pathCombine()`` was added to help build paths without worrying about duplicate and trailing slashes. +- A new ``events`` hook was added to the ``BaseApplication`` as well as the ``BasePlugin`` class. This hook + is the recommended way to register global event listeners for you application. See :ref:`Registering Listeners ` Database -------- diff --git a/en/core-libraries/events.rst b/en/core-libraries/events.rst index 5aa43ad40f..032d7f18b2 100644 --- a/en/core-libraries/events.rst +++ b/en/core-libraries/events.rst @@ -198,6 +198,30 @@ As you can see in the above code, the ``on()`` function will accept instances of the ``EventListener`` interface. Internally, the event manager will use ``implementedEvents()`` to attach the correct callbacks. +.. versionadded:: 5.1.0 + The ``events`` hook was added to the ``BaseApplication`` as well as the ``BasePlugin`` class + +As of CakePHP 5.1 it is recommended to register event listeners by adding them via the ``events`` hook in your application or plugin class:: + + namespace App; + + use App\Event\UserStatistic; + use Cake\Event\EventManagerInterface; + use Cake\Http\BaseApplication; + + class Application extends BaseApplication + { + // The rest of your Application class + + public function events(EventManagerInterface $eventManager): EventManagerInterface + { + $statistics = new UserStatistic(); + $eventManager->on($statistics); + + return $eventManager; + } + } + Registering Anonymous Listeners -------------------------------