Slim Flash 消息在 try {} catch() {} 中不起作用
Slim flash messages not working inside try {} catch() {}
我正在使用版本 2.6.1 中的 PHP Slim Framework(由于升级的一些限制 PHP 没有更新的版本)并且在尝试使用内部的闪存消息时a try/catch 阻止消息在呈现模板时不存储在会话中。
例如,下面的代码可以正常工作(当验证器出现错误时,页面会重定向到所需的闪现消息):
$objValidation = FormValidator::isValidData($post);
if($objValidation->bolHasError)
{
$app->flash('objValidation', serialize($objValidation));
$app->flash('selectedData', $post);
return $app->redirect('/app/edit/form/components/');
}
但是如果我开始使用 try 块,如下所示,则 flash 消息不会存储在 $_SESSION 中(甚至不会存储在模板中的 {{ flash }} 中):
try {
$objValidation = FormValidator::isValidData($post);
if($objValidation->bolHasError)
{
$app->flash('objValidation', serialize($objValidation));
$app->flash('selectedData', $post);
return $app->redirect('/app/edit/form/components/');
}
# some other stuff processed here...
}
catch(Exception $e) {
# do something
}
P.S.: 会话以 PHP 本机方式存储 ( session_start() ).
以这种方式使用即显消息有任何范围限制吗?
我发现 try
块创建了一个 "isolated scope"。因此,我尝试在重定向之前放置一个 return false
以测试下一页是否会显示闪现消息。最后flash message存储在$_SESSION变量中(当然没有执行重定向,但至少我发现问题与try
范围有关)。
然后,我找到的解决方案是引发异常并在 catch 块内进行重定向。像这样:
$objValidation = FormValidator::isValidData($post);
if($objValidation->bolHasError)
{
throw new Exception('validation_error');
}
然后将错误捕获到catch块中:
catch(Exception $e)
{
if($e->getMessage() == 'validation_error')
{
$app->flash('objValidation', serialize($objValidation));
$app->flash('formData', $post);
return $app->redirect('/api/form/change/components/');
}
}
这样我就可以将 flash 消息放入模板中。
我正在使用版本 2.6.1 中的 PHP Slim Framework(由于升级的一些限制 PHP 没有更新的版本)并且在尝试使用内部的闪存消息时a try/catch 阻止消息在呈现模板时不存储在会话中。
例如,下面的代码可以正常工作(当验证器出现错误时,页面会重定向到所需的闪现消息):
$objValidation = FormValidator::isValidData($post);
if($objValidation->bolHasError)
{
$app->flash('objValidation', serialize($objValidation));
$app->flash('selectedData', $post);
return $app->redirect('/app/edit/form/components/');
}
但是如果我开始使用 try 块,如下所示,则 flash 消息不会存储在 $_SESSION 中(甚至不会存储在模板中的 {{ flash }} 中):
try {
$objValidation = FormValidator::isValidData($post);
if($objValidation->bolHasError)
{
$app->flash('objValidation', serialize($objValidation));
$app->flash('selectedData', $post);
return $app->redirect('/app/edit/form/components/');
}
# some other stuff processed here...
}
catch(Exception $e) {
# do something
}
P.S.: 会话以 PHP 本机方式存储 ( session_start() ).
以这种方式使用即显消息有任何范围限制吗?
我发现 try
块创建了一个 "isolated scope"。因此,我尝试在重定向之前放置一个 return false
以测试下一页是否会显示闪现消息。最后flash message存储在$_SESSION变量中(当然没有执行重定向,但至少我发现问题与try
范围有关)。
然后,我找到的解决方案是引发异常并在 catch 块内进行重定向。像这样:
$objValidation = FormValidator::isValidData($post);
if($objValidation->bolHasError)
{
throw new Exception('validation_error');
}
然后将错误捕获到catch块中:
catch(Exception $e)
{
if($e->getMessage() == 'validation_error')
{
$app->flash('objValidation', serialize($objValidation));
$app->flash('formData', $post);
return $app->redirect('/api/form/change/components/');
}
}
这样我就可以将 flash 消息放入模板中。