发出API GET请求时,如何在Symfony 4中使用URL和路由返回特定数据?

用户名

我是Symfony的新手,正在尝试学习基础知识。我最近看到了这个问题,我想学习路由的工作方式。所以我Controller1.php从问题中复制了并将其更改为UserController.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 UsersController extends AbstractController
{
    /**
     * @Route("/listOf/Users", 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\Entity\User')->findAll());
    }
}

如OP所言,确实可以正常工作并返回以下列表(使用Sequel Pro手动添加的数据)列表:

    [
    {
        "id": 14,
        "name": "user1 Name"
    },
    {
        "id": 226,
        "name": "user2 Name"
    },
    {
        "id": 383,
        "name": "user3 Name"
    }
    ]

因此,我的下一步是学习如何调整此用户列表,以返回具有给定的特定用户id因此,我遵循了有关路由的Symfony官方文档所以我将代码更改为以下内容:

<?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 UsersController extends AbstractController
{
    /**
     * @Route("/listOf/Users/{IdUser}", requirements={"IdUser"="\d+"},  methods={"GET"})
     * @param Request $request
     * @param int $IdUser
     * @return JsonResponse
     */
    public function list(Request $request, int $IdUser)
    {
        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\User\{IdUser}')->findAll());
    }
}

并尝试请求ID为14的用户数据,但这无效,并产生以下错误:

类App \ Entity \ User {IdUser}不存在(500内部服务器错误)

为了能够做我想做的事情,我还需要做些什么改变?

这是我的User.php实体:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements \JsonSerializable
{

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function jsonSerialize()
    {
        return get_object_vars($this);
    }
}

UserRepository.php除了自动生成的代码外,什么也没有。

编辑:我的第一个请求的工作形式是:http://domainName.local:80/listOf/Users我的第二个请求是:http://domainName.local:80/listOf/Users/14

Nimmneun

如前所述,这就是为什么它不起作用以及如何使其起作用。

让我们检查一下代码的打击:

$this->getDoctrine()->getRepository('App\Entity\User\{IdUser}')->findAll();

基本上,您是在说:学说,给我一个负责App\Entity\User\{IdUser}从字面上处理实体的存储库,并且没有这样的实体类。您真正想要的是仓库App\Entity\User

传递给该getRepository()方法的字符串必须始终是实体的全限定类名-句点。为了确保您在这里没有任何错字,使用实体的类常量非常有帮助,如下所示

$repo = $this->getDoctrine()->getRepository(App\Entity\User::class);

有了存储库后,您可以调用其不同的方法,如教义文档中所示:https://www.doctrine-project.org/api/orm/latest/Doctrine/ORM/EntityRepository.html对于您而言,$IdUser您要映射到id用户类的db列/实体属性的变量既然您知道您恰好希望这个ID为14的用户,那么您要做的就是告诉存储库查找一个看起来像这样的用户。

// here's the example for your specific case
$user = $repo->findOneBy(['id' => $IdUser]);

// another example could be e.g. to search a user by their email address
$user = $repo->findOneBy(['email' => $email]);

// you can also pass multiple conditions to find*By methods
$user = $repo->findOneBy([
    'first_name' => $firstName,
    'last_name' => $lastName,
]);

希望这比混淆=>更有用

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何从getStaticProps向API路由发出请求

向Google Contacts REST API发出HTTP GET请求时如何使用API密钥

在流星中,您如何发出API请求

如何使用 React 发出 API 请求?

如何在Flutter中针对Web API发出POST请求

如何在React中自动发出API请求?

如何向外部API发出GET和POST请求?

如何使用Angular向API网关发出Get请求?

如何在php中向eBay Restful API发出GET cURL请求

使用pastebin API发出简单的POST请求

使用python向RESTful API发出请求

发出 POST 请求以休息 api,然后发出 GET 请求以获取正在添加的资源的附加数据

当您不知道页数时,如何在使用Node.js的while循环中向API发出多个分页的GET请求?

如何在C#中向Google自定义搜索API发出GET REST API请求

如何在 Symfony 4 中发出 Ajax 请求?

Python-如何使用请求向API发出PATCH请求

ECONNRREFUSED 使用 Nodejs 向 API 发出获取请求时出错

在对StackExchange API AngularJS发出HTTP请求时如何使用请求密钥

使用python向Stackoverflow API发出请求时,如何通过标头传递我的API密钥

向Objective-C中的解析API发出GET请求

向Node.js中的JSON API发出GET请求?

无法使用Express API发出POST或GET请求

如何在Google Apps脚本中使用UrlFetchApp发出Drive API批处理请求

如何在 Python 中使用 while 循环发出多个 API 请求?

如何通过在 Firefox 中 fetch js 向 API 发出请求?

如何使用 riot-lol-api 连续发出多个请求?

如何使用spring RestTemplate针对Cloudant API发出测试请求?

如何使用restapi向Github存储库发出api请求?

在应用中发出GET请求时ECONNREFUSED,但API成功返回JSON