Api platform 教程1---创建您的第一个 ApiResource
我们为爱炫耀宝藏的龙构建一个API,目前我们的项目还没有一个数据库实体,我们需要创建一个以存储所有宝藏
php bin/console make:entity
我们把实体命名为Dragon,Treasure,在Mark this class as an API platform resource时选择no。
我们开始添加属性。以 name 作为字符串开头,长度默认为 255,并使其不可为空。然后,添加 description 和 text 类型,并使其不可为空。我们还需要一个 value ,比如......宝藏值多少钱。这将是一个不可为空的 integer 。我们必须有一个 coolFactor :龙需要指定这个宝藏有多么棒。这将是 1 到 10 之间的数字,因此请将其设为 integer 并且不可为空。然后, createdAt datetime_immutable 不可为 null...最后,添加一个 isPublished 属性,该属性也是 boolean 类型不可为空。按“输入”完成。
<?php
namespace App\Entity;
use App\Repository\DragonTreasureRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: DragonTreasureRepository::class)]
class DragonTreasure
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $name = null;
#[ORM\Column(type: Types::TEXT)]
private ?string $description = null;
#[ORM\Column]
private ?int $value = null;
#[ORM\Column]
private ?int $coolFactor = null;
#[ORM\Column]
private ?\DateTimeImmutable $createdAt = null;
#[ORM\Column]
private ?bool $isPublished = null;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): static
{
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): static
{
$this->description = $description;
return $this;
}
public function getValue(): ?int
{
return $this->value;
}
public function setValue(int $value): static
{
$this->value = $value;
return $this;
}
public function getCoolFactor(): ?int
{
return $this->coolFactor;
}
public function setCoolFactor(int $coolFactor): static
{
$this->coolFactor = $coolFactor;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeImmutable $createdAt): static
{
$this->createdAt = $createdAt;
return $this;
}
public function isPublished(): ?bool
{
return $this->isPublished;
}
public function setPublished(bool $isPublished): static
{
$this->isPublished = $isPublished;
return $this;
}
}
然后我们通过migration把实体生成到数据库
php bin/console make:migration
php bin/console doctrine:migrations:migrate
我们现在有一个实体和一个数据库表。但如果你去刷新文档......那里仍然什么也没有。我们需要做的是告诉 API Platform 将我们的 DragonTreasure 实体公开为 API 资源。为此,请在类上方添加一个名为 ApiResource 的新属性。点击“tab”添加 use 语句。
// src/Entity/DragonTreasure.php
use ApiPlatform\Metadata\ApiResource;
#[ORM\Entity(repositoryClass: DragonTreasureRepository::class)]
#[ApiResource]
class DragonTreasure
{
//....
}
然后我们刷新API文档页面,可以看到现在有6个API端点,两个GET分别表示取列表和取单个详情,然后是POST增加,PATCH修改,PUT修改,DELETE删除,这不仅仅是文档,还是可在线操作的端点,现在如果你在第一个GET上点击“Try it out”然后"Execute",数据里什么都没有 因为我们的数据库里还是空的