wizards / rest-bundle
将 php-rest-api 集成到 Symfony 中。
1.0-beta5
2021-01-17 22:19 UTC
Requires
- php: >=7.3
- ext-json: *
- nyholm/psr7: ^1.1
- pagerfanta/pagerfanta: ^2.0
- sensio/framework-extra-bundle: ^5.2
- symfony/http-kernel: ^4.4|^5.0
- symfony/psr-http-message-bridge: ^2.0
- symfony/validator: ^4.4|^5.0
- wizards/rest-api: 0.9.0
Requires (Dev)
- phpmd/phpmd: ^2.9
- phpstan/phpstan: ^0.12
- phpunit/phpunit: ^9.2
- squizlabs/php_codesniffer: ^3.5
- symfony/form: ^4.4|^5.0
- symfony/phpunit-bridge: ^4.4|^5.0
- symfony/var-dumper: ^4.4|^5.0
- dev-master
- 1.0-beta5
- 1.0-beta4
- 1.0-beta3
- 1.0-beta2
- 1.0-beta
- 1.0-alpha
- 0.10.6
- 0.10.5
- 0.10.4
- 0.10.3
- 0.10.2
- 0.10.1
- 0.10.0
- 0.9.7
- 0.9.6
- 0.9.5
- 0.9.4
- 0.9.3
- 0.9.2
- 0.9.1
- 0.9.0
- 0.8.0
- 0.7.0
- 0.6.6
- 0.6.5
- 0.6.4
- 0.6.3
- 0.6.2
- 0.6.1
- 0.6
- 0.5.4
- 0.5.3
- 0.5.2
- 0.5.1
- 0.5
- 0.4.3
- 0.4.2
- 0.4.1
- 0.4
- 0.3
- 0.2
- 0.1
- dev-update072
- dev-chore/tests-and-doc
This package is auto-updated.
Last update: 2024-09-18 06:22:50 UTC
README
为 wizards/php-rest-api 提供的 Symfony 扩展包。
帮助您以简洁、高效的方式创建 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 提供了一些额外的功能。
- 一个订阅者,可自动序列化您的响应
- 一个订阅者,可自动序列化您的异常
- 一个参数转换器,用于向控制器中注入 PSR-7 请求
- 一个多部分异常,可轻松序列化多个错误(如表单错误)
- 一个控制器特性,帮助从 json 和 jsonapi 序列化输入数据
如果您使用 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;
}
}