【问题标题】:How do I send variables to an error layout in ZF3?如何将变量发送到 ZF3 中的错误布局?
【发布时间】:2019-04-19 14:44:22
【问题描述】:

将变量发送到布局模板的正确方法是什么?因为它可以在错误页面中接近?

我在所有前端控制器之上都有 AppFrontController。它在 onDispatch() 方法中有代码(代码就在附近):

 $assocArrayOfVars = $this->MyPlugin()->getDbVariablesArray();
  foreach($assocArrayOfVars as $name => $value){
     $this->layout()->$name = $value;
  }

  list($catalog, $count_goods) = $this->MyPlugin()->getStandardCatalogDataForLayout();
  $this->layout()->catalog = $catalog;
  $this->layout()->count_goods = $count_goods;

因此,我在每个前端页面中都有我的局部变量。但我没有在错误页面中。我该如何解决这个问题?我非常需要你的建议!谢谢!

【问题讨论】:

  • throw new CustomException($var1, $var2, $var3, $message, $code, $previous) -> class CustomException extends Exception { pub fun __construct(string $var1, string $var2, int $var3, $message = '', $code = null, Throwable $previous = null) { ...} } -> 抱歉,有几个,应该是。只需确保您抛出正确的状态,并且在您的特定错误布局中有一个默认的“异常”处理,并且如果它是您的自定义异常类型 ($error instanceof CustomException) 则在其中进行检查。
  • 在此处查看示例配置:olegkrivtsov.github.io/using-zend-framework-3-book/html/en/… - 查看Skeleton view/error folder 以了解其通常处理方式。根据需要修改。
  • 错误页面默认读取抛出的异常。但如果你想添加额外的信息(例如:会话、cookie 等),你必须监听 MvcEvent::EVENT_RENDER。您可以检查是否有任何异常抛出。请检查这个关于error handling的问题。

标签: zend-framework zend-framework2 zend-framework3 zend-view


【解决方案1】:

感谢您的建议!问题解决了。下面是最终版本 Module.php 文件的代码。根据 froschdesign 的建议,我使用侦听器而不是“父控制器”。

 public function onBootstrap(MvcEvent $event)
   {
      $application = $event->getApplication();
      $eventManager = $application->getEventManager();
      $eventManager->attach('dispatch', array($this, 'loadConfiguration'), 2);
      $eventManager->attach('dispatch.error', array($this, 'loadConfiguration'), 2);
}


 public function loadConfiguration(MvcEvent $e)
   {
      $application = $e->getApplication();
      $sm = $application->getServiceManager();
      $sharedManager = $application->getEventManager()->getSharedManager();

      $router = $sm->get('router');
      $request = $sm->get('request');

      $zendCart = $sm->get('ControllerPluginManager')->get('ZendCart');
      $myPlugin = $sm->get('ControllerPluginManager')->get('MyPlugin');
      $viewModel = $e->getViewModel();

      $viewModel->setVariable('total', $zendCart->total());
      $viewModel->setVariable('total_items', $zendCart->total_items());

      $viewModel->setVariable('rusmonth', $rusmonth);

      /* Layout variables */
      $assocArrayOfVars = $myPlugin->getDbVariablesArray();
      foreach ($assocArrayOfVars as $name => $value) {
         $viewModel->setVariable($name, $value);
      }

      list($catalog, $count_goods) = $myPlugin->getStandardCatalogDataForLayout();
      $viewModel->setVariable('catalog', $catalog);
      $viewModel->setVariable('count_goods', $count_goods);

   }

更多听众示例here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    相关资源
    最近更新 更多