Symfony 4, 如何将通用控制器实现为服务? [英] Symfony 4, How to implement a general controller as a service?

查看:36
本文介绍了Symfony 4, 如何将通用控制器实现为服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个控制器

Controller1.php

<?php


namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class file1Controller extends AbstractController
{
    /**
     * @Route("/Some/URI", methods={"GET"})
     * @param Request $request
     * @return JsonResponse
     */
    public function list(Request $request)
    {
        if (empty($request->headers->get('api-key'))) {
            return new JsonResponse(['error' => 'Please provide an API_key'], 401);
        }

        if ($request->headers->get('api-key') !== $_ENV['API_KEY']) {
            return new JsonResponse(['error' => 'Invalid API key'], 401);
        }

        return new JsonResponse($this->getDoctrine()->getRepository('App:Something')->findAll());
    }
}

完全按预期工作(使用 Postman 和我的浏览器对其进行了测试).我想概括地将通用控制器作为服务,并为每个控制器使用该服务,Controller1.phpController2.phpController3.php 在方法 getRepository 中,除了 @routeSomething 之外,一切都相同.

Which works exactly as intended (tested it with Postman and with my browser). I would like to generalize to make a general controller as a Service and use that Service for each controller, Controller1.php, Controller2.php and Controller3.php where everything is the same excpet the @route and the Something inside the method getRepository.

这是我的目标:

GeneralService.php

<?php


namespace Service;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;


class GeneralService
{
    /**
     * @param Request $request
     * @param String $entity
     * @return JsonResponse
     */
    public function list(Request $request, String $entity)
    {
        if (empty($request->headers->get('api-key'))) {
            return new JsonResponse(['error' => 'Please provide an API_key'], 401);
        }

        if ($request->headers->get('api-key') !== $_ENV['API_KEY']) {
            return new JsonResponse(['error' => 'Invalid API key'], 401);
        }

        return new JsonResponse($this->getDoctrine()->getRepository('App:{$entity}')->findAll());
    }

}

然后将Controller1.php改为SubscriptionController.php:

<?php


namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Service\GeneralService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class SubscriptionController extends AbstractController
{
    /**
     * @Route("/Some/Uri", methods={"GET"})
     * @param GeneralService $generalService
     * @param Request $request
     * @return JsonResponse
     */
    public function AuthenticateAPI(GeneralService $generalService, Request $request)
    {
        $AuthenticatorObject = $generalService->list($request ,'Something');
        return $AuthenticatorObject;
    }

}

不幸的是,这不起作用并产生以下错误:

This unfortunately does not work and yields the following error:

InvalidArgumentException

InvalidArgumentException

无法确定App\Controller\Controller1::AuthenticateAPI()"的控制器参数:$generalService 参数使用不存在的类或接口:Service\GeneralService"进行类型提示.

Cannot determine controller argument for "App\Controller\Controller1::AuthenticateAPI()": the $generalService argument is type-hinted with the non-existent class or interface: "Service\GeneralService".

我不知道这个错误是从哪里来的,也不知道为什么会发生.有人能帮我理解为什么会这样以及如何解决吗?

I don't see where this error is coming from nor why it's happening. Could somehelp help me understand why is this the case and how to fix it?

推荐答案

看起来您导入的服务有误,我们在 tchat 中讨论了其他一些问题.

It looks like your import of the service is wrong and some other things that we spoke about in tchat.

重要:

  • 服务应该在 src/Service 文件夹中.
  • 不应在 services.yml 中排除该服务

最终解决方案:

服务:

namespace App\Service;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface; 

class GeneralService
{

    private $entityManager;

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

    /**
     * @param Request $request
     * @param String $entity
     * @return JsonResponse
     */
    public function list(Request $request, String $entity)
    {
        if (empty($request->headers->get('api-key'))) {
            return new JsonResponse(['error' => 'Please provide an API_key'], 401);
        }

        if ($request->headers->get('api-key') !== $_ENV['API_KEY']) {
            return new JsonResponse(['error' => 'Invalid API key'], 401);
        }

        return new JsonResponse($this->entityManager->getRepository($entity)->findAll()); 
    }

}

和控制器:

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Service\GeneralService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class SubscriptionController extends AbstractController
{

    /**
    * @Route("/Some/Uri", methods={"GET"})
    * @param GeneralService $generalService
    * @param Request $request
    * @return JsonResponse
    */
    public function AuthenticateAPI(GeneralService $generalService, Request $request)
    {
        $AuthenticatorObject = $generalService->list($request , 'App\Entity\Something');
        return $AuthenticatorObject;
    }
}

这篇关于Symfony 4, 如何将通用控制器实现为服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆