Silex 在中间件中保存变量并在控制器上访问它
Silex saving variable on middleware and acces it on controller
我需要从之前在 silex 上获取一个变量,并在中间件之外访问它:
$app->before(function (Request $request, Application $app) {
if ($request->getMethod() !== "OPTIONS") {
$bearer = $request->headers->get('Authorization');
$app["bearer"] = $bearer;
echo $app["bearer"]; // Works and display value
}
return null;
}, Application::EARLY_EVENT);
echo $app["bearer"]; // Don't works, Display "" :'(
谢谢
您(未)在真正定义之前期望该值。你这样做:
$app->before(function (Request $request, Application $app) {
if ($request->getMethod() !== "OPTIONS") {
$app["bearer"] = $request->headers->get('Authorization');
}
return null;
}, Application::EARLY_EVENT);
echo $app["bearer"]; // WRONG!
请注意,您定义了前中间件并立即检查 bearer 值。但是在这一步中间件还没有执行!一旦你 运行 $app->run();
,中间件就会在任何控制器之前执行。因此,在您的控制器中,您可以检查该值,但不能在执行 $app->run()
方法(触发中间件)之前检查。你可以试试,例如:
$app->before(function (Request $request, Application $app) {
if ($request->getMethod() !== "OPTIONS") {
$app["bearer"] = $request->headers->get('Authorization');
}
return null;
}, Application::EARLY_EVENT);
$app->get('/some-route', function(Aplication $app) {
echo $app["bearer"]; // Right!
});
我需要从之前在 silex 上获取一个变量,并在中间件之外访问它:
$app->before(function (Request $request, Application $app) {
if ($request->getMethod() !== "OPTIONS") {
$bearer = $request->headers->get('Authorization');
$app["bearer"] = $bearer;
echo $app["bearer"]; // Works and display value
}
return null;
}, Application::EARLY_EVENT);
echo $app["bearer"]; // Don't works, Display "" :'(
谢谢
您(未)在真正定义之前期望该值。你这样做:
$app->before(function (Request $request, Application $app) {
if ($request->getMethod() !== "OPTIONS") {
$app["bearer"] = $request->headers->get('Authorization');
}
return null;
}, Application::EARLY_EVENT);
echo $app["bearer"]; // WRONG!
请注意,您定义了前中间件并立即检查 bearer 值。但是在这一步中间件还没有执行!一旦你 运行 $app->run();
,中间件就会在任何控制器之前执行。因此,在您的控制器中,您可以检查该值,但不能在执行 $app->run()
方法(触发中间件)之前检查。你可以试试,例如:
$app->before(function (Request $request, Application $app) {
if ($request->getMethod() !== "OPTIONS") {
$app["bearer"] = $request->headers->get('Authorization');
}
return null;
}, Application::EARLY_EVENT);
$app->get('/some-route', function(Aplication $app) {
echo $app["bearer"]; // Right!
});