zend-framework2 - 重定向后获取的好处

标签 zend-framework2

当我开始使用 ZF2 时,我使用的第一个模块是 ZfcUser。当我调试它的 Controller 代码时,我发现了一种奇怪的方式(至少对我而言)来管理操作。我发现像这样的代码

    $prg = $this->prg('zfcuser/changepassword');

    if ($prg instanceof Response) {
        return $prg;
    } elseif ($prg === false) {
        return array(
            'status' => $status,
            'changePasswordForm' => $form,
        );
    }

    //VALIDATE FORM AND DATABASE STUFF
    (...)

行为如下:

  1. 第一次加载 $prg 是假的,所以它返回表单。
  2. 当你提交页面时,$prg 是 Response 的一个实例,所以它返回 $prg。
  3. 当返回 $prg 时,再次调用相同的函数并且 $prg 变成一个包含所有发布数据的数组,因此它跳转到表单和数据库内容的验证。

我认为这是一种奇怪的方法,所以我覆盖了所有需要的函数,用简单的 request->isPost() 替换它。我发现处理第一个加载/发布的数据更容易。

直到现在我才更加重视它。当我尝试上传文件时,我再次面临 Post-Redirect-Get 方法:当表单出现验证错误时,似乎需要防止用户重新选择文件并重新上传。

Post-Redirect-Get 有什么意义?你什么时候推荐使用它(除了评论文件上传)?

最佳答案

如文档所述:

When a user sends a POST request (e.g. after submitting a form), their browser will try to protect them from sending the POST again, breaking the back button, causing browser warnings and pop-ups, and sometimes reposting the form. Instead, when receiving a POST, we should store the data in a session container and redirect the user to a GET request.

所以这个插件的目的是提高用户体验。当您提交表单并尝试刷新页面时,您一定遇到过这个问题,您会收到一条弹出消息,例如(来自 google chrome 的示例):

Confirm Form Resubmission: The page that you're looking for used information that you entered. Returning to that page might cause any action you took to be repeated. Do you want to continue?

您可以在 Post/Redirect/Get Plugin 的文档中获取更多详细信息, 或 File Post/Redirect/Get Plugin如果您的表单处理文件上传。

注意:对于 File Post/Redirect/Get Plugin - Example Usage,第 16 行有一个拼写错误,您应该使用 $this->filePrg() 而不是 $this->prg()。它应该像下面的行。

$prg = $this->filePrg($myForm, '/user/profile-pic', true);

关于zend-framework2 - 重定向后获取的好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15861458/

相关文章:

module - ZF2 : Get module name (or route) in the application layout for menu highlight

php - Doctrine2 挑战,我有 OneToMany,但没有 ManyToOne,

mysql - 关联的 DQL 邮政编码距离

php - ZF2、Oracle、SlmQueueDoctrine、ClearObjectManagerStrategy 不工作

zend-framework2 - 安装建议的 Composer 包 ZF2(Zend Framework 2)

php - Zend Framework 2 中的结果集不适用于 toArray()

php - 敏捷性 : ApiProblem alternative?

php - Zend 框架 2 中的 Zend\ServiceManager\Exception\ServiceNotFoundException

session - Zend\Authentication\Storage\Session session 验证失败,有什么想法吗?