InvalidArgumentException Symfony4 - PullRequest
       6

InvalidArgumentException Symfony4

0 голосов
/ 12 ноября 2018

У меня проблема с приложением после того, как я переместил его в докер-контейнер. Я новичок в Symfony и не могу понять, в чем проблема.

После того, как я хочу вызвать свое индексное действие UserController, мой браузер выдает ошибку:

Контроллер "App \ Controller \ UserController" имеет обязательные аргументы конструктора и не существует в контейнере. Вы забыли определить такой сервис? Слишком мало аргументов для функции App \ Controller \ UserController :: __ construct (), 0 передано в /projekty/taskit/vendor/symfony/http-kernel/Controller/ControllerResolver.php в строке 133 и ровно 1 ожидается

Файл My services.yaml:

parameters:
    locale: 'en'

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
        public: false       # Allows optimizing the container by removing unused services; this also means
                            # fetching services directly from the container via $container->get() won't work.
                            # The best practice is to be explicit about your dependencies anyway.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones

    App\Entity\UserRepositoryInterface: '@App\DTO\UserAssembler'

Файл UserController.php

<?php

namespace App\Controller;

use App\Service\UserService;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

/**
 * Class UserController
 * @package App\Controller
 */
class UserController extends AbstractController
{
    /**
     * @var UserService
     */
    private $userService;

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

    /**
     * @Route("/users/", name="users_index")
     */
    public function index()
    {
        $users = $this->userService->findAll();
        return $this->render('user/index.html.twig', array('users' => $users));
    }
}

И мой код файла UserService.php

<?php

namespace App\Service;

use App\Entity\UserRepositoryInterface;
use Doctrine\ORM\EntityNotFoundException;

/**
 * Class UserService
 * @package App\Service
 */
class UserService
{
    /**
     * @var UserRepositoryInterface
     */
    private $userRepository;

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

    /**
     * @return array
     * @throws EntityNotFoundException
     */
    public function findAll() : array
    {
        $users = $this->userRepository->findAll();

        if (is_null($users)) {
            throw new EntityNotFoundException('Table users is empty');
        }
        return $users;
    }
}

1 Ответ

0 голосов
/ 13 ноября 2018

Мне кажется, вы делаете много ненужных вещей, которые уже являются частью фреймворка.Как ваш сервис, что он делает?Вы можете позвонить в ваши репозитории прямо с вашего контроллера.И в вашем контроллере вы объявляете переменные и создаете, что также не нужно.Просто используйте внедрение зависимостей в своей функции в контроллере.Этот небольшой кусочек кода должен работать и заменить и ваш контроллер, и ваш сервис (от которого вы снова можете избавиться).

<?php

namespace App\Controller;

use App\Repository\UserRepository;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

/**
 * Class UserController
 * @package App\Controller
 */
class UserController extends AbstractController
{

    /**
     * @Route("/users/", name="users_index")
     */
    public function index(UserRepository $userRepository)
    {
        $users = $this->userRepository->findAll();
        return $this->render('user/index.html.twig', array('users' => $users));
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...