向 EventSubscriber 注入服务

Inject service to EventSubscriber

我的代码有问题。我有 EventSubscriber:

<?php

namespace App\EventSubscriber;

use App\Service\PostService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class NewPostSubscriber implements EventSubscriberInterface
{
    /**
     * @var PostService $postService
     */
    private $postService;

    /**
     * @param PostService $postService
     */
    public function constructor($postService)
    {
        $this->postService = $postService;
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::REQUEST => 'postNotification'
        ];
    }

    public function postNotification(RequestEvent $event)
    {
        $request = $event->getRequest();

        if ('app_post_createpost' != $request->get('_route')) {
            return;
        }

        $post = $this->postService->deletePost(3);
    }

}

我为他注入 PostService,但是当我向 post 端点发送请求时,我收到异常代码 500 和文本

Call to a member function deletePost() on null

在我的 services.yaml 我有

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true     
        autoconfigure: true 


    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    app.post_service:
        class: App\Service\PostService
        arguments: ['@doctrine.orm.entity_manager']
        autowire: true

    app.new_post_subscriber:
        class: App\EventSubscriber\NewPostSubscriber
        arguments: ['@app.post_service']
        autowire: false
        tags:
            - { name: kernel.event_subscriber }

我的 PostService 中有 deletePost 方法。我不知道出了什么问题,我有服务和 deletePost 方法,服务已注入订阅者但仍然无法正常工作。

在 symfony 4 中你不需要在 services.yaml 中声明你的服务。你可以这样做

private $postService;

/**
 * @param PostService $postService
 */
public function __construct(PostService $postService)
{
    $this->postService = $postService;
}

并且在您的 PostService 中

private $em;

public function __construct(EntityManagerInterface $em)
{
    $this->em = $em;
}

另外你的构造函数名字有误 constructor 必须是 __construct