basster/lazy-response-bundle

一个支持所谓懒加载的Symfony控制器响应的库。

2.0 2021-03-01 16:05 UTC

This package is auto-updated.

Last update: 2024-08-29 05:22:54 UTC


README

Build Status Scrutinizer Code Quality Code Coverage

我更喜欢在Symfony控制器外部处理响应类型,并返回DTO,然后在之后将它们转换为相应的响应。一些非常标准的DTO和kernel.view事件处理器在这个库中。

安装

composer req basster/lazy-response-bundle

如果你使用 Symfony Flex,那么你在这里就完成了,否则将以下行添加到你的services.yaml文件中:

services:
    _defaults:
        # make sure autowire and autoconfigure are activated
        autowire: true      
        autoconfigure: true
    
    Basster\LazyResponseBundle\Response\Handler\TwigResponseHandler: ~
    Basster\LazyResponseBundle\Response\Handler\RedirectResponseHandler: ~
    Basster\LazyResponseBundle\Response\Handler\JsonSerializeResponseHandler: ~

使用

我更喜欢纯Symfony控制器,不扩展Symfony\Bundle\FrameworkBundle\Controller\AbstractController,使用适当的依赖注入来获取我想要使用的服务。我也喜欢@Template注解的想法,所以控制器返回数据,而不是响应。但是有时,这也带来了一些缺点:如果你想要给你的控制器动作添加适当的类型提示。例如,如果你在一个动作中处理表单,你会在表单处理成功后返回一个视图模型数组或一个RedirectResponse。缺点:这些“返回类型”之间没有任何共同点。

以下是我的方法

<?php 
use Basster\LazyResponseBundle\Response\LazyResponseInterface;
use Basster\LazyResponseBundle\Response\RedirectResponse;
use Basster\LazyResponseBundle\Response\TemplateResponse;

class MyController {
    public function commentNew(Request $request, FormFactoryInterface $formFactory): LazyResponseInterface
    {
        $post = new Post();
    
        $form = $formFactory->create(PostType::class, $post);
        $form->handleRequest($request);
    
        if ($form->isSubmitted() && $form->isValid()) {
            // do stuff with the submitted data
            return new RedirectResponse('post_index'); // will end up in a RedirectResponse
        }
        
        return new TemplateResponse('post/new.html.twig',[
            'post' => $post,
            'form' => $form->createView(),
        ]); // will end up in a regular Response with contents of the rendered template.
    }
}

LazyResponseInterface

Basster\LazyResponseBundle\Response\LazyResponseInterface只是一个标记接口,用于多个DTO共享。目前有以下标准DTO:

  • Basster\LazyResponseBundle\Response\JsonSerializeResponse
  • Basster\LazyResponseBundle\Response\RedirectResponse
  • Basster\LazyResponseBundle\Response\TemplateResponse

响应DTO是框架无关的,可以在任何你想使用的地方使用!

LazyResponseHandlers

这些库附带的处理程序是Symfony kernel.view事件订阅者,将DTO转换为Symfony响应对象。

  • Basster\LazyResponseBundle\Response\Handler\JsonSerializeResponseHandler处理JsonSerializeResponse并利用Symfony序列化器。
  • Basster\LazyResponseBundle\Response\Handler\RedirectResponseHandler处理RedirectResponse并利用Symfony路由器。
  • Basster\LazyResponseBundle\Response\Handler\TwigResponseHandler处理TemplateResponse并利用Twig(哦!)。