Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

[11.x] Add support for middlewares & failed handler on broadcastable events #54562

Merged

Conversation

Jacobs63
Copy link
Contributor

@Jacobs63 Jacobs63 commented Feb 11, 2025

This PR introduces support for using middlewares & a failure handler on broadcastable events.

Currently, classes utilizing the ShouldBroadcast interface are internally transformed to a BroadcastEvent job. This job supports proxying a few of job-specific properties, such as $queue, $connection, $tries, etc., to allow customizing when/how the queueable job is processed. One of the big drawbacks is not being able to define middlewares & job failures, which I, in fact, already expected to work as this can be very handy.
As this should be possible by proxying the data from the original event, just as is the case for some of the aforementioned properties, I would expect to this work when using broadcasting via queue.

Solution

This PR solves this issue by forwarding the middlewares defined on the original event via the middlewares method to the BroadcastEvent job.
The other drawback, job failure, can also now be solved by defining a failed method on the original event.

In summary, the following is now possible:

class TestEvent implements ShouldBroadcast
{
    //

    public function middleware(): array
    {
        return [
            new TestEventMiddleware,
        ];
    }

    public function failed(?Throwable $e = null): void
    {
        Log::error('Test event failed to broadcast!');
    }
}
class TestEventMiddleware
{
    public function handle(object $job, Closure $next)
    {
        Log::info('Handling broadcast event...');

        return $next($job);
    }
}

Possible drawback

The underlying middleware will instead receive a BroadcastEvent, instead of the TestEvent, as the actual job that is processed by our selected queue driver is used on is the BroadcastEvent job, which wraps the original event. Meaning, the event is easily accessible via $job->event, so I'd, in fact, say this should be completely fine and a little mention in the docs should be enough.

Discussion

I'm not 100% decided whether using methods, or properties, should be preferred. Perhaps.. both could work? I'm unsure on what the priority is between $middleware & middleware() on a job.

@taylorotwell taylorotwell merged commit 16da841 into laravel:11.x Feb 11, 2025
44 checks passed
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants