如何将变量传递给中间件函数? [SLIM框架]

时间:2015-12-21 15:50:04

标签: php frameworks routes slim middleware

我试图将数据库变量传递给中间件函数。但是我收到以下错误:

  

致命错误:调用未定义的方法Slim \ Route :: prepare()in   第11行的/Applications/MAMP/htdocs/website/models/feedback.php   代码:" $ results = $ db-> prepare(" INSERT INTO ..."

代码如下:

function newsletter(){

  $app = \Slim\Slim::getInstance();
  $route = $app->request->post('route');
  $email = $app->request->post('email_subscribe');
  $subscribe = $app->request->post("subscribe");
  $oFeedback = new Feedback();
  if(!empty($email)) {
    $cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
    $type="newsletter";
    $oFeedback->saveFeedback($db,NULL,$cleanEmail,NULL,$type);
  }
}

我正在这样的路线中调用中间件功能:

$app->post('/triparticle', 'newsletter', function() use($app, $db){
})->name("triparticle_post");

你能帮帮我吗?

2 个答案:

答案 0 :(得分:2)

您应该可以使用匿名函数执行此操作。

您的代码可能如下所示:

$newsletter = function ($db){
    return function () use ($db){

      $app = \Slim\Slim::getInstance();
      $route = $app->request->post('route');
      $email = $app->request->post('email_subscribe');
      $subscribe = $app->request->post("subscribe");
      $oFeedback = new Feedback();
      if(!empty($email)) {
        $cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
        $type="newsletter";
        $oFeedback->saveFeedback($db,NULL,$cleanEmail,NULL,$type);
      }
    };
};

$app->post('/triparticle', $newsletter($db), function(){
})->name("triparticle_post");

这描述为here

答案 1 :(得分:0)

您无法将vars直接传递给中间件。 通过您的呼叫,您可以使用该变量调用空函数。 但是你可以将vars嵌入你的$ app并从中间件中获取它。