1

我正在使用 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 实现的?

4

1 回答 1

-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;
}
}
于 2018-06-05T10:26:51.367 回答