如何在Lumen中间件响应之前获取路由参数?

时间:2017-09-01 20:21:59

标签: lumen lumen-5.4

我正在使用Lumen 5.4,我需要获取一个路由参数并将其处理到每个请求,因此我创建了以下中间件:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Config;

class StoreMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {        
        $store = $request->route()[2]['store'];

        $map = Config::get("mapping.stores");
        if(isset($map[$store])){
            Config::set(["data.stores" => $map[$store]]);
        } else {
            return response()->json([
                'status' => 'error',
                'message' => "Invalid store '$store'",
                'valid_store_list' => array_keys($map)],404);
        }

        $response = $next($request);

        return $response;
    }
}

问题是$ store变量只有在我把$ next($ request)放在它之前才设置,但这意味着我无法通过我的控制器上的Config :: set获取数据集,因为控制器将现在在中间件之前处理。

换句话说,我想要实现的是处理网址:

  • domain.com/store1/costumers /
  • domain.com/store1/sellers /
  • domain.com/store2/costumers
  • domain.com/store2/sellers /

这是我的web.php文件(还没有卖家):

$app->group(['prefix' => '/{store}/costumers/', 'namespace' => '\App\Http\Controllers'], function ($app) {
    $app->get('/','CostumersController@index'); //get all the routes    
    $app->post('/','CostumersController@store'); //store single route
    $app->get('/{id}/', 'CostumersController@show'); //get single route
    $app->put('/{id}/','CostumersController@update'); //update single route
    $app->delete('/{id}/','CostumersController@destroy'); //delete single route
});

我被困在这一段时间内无法找到解决方案。我做错了什么,或者这是不可能用Lumen实现的?

1 个答案:

答案 0 :(得分:-1)

编写以下代码行以获取任何路由的请求,

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;

class StoreMiddleware
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{        
    //your all requests coming from route
    $all = $request->all();

    //for any specific field or condition
    if($request->input('age') < 18){
       //return some error or handle code
    }       

    $store = $request->route()[2]['store'];

    $map = Config::get("mapping.stores");
    if(isset($map[$store])){
        Config::set(["data.stores" => $map[$store]]);
    } else {
        return response()->json([
            'status' => 'error',
            'message' => "Invalid store '$store'",
            'valid_store_list' => array_keys($map)],404);
    }

    $response = $next($request);

    return $response;
}
}