2015-12-21 114 views
2

我想将数据库变量传递给中间件功能。然而,我发现了以下错误:如何将变量传递给中间件功能? [SLIM框架]

Fatal error: Call to undefined method Slim\Route::prepare() in /Applications/MAMP/htdocs/website/models/feedback.php on line 11 with the code: "$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"); 

你能帮我么?

回答

0

您不能将变量直接传递给中间件。 随着你的呼叫,你用这个变量调用一个空函数。 但是你可以将变量嵌入到你的$ app中,并从中间件中获取它。

+0

如果您可以在$ app中显示嵌套变量的示例以及如何在中间件内访问这些变量,那么您的答案会更有帮助。 –

2

你应该可以用anonymus函数做到这一点。

您的代码看起来是这样的:

$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