Lumen Microservice Architecture

I posted a blog on implementing Microservice Architecture. Here is the link. This blog is second part of it. In first post I just explained about Microservices and proposed architecture. In this post I will give practical example of Lumen Microservice.

Microservice Using Laravel

Lumen Microservice

Lumen Microservice

Lumen Microservice

You can either install Lumen in public folder of main Laravel app or you can have different installation all together.

composer global require “laravel/lumen-installer”

After it’s installed, now lets create an API.

$router->post(‘getDetails’,’APIController@getDetails’);
Now in a controller define the API.
public function getDetails(){
      return response()->json(array(
           “key1″=>”value1”,
           “key2″=>”value2”,
           “key3″=>”value3”,
           “key4″=>”value4”,
           “key5″=>”value5”
      ));
}
Now we can call these API either through our JavaScript app as Ajax request or we can call it in Laravel app using GuzzleHttp

Benefits of GuzzleHttp as mentioned on their website

  • Simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data, etc…
  • Can send both synchronous and asynchronous requests using the same interface.
  • Uses PSR-7 interfaces for requests, responses, and streams. This allows you to utilize other PSR-7 compatible libraries with Guzzle.
  • Abstracts away the underlying HTTP transport, allowing you to write environment and transport agnostic code; i.e., no hard dependency on cURL, PHP streams, sockets, or non-blocking event loops.
  • Middleware system allows you to augment and compose client behavior.

Install GuzzleHttp

Install it using Composer.

composer require guzzlehttp/guzzle

Once installed we can use in controller by name space.

use GuzzleHttp\Client;
Now call API using this client.

$client = new Client();

$response = $client->post(‘/lumenapi/public/getDetails’, [
‘form_params’ => []
]);

$data = json_decode($response->getBody()->getContents(), true);

Here in above code if you want to pass any param in POST request, you can do so inside form_params.
Above code is for the synchronous request. We can also have async request.
$request = new Request(‘GET’,’/lumenapi/public/getDetails’);
$client->sendAsync($request)->then(function ($response) {
       $data = json_decode($response->getBody()->getContents(), true);
});
So this way we can build Lumen Microservice and consume it with Laravel app.

Leave a Reply

Your email address will not be published. Required fields are marked *