Kev*_*ell 9 api routes request laravel laravel-4
我正在编写一个简单的API,并在此API之上构建一个简单的Web应用程序.
因为我想直接"使用我自己的API",所以我首先使用Googled在StackOverflow上找到了这个答案,它完美地回答了我的初始问题:使用我自己的Laravel API
现在,这很好用,我可以通过以下方式访问我的API:
$request = Request::create('/api/cars/'.$id, 'GET');
$instance = json_decode(Route::dispatch($request)->getContent());
Run Code Online (Sandbox Code Playgroud)
这很棒!但是,我的API还允许您向GET查询字符串添加可选字段参数,以指定应返回的特定属性,例如:
http://cars.com/api/cars/1?fields=id,color
Run Code Online (Sandbox Code Playgroud)
现在,我在API中实际处理此问题的方式与此类似:
public function show(Car $car)
{
if(Input::has('fields'))
{
//Here I do some logic and basically return only fields requested
....
...
}
Run Code Online (Sandbox Code Playgroud)
我会假设我可以做类似于之前的查询字符串无参数方法,类似这样的事情:
$request = Request::create('/api/cars/' . $id . '?fields=id,color', 'GET');
$instance = json_decode(Route::dispatch($request)->getContent());
Run Code Online (Sandbox Code Playgroud)
但是,它似乎并非如此.简而言之,在单步执行代码之后,似乎Request正确创建了对象(并且它正确地拉出了fields参数并为其分配了id,颜色),并且Route似乎被调度好了,但是在我的API控制器本身内我不知道如何访问field参数.使用Input::get('fields')(这是我用于"普通"请求的东西)什么都不返回,我很确定这是因为静态Input引用或确定了进入的初始请求,而不是我从"内部"手动调度的新请求.应用本身.
所以,我的问题是我应该怎么做呢?难道我做错了什么?理想情况下,我想避免在我的API控制器中做任何丑陋或特殊的事情,我希望能够将Input :: get用于内部调度的请求,而不必进行第二次检查等.
Jas*_*wis 18
你是正确的,因为使用Input实际上是引用当前请求而不是新创建的请求.您的输入将在您实例化的请求实例本身上可用Request::create().
如果您正在使用(因为您应该)Illuminate\Http\Request实例化您的请求,那么您可以使用$request->input('key')或$request->query('key')从查询字符串中获取参数.
现在,问题在于您可能没有Illuminate\Http\Request在路线中使用您的实例.这里的解决方案(以便您可以继续使用Input外观)是物理地替换当前请求的输入,然后将其切换回来.
// Store the original input of the request and then replace the input with your request instances input.
$originalInput = Request::input();
Request::replace($request->input());
// Dispatch your request instance with the router.
$response = Route::dispatch($request);
// Replace the input again with the original request input.
Request::replace($originalInput);
Run Code Online (Sandbox Code Playgroud)
这应该有效(理论上),您仍然可以在发出内部API请求之前和之后使用原始请求输入.
| 归档时间: |
|
| 查看次数: |
37918 次 |
| 最近记录: |