Cakephp 5 Global Event Manager not execute

here is edit method so i want to save data into notification table it would save through event system, but its is not working when i am edit the record in contrast add method (new record) insert then Event fired.

here is afterSave method so it works perfectly fine:-

I set here in global event:- NotificationEvent

please give me any idea how it will be work.? docs not help for this now

src/EventListeners/TestContext.php

<?php
declare(strict_types=1);

namespace App\EventListeners;

use Cake\Event\Event;
use Cake\Event\EventListenerInterface;

class TestContext implements EventListenerInterface
{
    /**
     * @return array<string, mixed>
     */
    public function implementedEvents(): array
    {
        return [
            'Notification.Published' => 'published',
        ];
    }

    /**
     * @param \Cake\Event\Event $event The event
     * @return void
     */
    public function published(Event $event): void
    {
        $data = $event->getData('entity');
    }
}

in controller

public function edit(?int $id = null)
{
    $article = $this->Articles->get($id);

    $this->dispatchEvent('Notification.Published', [
        'entity' => $article
    ]);
}

in config/bootstrap.php

$eventManger = \Cake\Event\EventManager::instance();
$eventManger->on(new \App\EventListeners\TestContext());

works fine for me.


You gotta know, that Controllers and Models each have their own EventManager instance. But all events get “bubbled up” to the global event manager as well so you should always be able to register event listeners on the global event manager.


Also be aware, that the 2nd param of the Event constructor is the subject, not the data present in the event.


Usually you shouldn’t care about manually creating event instances since thats what the EventDispatcherTrait is for which both Controllers as well as Models use by default.

Thats why my example just does $this->dispatchEvent()

Hi!! @KevinPfeifer thank’s brother for replying and help me here… my code also well fine, I just find another issue which was existed in NotificationEvent.php file so I just fix there and now… events are working fine… great!!

Any Idea @KevinPfeifer why not composer install this package

You need to install the 3.0-RC Version of that plugin.

composer require dereuromark/cakephp-ajax:^3.0-RC

yo!!! man thank’s @KevinPfeifer it works
thanks a lot

hi @KevinPfeifer how are you? @KevinPfeifer do you know that RequestHandler->renderAs how it work in cakephp 5. Actually cakephp 4x $this->RequestHandler->renderAs($this,‘json’) I was using this mehod for display json format data from Api side with .json extension and error also print in json format but now in cakephp 5x RequestHandler->renderAs not working because cakephp 5x removed it… is there any method which perform same functionality as in cakephp 4x

https://book.cakephp.org/4/en/controllers/components/request-handling.html
https://book.cakephp.org/4/en/appendices/4-4-migration-guide.html#requesthandlercomponent

yes i know all that @KevinPfeifer but this view Json class does not work if any Error triggered, I mean Error triggered message show in web view but i want to show all errors in json view… please look at that screenshots

cakephp 4x working fine

But in cakephp 5x does not throw in json format error

You need to adjust the exceptionRenderer for that. See Cakephp default error response but i need to json format error response - #8 by KevinPfeifer

nope!! its not working in cakephp 5x version @KevinPfeifer… Mixture Api

I never said you need to use mixerapi, I just said you need to set a custom exceptionRenderer.

But let me hand feed the info to you: There is no ready made plugin yet for CakePHP 5 so in your case you have to copy the plugin GitHub - mixerapi/exception-render: Handles rendering entity validation errors and other exceptions for your API [READ-ONLY] to your own app and adjust it to CakePHP 5 (if there are changes necessary at all)

Just because the plugin can’t be installed via composer doesn’t mean its not compatible with CakePHP 5.

In CakePHP 4.x JSON error responses are handled transparently by the request handler component, which doesn’t exist in 5.x anymore.

If all you want is to bring back that behavior, and you’re using negotiable requests (ie they have a Accepts header), then that behavior can be enabled by adding the respective view class to the error controller.

So if you wanted to add JSON support, you’d add the following call in ErrorController::initialize() (located in src/Controller/ErrorController.php):

$this->addViewClasses([\Cake\View\JsonView::class]);

https://book.cakephp.org/5/en/controllers.html#content-type-negotiation

If you need more control over the behavior, then you’d possibly need a customized exception renderer as noted by @KevinPfeifer

1 Like

thank @ndm its really help me and i got error message in json response, can tell me one thing more here if i do not set negotiable requests… without json extension then how can i print json error message. Now i am getting web based error message

Actually want to throw json error response error when Any User/Client open /api/v1 url without any specific endpoint

There are many different ways in which that could be achieved. One would be instead of using negotiation, to directly set the respective view class in the controllers that should be affected, depending on the requested endpoint if necessary.

So in your error controller’s initialize() method you could do something like this:

if ($this->request->getParam('controller') === 'Api') {
    $this
        ->viewBuilder()
        ->setClassName(\Cake\View\JsonView::class);
}

Depending on the exact route that you’re trying to match you may have to add further conditions for the action, prefix, and/or plugin params.

1 Like

hahahhaah… thanks @ndm its real working & helping me thanks man… now my application get ready for my client.