首页 > 解决方案 > PHP - 调用内部 API

问题描述

我是PHP的新手。我使用 *composer** 创建了一个 Laravel 项目。我的控制器有两个端点uploadFiletestpost

public function uploadFile(Request $request) {
    //there are more code about reading uploaded file here. Everything is OK here.

    $request = Request::create('/api/testpost', 'POST',
        [],[],[],[],'{"this is" : "my test content"}');
    return Route::dispatch($request);
}

public function testpost(Request $request){
    Log::info($request->all());

    return response()->json(["title"=>"this is the test get method"]);
}

uploadFile由 POST 操作从带有上传的 JSON 文件的表单调用。我想使用Request::create(...)Route::dispatch(...)uploadFile方法中调用testposttestpost被调用,但是请求的主体不是预期的。日志文件显示$request->all()没有返回我期望的请求正文{"this is" : "my test content"}

我的日志文件:

[2019-02-23 12:16:47] local.INFO: array (
  '_token' => 'JzQjclRD4WaTkezqLxlU48D1dM7S3X2X3hok3kr4',
  'employee_file' => 
  Illuminate\Http\UploadedFile::__set_state(array(
     'test' => false,
     'originalName' => 'test_input_file.txt',
     'mimeType' => 'text/plain',
     'error' => 0,
     'hashName' => NULL,
  )),
)

我的代码有什么问题?API 调用或请求正文检索?我知道我们可以直接调用testpost方法而不是调用 API。但是,我的最终目的是知道如何调用内部 API。

标签: phplaravel

解决方案


您不需要为此使用内部 API 调用。

如果两种方法都在同一个类中,您可以直接调用

$this->methodName($args);

并将结果直接返回给调用函数。(前提是您正在调用的方法中有 return 语句)


推荐阅读