alcalyn / serializable-api-response
允许将原始对象作为控制器响应返回,以便稍后由序列化器序列化并转换为 Symfony 响应。
1.1.0
2018-04-25 11:06 UTC
Requires
- php: >=5.4
- jms/serializer: ~1.1|~2.0
- symfony/http-foundation: ~2.0|~3.0|~4.0
- symfony/http-kernel: ~2.0|~3.0|~4.0
This package is not auto-updated.
Last update: 2024-09-14 19:31:08 UTC
README
如果你使用 Symfony Http foundation 和 JMS Serializer,这个库允许返回原始对象和状态码作为控制器响应,以便稍后由序列化器序列化并转换为 Symfony 响应。
问题:如果使用 Symfony Response,或者返回原始对象并使用过滤器监听器,则 Symfony 会将响应内容转换为字符串,这时我们无法传递状态码。
安装
通过 composer 安装
{ "require": { "alcalyn/serializable-api-response": "~1.0" } }
使用方法
在控制器中返回尚未序列化的响应
use Symfony\Component\HttpKernel\Exception\ConflictHttpException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Alcalyn\SerializableApiResponse\ApiResponse; use Acme\UserApi\Exception\UserAlreadyExistsException; class UserController { /** * @param Request $request * * @return ApiResponse * * @throws ConflictHttpException if username already exists. */ public function registerUserAction(Request $request) { $username = $request->request->get('username'); $password = $request->request->get('password'); try { $user = $this->userManager->createUser($username, $password); } catch (UserAlreadyExistsException $e) { throw new ConflictHttpException('An user with username "'.$username.'" already exists.', $e); } return new ApiResponse($user, Response::HTTP_CREATED); } }
注册 ApiResponse 过滤器监听器
在 Silex 中
use Symfony\Component\HttpKernel\KernelEvents; use Alcalyn\SerializableApiResponse\ApiResponseFilter; // Register reponse filter as a service $this['acme.listener.api_response_filter'] = function () { $serializer = $this['serializer']; // Assuming your serializer service has this name return new ApiResponseFilter($serializer); }; // Listen Kernel response to convert ApiResponse with raw object to Symfony Response with serialized data $this->on(KernelEvents::VIEW, function ($event) { $this['acme.listener.api_response_filter']->onKernelView($event); });
许可
此项目受MIT 许可证保护