Sunday, January 23, 2022

[FIXED] Inject service to EventSubscriber

Issue

I have problem with my code. I have 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);
    }

}

and i inject for him PostService, but when i send request to post endpoint then i receive exception witj code 500 and text

Call to a member function deletePost() on null

In my services.yaml i have

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 }

I have method deletePost in my PostService. I don't know what is wrong, i have service and deletePost method, service is inject to subscriber but still not working.


Solution

In symfony 4 you don't need declare your services in services.yaml. You can do like this

private $postService;

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

And in your PostService

private $em;

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

Also you have wrong name of your constructor constructor must be __construct



Answered By - Ihor Kostrov

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.