Reputation: 95
I've created API REST collections on my project that will be called both internally (in the same PHP project) and externally (from other projects)
My question is : What is the best way to consume internal API REST ?
I've created a function to mock the call this way :
// init mock
$env = Environment::mock([
'REQUEST_METHOD' => 'GET',
'REQUEST_URI' => $path,
'QUERY_STRING' => $urlParams,
'HTTP_AUTHORIZATION' => 'Bearer '.$token
]);
$req = Request::createFromEnvironment($env);
// Instantiate CandidateRoute
$app = (new $class)->get();
$app->getContainer()['request'] = $req;
// Run slim inst
ob_flush();
// Run Slim
$response = $app->run(true);
This is working, but it's still an HTTP call in the end...
Any other way to consume internally API REST ?
Is better to call through CURL instead of mocking ?
Is it OK to make many HTTP calls for API REST that are in the same project ? (I guess no)
Thanks in advance!
Upvotes: 0
Views: 975
Reputation: 95
Based on Slim documentation : http://www.slimframework.com/docs/v3/cookbook/environment.html
Mock Environment objects are only useful when writing unit tests.
This rules out using mock on production, which means I'll have to consume internal APIs using cURL. I kept my function for PHPUnit tests.
I've decided to add a callApi() function that sends GET/POST/PUT cURL requests as if the API is external, since I couldn't find any better solution... I still have a problem with the 414 Request-URI Too Long when using GET, but that will be for another topic.
Upvotes: 1
Reputation: 4960
Edit: I think the problem here is the architecture. If you put the business login into the "controllers" then it's hard to reuse this code. Instead you could put the business logic into service classes and resuse the service with different clients like the controller, the CLI or the unit tests.
Upvotes: 0