我有以下代码在将数据发送到前端之前检查 API 密钥是否正确。
file1Controller.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"}) // "/Some/URI" here
* @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()); //Something here
}
}
对于我的简单学习示例,它完全按预期工作(使用 Postman 对其进行了测试)。我想概括一下,以便我可以在其他地方使用它。除了有注释的部分,几乎所有内容都应该保持不变。我尝试了以下方法:
General.php
<?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class General extends AbstractController
{
private $request;
private $route;
private $entity;
/**
* ApiKeyAuthenticator constructor.
* @param Request $request
* @param String $route
* @param String $entity
*/
function __construct(Request $request, String $route, String $entity)
{
$this->request = $request;
$this->route = $route;
$this->entity = $entity;
}
/**
* @Route({$route}, methods={"GET"}) //notice here
* @return JsonResponse
*/
public function list()
{
if (empty($this->request->headers->get('api-key'))) {
return new JsonResponse(['error' => 'Please provide an API_key'], 401);
}
if ($this->request->headers->get('api-key') !== $_ENV['API_KEY']) {
return new JsonResponse(['error' => 'Invalid API key'], 401);
}
return new JsonResponse($this->getDoctrine()->getRepository('App:{$this->entity}')->findAll()); //notice here
}
}
然后我将代码更改file1Controller.php
为:
<?php
namespace App\Controller;
require(__DIR__.'/../General.php'); //note that there's no error accessing the file here
use Symfony\Component\HttpFoundation\Request;
class file1Controller
{
/**
* @param Request $request
*/
public function AuthenticateAPI(Request $request)
{
$AuthenticatorObject = new ApiKeyAuthenticator($request, "/Some/URI", 'Something'); //getting undefiend class
return $AuthenticatorObject;
}
}
不幸的是,在使用 Postman 对其进行测试时,这不起作用,并且我在此行$AuthenticatorObject = new ApiKeyAuthenticator($request, "/Some/URI", 'Something');
中遇到了 undefiend 类错误file1Controller.php
我做错了什么,我该如何解决?
你不应该在 Symfony 中这样调用你的控制器:
require(__DIR__.'/../General.php'); //note that there's no error accessing the file here
请查看 Symfony 文档中定义和访问控制器作为服务:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句