simhamed
simhamed

Reputation: 95

Slim Framework : Call internal API REST

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...

Thanks in advance!

Upvotes: 0

Views: 975

Answers (2)

simhamed
simhamed

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

odan
odan

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

Related Questions