原生浏览器通知

在 PHP 内部通知用户

通过 Symfony 的 Notifier 组件向所有人发送实时的原生浏览器通知。

composer require symfony/ux-notify
// ... use statements hidden - click to show
use App\Form\SendNotificationForm; use App\Service\UxPackageRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Notifier\Bridge\Mercure\MercureOptions; use Symfony\Component\Notifier\ChatterInterface; use Symfony\Component\Notifier\Message\ChatMessage; use Symfony\Component\Routing\Attribute\Route;

class NotifyController extends AbstractController
{
    #[Route('/notify', name: 'app_notify')]
    public function __invoke(UxPackageRepository $packageRepository, Request $request, ChatterInterface $chatter): Response
    {
        $package = $packageRepository->find('notify');

        $form = $this->createForm(SendNotificationForm::class);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $message = SendNotificationForm::getTextChoices()[$form->getData()['message']];

            // custom_mercure_chatter_transport is configured in config/packages/notifier.yaml
            $message = (new ChatMessage(
                $message,
                new MercureOptions(['/demo/notifier'])
            ))->transport('custom_mercure_chatter_transport');
            $chatter->send($message);

            return $this->redirectToRoute('app_notify');
        }

        return $this->render('ux_packages/notify.html.twig', [
            'package' => $package,
            'form' => $form,
        ]);
    }
}
{% extends 'base.html.twig' %}

{% block body %}
    {{ stream_notifications(['/demo/notifier']) }}
    
    {{ form_start(form) }}
        {{ form_widget(form) }}
    
        <button type="submit" class="btn btn-primary">Send Notification</button>
    {{ form_end(form) }}
{% endblock %}
Symfony logo

UX Notify

这将作为浏览器通知发送给此页面上的任何用户!(某些浏览器不支持 Notification API

安装它

$ composer require symfony/ux-notify