Symfony 4, How to implement a general controller as a service?

后端 未结 2 1863
-上瘾入骨i
-上瘾入骨i 2021-01-16 11:40

I have this controller

Controller1.php



        
2条回答
  •  孤独总比滥情好
    2021-01-16 12:10

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

    Important :

    • The service should be in src/Servicefolder.
    • The service should not be excluded in services.yml

    Final solution for people :

    The service :

    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()); 
        }
    
    }
    

    And the controller :

    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;
        }
    }
    

提交回复
热议问题