编辑:请参阅下文了解我当前的问题。顶部是我已经解决但有些相关的先前问题
我需要在它实际到达那里之前修改传递给我的控制器的输入值。我正在构建一个 Web 应用程序,我希望它能够支持多种请求输入类型(最初是 JSON 和 XML)。我希望能够在输入进入我的休息控制器之前捕获输入,并将其修改为适当的 StdClass 对象。
在我的一生中,我无法弄清楚如何拦截和修改该输入。帮助?
例如,我希望能够拥有这样的过滤器:
Route::filter('json', function()
{
//modify input here into common PHP object format
});
Route::filter('xml', function()
{
//modify input here into common PHP object format
});
Route::filter('other', function()
{
//modify input here into common PHP object format
});
Route::when('*.json', 'json'); //Any route with '.json' appended uses json filter
Route::when('*.xml', 'xml'); //Any route with '.json' appended uses json filter
Route::when('*.other', 'other'); //Any route with '.json' appended uses json filter
现在我只是Input::isJson()
在我的控制器函数中进行检查,然后是下面的代码 - 请注意,这有点简化了我的代码。
$data = Input::all();
$objs = array();
foreach($data as $key => $content)
{
$objs[$key] = json_decode($content);
}
编辑:我实际上已经解决了这个问题,但现在有另一个问题。这是我解决它的方法:
Route::filter('json', function()
{
$new_input = array();
if (Input::isJson())
{
foreach(Input::all() as $key => $content)
{
//Do any input modification needed here
//Save it in $new_input
}
Input::replace($new_input);
}
else
{
return "Input provided was not JSON";
}
});
Route::when('*.json', 'json'); //Any route with '.json' appended uses json filter
我现在遇到的问题是:Router 在过滤器之后尝试去的路径,包含.json
来自输入 URI。我见过的解决此问题的唯一选择是替换Input::replace($new_input)
为
$new_path = str_replace('.json', '', Request::path());
Redirect::to($new_path)->withInput($new_input);
然而,这会导致 2 个问题。首先,我无法通过请求重定向它POST
- 它始终是一个GET
请求。其次,传入的数据正在被刷新到会话中——我宁愿通过Input
类使用它,就像使用Input::replace()
.
关于如何解决这个问题的任何建议?