wizards/rest-bundle

将 php-rest-api 集成到 Symfony 中。

1.0-beta5 2021-01-17 22:19 UTC

README

为 wizards/php-rest-api 提供的 Symfony 扩展包。

Build Status

帮助您以简洁、高效的方式创建 REST API。它将帮助您构思成熟且易于发现的 API,得益于 jsonapi 规范。无论输出序列化方式如何,请求格式都将保持一致。有关更多文档和说明,请参阅 http://github.com/wizardstechnologies/php-rest-api。您可以在 https://github.com/BigZ/promoteapi 上找到一个示例项目。

要求

symfony >= 4.4
php >= 7.3

安装

composer require wizards/rest-bundle

配置

创建一个包含以下值的配置文件

# config/bundles/wizards_rest.yaml
wizards_rest:
	data_source: orm|array # Choose between ORM and Array for your data source. More will be added soon
	reader: annotation|array
	format: jsonapi|array
	base_url: your_url

使用方法

以简单和可配置的方式创建 REST API!

此扩展包简化了 wizard 的 php rest api 的使用,并为 Symfony 提供了一些额外的功能。

如果您使用 symfony flex,这些服务将自动注册。

要序列化单个资源,只需从控制器返回对象即可

public function getArtistAction(string $id, EntityManagerInterface $entityManager)
{
    try {
        $artist = $entityManager->find(Artist::class, $id);
    } catch (\Exception $exception) {
        throw new NotFoundHttpException('Artist not found.');
    }

    return $artist;
}

注意,我们不使用实体参数注入器,因为我们想自己分发错误,以便正确格式化。

要序列化集合,请使用 collectionManager

public function getArtistsAction(CollectionManager $collectionManager, ServerRequestInterface $request)
{
    return $collectionManager->getPaginatedCollection(Artist::class, $request);
}

要反序列化输入,请使用 json 特性

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Wizards\RestBundle\Controller\JsonControllerTrait;

class ArtistController extends AbstractController
{
    use JsonControllerTrait;
	public function postArtistAction(Request $request, EntityManagerInterface $entityManager)
    {
        $artist = new Artist();
        $form = $this->createForm(ArtistType::class, $artist);
        $this->handleJsonForm($form, $request);

        if (!$form->isValid()) {
            $this->throwRestErrorFromForm($form);
        }

        $entityManager->persist($artist);
        $entityManager->flush();

        return $artist;
    }
}