将额外参数传递给 silex 错误处理程序回调函数

Pass extra parameters to silex error handler callback function

我正在使用 Silex 和 Twig 构建一个应用程序,我在其中以这种方式(标准方式)定义了我的路由处理程序:

//routes.php
$app->get('/pageA',function () use($app){
  //Display something
});

$app->get('/pageB',function () use($app){
  //Display something
});

$app->post('/pageB',function (Request $req) use($app){
  //Process something
});

然后我设置了一个错误处理程序来管理路由处理程序中可能抛出的错误,如下所示:

//routes.php
$app->post('/pageB',function (Request $req) use($app){
  //Do something, but an error occurs..
  $app->abort(404,"Page not found");
});

//errors.php
$app->error(function (\Exception $e, $code) use($app) {
  switch($code){
    case 404:
      return $app['twig']->render('404.twig',array('error'=>$e->getMessage()));
    //Other error codes...
    default:
      //return something
  }
});

我想做的是将路由处理程序的额外参数传递给错误处理程序的回调函数,如下所示:

//routes.php
$app->post('/pageB',function (Request $req) use($app){
  //Do something, but an error occurs..
  $app->abort(404,"Page not found","My extra parameter");
});

//errors.php
$app->error(function (\Exception $e, $code,$extra_param=null) use($app) {
  if(isset($extra_param))
    //Process the error in a different way
  else{ //Standard way
    switch($code){
      case 404:
        return $app['twig']->render('404.twig',array('error'=>$e->getMessage()));
      //Other error codes...
      default:
        //return something
    }
 }
});

这可以做到吗?

这可能不是最优雅的解决方案,但您可以将数组添加到 $app

$app['my_param_bag'] = array();

$app->get('/pageB', function(Request $request) use ($app) {
  $app['my_param_bag'] = array('foo', 'bar', 'baz');
  $app->abort(404, "Page not found");
});

$app->error(function (\Exception $e, $code) use($app) {
  error_log(print_r($app['my_param_bag'],1).' '.__FILE__.' '.__LINE__,0);

  if(!empty($app['my_param_bag'])) {
    // do something with the params
  }
  else{ 
    switch($code){
      case 404:
        return $app['twig']->render('404.html.twig',array('error'=>$e->getMessage()));
      default:
    }
  }
});

我不确定您是如何设置应用程序的,但对我来说,我能够在配置文件中添加这个空数组。