1

我正在尝试用教义替换zend 表达专辑教程中的 Zend_Db 用法。最重要的是,我想用一个用zend form annotationbuilder构建的表单来删除相册表单和表单工厂。我让 annotationbuilder 工作并收到一个工作表单。

在教程中,表单在album.global.config中定义为依赖:

<?php
return [
  'dependencies' => [
    'factories' => [
      ...     
      Album\Form\AlbumDataForm::class =>
      Album\Form\AlbumDataFormFactory::class,
      ...
    ],
  ],
  'routes' => [
    ...
    [
        'name'            => 'album-update-handle',
        'path'            => '/album/update/:id/handle',
        'middleware'      => [
            Album\Action\AlbumUpdateHandleAction::class,
            Album\Action\AlbumUpdateFormAction::class,
        ],
        'allowed_methods' => ['POST'],
        'options'         => [
            'constraints' => [
                'id' => '[1-9][0-9]*',
            ],
        ],
    ],
    ...
  ],
];

...并注入动作AlbumUpdateFormAction.phpAlbumUpdateFormHandleAction.php

<?php
...
class AlbumUpdateFormAction
{
  public function __construct(
    TemplateRendererInterface $template,
    AlbumRepositoryInterface $albumRepository,
    AlbumDataForm $albumForm
  ) {
    $this->template        = $template;
    $this->albumRepository = $albumRepository;
    $this->albumForm       = $albumForm;
  }
  public function __invoke(
    ServerRequestInterface $request,
    ResponseInterface $response,
    callable $next = null
  ) {
    ...
    if ($this->albumForm->getMessages()) {
      $message = 'Please check your input!';
    } else {
      $message = 'Please change the album!';
    }
    ...
  }
}

由于使用了“处理操作”,因此需要这样做。如果表单验证发生错误,则调用下一个中间件。现在,提取并显示表单元素的错误消息if ($this->albumForm->getMessages()) {

这正是我的问题。我让表单工作,但是当调用下一个中间件时,Album\Action\AlbumUpdateHandleAction::class我的表单是空的,因为我在两个中间件中“从头开始”生成它。我需要做的是,要么将我的 annotationuilder 构建形式定义为依赖项并将其注入中间件,要么将其从一个中间件传递到另一个中间件。

但我不知道如何做到这一点。任何想法都非常受欢迎!

我希望,我已经说清楚了。我必须承认,我对 zend expressive 和相关概念还很陌生。提前致谢, LT

4

1 回答 1

0

zend-expressive 概念是关于中间件的。你在行动中做什么以及如何做完全取决于你自己。处理表单没有固定规则或最佳实践,因为您可以自由使用任何适合您需求的解决方案。使用更新和处理操作是众多可能性之一。

您可以将数据传递给以下中间件的方法是将其注入请求中:

return $next($request->withAttribute('albumForm', $albumForm), $response);

我已经在这里解释了这个概念。

您也可以尝试一个更简单的概念,看看是否符合您的要求。您可以将 AlbumUpdateHandleAction 和 AlbumUpdateFormAction 合并为 AlbumUpdateAction。这样您就不需要将数据传递给下一个中间件,因为所有相关任务都在同一个操作中处理。

于 2016-09-22T06:57:23.540 回答