Slim 3 - 更新了返回两个数组值的闪存消息


Slim 3 - updated Flash messages returning two array values

所以我最近决定将我的 Slim2 应用程序转换为较新的第 3 版,很多应用程序都必须更改等等。

另一件事是从核心框架中删除了 flash 消息,所以我决定将它们与 composer 一起添加回去,我意识到它们也发生了变化,出于某种原因,我得到了一个具有两个值而不是一个值的数组。

$container['flash'] = function ($c) {
    return new 'Slim'Flash'Messages();
};
$this->app->flash->addMessage('error', 'hello');
$flash = $this->flash->getMessages();
print_r($flash); // returns Array ( [error] => Array ( [0] => hello [1] => hello ) )

我的模板显然也抱怨这一点,因为它的类型不正确

Notice: Array to string conversion in cache'66'664fc695876aa16573ce7a84cfe29c998af42da36e69199f149219a4e821d44a.php on line 80 Array

我如何能够像 Slim2 使用它们一样使用 Flash 消息?或者我什至应该使用它们,有没有更好的选择可以完成相同的工作?

查看对getMessages()的源调用会返回一个数组。如果您只需要一条消息,则可以使用 getMessage() .例如getMessage("error") .

对于遇到此问题的任何人:Slim 返回一个嵌套数组,您需要遍历两者。

foreach ($messages as $singlemessage) {
    foreach ($singlemessage as $m) {
      print("<li>{$m}</li>");
    }
}

这将获取每个消息集,然后单独打印其中的每条消息。错误"注意:数组到字符串的转换"实际上是在告诉您,您正在尝试将数组打印为字符串,但不能。

您需要

$container['flash']添加到view中,例如:twig .如果您使用 TWIG 渲染视图,则添加它就像这样$view->getEnvironment()->addGlobal('flash', $container['flash']);

然后在你里面查看{% flash.getMessage('error') %}

试试这个

$container['flash'] = function ($container) {
  return new 'Slim'Flash'Messages;
};
$container->flash->addMessage('error', 'hello');
$flash = $container->flash->getMessage('error');
var_dump($flash);

getMessages() 返回所有消息,getMessage($key)仅返回具有此示例$key的消息 error ;

如果你想访问树枝中的闪光对象,你可以为它制作中间件,就像FlashMiddleware

class FlashMiddleware extends Middleware
{
  public function __invoke($request, $response, $next)
  {
    $this->view->getEnvironment()->addGlobal('flash', $this->flash);
    return $next($request, $response);
  }
}

对于基本中间件

class Middleware
{
  protected $container;
  public function __construct($container)
  {
    $this->container = $container;
  }
  public function __get($property)
  {
    if (isset($this->cotainer->{$property})) {
      return $this->cotainer->{$property};
    }
    // otherwise error
  }
}

最后在你的树枝里,你可以这样做

{% if flash.hasMessage('error') %}
    {{ flash.getMessage('error') | first }}
{% endif %}