CREATE MICRO-SERVICES USING LUMEN FRAMEWORK: PART I

in utopian-io •  7 years ago  (edited)

Untitled-1.jpg

CREATE MICRO-SERVICES USING LUMEN FRAMEWORK: PART I

What Will I Learn?

In this part, you will learn the following

  • What is a Micro-service

  • Why you need to make use of micro-services

  • What is Lumen

  • How to install Lumen

  • Setup Lumen development environment

  • Setup database environment

  • Install Postman on Google Chrome

Requirements

For this tutorial, you will need the following

  • A PC/laptop with any Operating system such as Linux, Mac OSX, Windows OS

  • Internet Connection

  • PHP version >= 7.1

  • Composer version >= 1.4.1

  • Google Chrome browser

Difficulty

  • Intermediate

Tutorial Contents

In this series, you will set up the lumen development environment to enable you get started.

Before then, I will explain some terminologies for you to understand what you are diving into.

What is a micro-service?

A micro-service is a variant of the service-oriented architecture (SOA). It is an approach to developing a single application as a suite of small parts - services communicated through APIs.

Why you need to make use of micro-services

  1. Scalability
  2. Protect from failure

What is Lumen?

Lumen is a stunningly fast micro-framework by laravel that is used for the development of lighting fast micro-services and APIs.

Why we use Lumen in building micro-services.

  1. Micro-services need to possess the ability to read and write to a database, must be secured, built with the so-called message driven approach, and have the ability to provide reports.
  2. Lumen utilizes all benefits of laravel framework including security, easy database configuration, queue service configuration and so on.

Installing Lumen

To have lumen up and running on your system, you need to make sure you server meets the following requirements:

  1. PHP >= 7.1
  2. OpenSSL PHP Extension
  3. PDO PHP Extension
  4. Mbstring PHP Extension

Make sure the above listed extensions are set on your server.

extension.png

Lumen utilizes composer to manage its dependencies so before installing lumen, make sure you have composer already installed. You can download composer here

You are going to install lumen via lumen installer

First, download the Lumen installer using Composer: Open your command prompt window and type in the following code

composer global require "laravel/lumen-installer"

You should see this in your CMD window

lumen install.png

Once lumen is installed, you can create a new lumen project folder in any directory of your choice. Let's call your project "eblog".

Type the following code:

lumen new eblog

And wait while your new eblog project is been created.

install lumen.png

Once your project folder is created completely, you can serve your project locally by using the following command

php -S localhost:8000 -t public

Open your google chrome browser and type http://localhost:8000/ to confirm your installation is properly done and if it was, you should see this page:

If you see this page, the your install was done perfectly well. So let's move to the next step.
welcome page.png

Setup lumen development environment.

The next thing you should do after installing Lumen is set your application key to a random string. The application key is a set of random key that is unique to your app. The key can be set in the .env environment file. Duplicate the .env.example file and rename to .env.

Generate a random key by typing random characters into the APP_KEY variable. This string should be 32 characters long

APP_ENV=local
APP_DEBUG=true
APP_KEY= jdgjdskdsjjkjdjdhghgjdhgjdsjgsmmledhqeevmfporiuevbdk
APP_TIMEZONE=UTC

LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

CACHE_DRIVER=file
QUEUE_DRIVER=sync

Note: If the application key is not set, your user encrypted data will not be secure!

Setup database environment

Open your database management system, i'm currently making use of HeidiSQL version 9.4.0.5125

There are other options like phpmyadmin which is more preferable.

Create a new database called "blog" and save.

new database on laragon2.png

So next, you need to configure your lumen app to make use of the blog database.

Go to .env file, and set the following variable:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=

So your .env file should look like this:

env.png

Remember, lumen is a stripped down version of laravel so this means that some settings were disabled or not even implemented at all, so you have to enable the settings we require.

So in your bootstrap/app.php, uncomment the following lines of codes:

$app->withFacades();

$app->withEloquent();

Install Postman on google chrome

Postman is a REST Client that runs as an application inside the Chrome browser. It is very useful for interfacing with REST APIs.

Go to : https://chrome.google.com/webstore/search/postman?_category=extensions

Click on Add to chrome on postman interceptor

postnman.png

So you are now ready to start building your first micro-service.

You are creating a blog website that makes use of the service-oriented architecture (SOA). So you can have a micro-service for posts, another one that takes care of comments, and so on depending on how robust your website is.

The next thing you have to do is to create a "post" table for your posts. In your CMD use the following code

php artisan make:migration create_table_posts --create=posts

Create Post Table.png

This creates a migration file containing your post table. The migration file can be accessed via database\migration\

Now you need to add fields to your post table. Go to database\migration\XXXX_create_table_posts.php and add the following code to your schema

$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('views')->nullable();
$table->timestamps();


id : Identity column that identifies each record as a unique entry

title: This is the title of the post

body: This is the body of the post

views: This is the number of times a post was viewed

timestamp: This gives the time which the post was created.

So your XXXX_create_table_posts.php should look this way.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTablePosts extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->integer('views')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Next, you need to create the post table in your database. So in CMD, type the

php artisan migrate

you should get the following feedback to show migration was succesful

Migration table created successfully. Migrating: 2018_03_22_084119_create_table_posts Migrated: 2018_03_22_084119_create_table_posts .

Next, you will create a model for posts. Lumen uses the MVC architecture which is Model View Controller.

Model corresponds to all the data-related logic that the user works with. Model are mostly used to interact with the database using Eloquent ORM. The Model is concerned with the data of the application.

View is used for all the UI logic of the application. Whatever the user sees on your application should be taken care of by the view. Every thing on the application the user interacts with like, textbox, dropdown, tables, data displayed is handled by the view.

Controller acts as the middle man between the Model and the View to process all business logic.

In laravel, you could use the command php artisan make:model Post but like i said lumen is a stripped down version of laravel and some commands are not implemented. So you have to manually create a model. Go to app directory and create a new file Post.php then copy the following lines of codes in the Post.php file.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class Post extends Model
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'body', 'views'
    ];


}


There you have your Post model in the app\Post.php

Next, you have to create a controller that will handle the business logic of the application and like model it can be created manually. So go to app\Http\Controller , then create a new file called PostsController.php and paste the following code in the file

<?php

namespace App\Http\Controllers;

use App\Post;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class PostsController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    //

    
}

So you can create functions to execute individual tasks when called. For the blog website, you will need a

  • createPost function : To create a new post
  • updatePost function : To update an existing post
  • deletePost function: To delete a post
  • allPost function: To fetch all existing posts

For now, we will work with these for the posts micro-service, when developing other micro-services like comment micro-service, etc. you will create more functions specific to their micro-services.

Paste the following codes in thePostsController.php file to create the functions.

// Get all existing posts
    public function allPost ()
    {

       $post = Post::all();
       return response()->json($post);

    }

    // Create new post
    public function createPost (Request $request)
    {

        $post = Post::create($request->all());
        return response()->json($post);

    }

    // Update an existing post
    public function updatePost (Request $request, $id)
    {

       $post = Post::find($id);
       $post->title = $request->input('title');
       $post->body = $request->input('body');
       $post-save();
       return response()->json($post);

    }

    // Delete an existing post
    public function deletePost ($id)
    {

       $post = Post::find($id);
       $post-delete();
       return response()->json("Post had been successfully deleted");

    }

Let me explain the following lines code

$post = Post::all(); : This gets the post model which you called at the top of your file use App\Post; and fetches all records in the posts database. all() is a helper function preconfigure to select all records from a database. Same as SELECT * FROM.

return response()->json($post) means instead of getting back your resource as an object, the function should return a JSON.

Post::create($request->all()); : $request->all() gets all values of the form, and passes it to the create() function. The create() creates a new record for the Post model in the Post table.

$post = Post::find($id); : This finds a particular post with the given $id

$post->title = $request->input('title'); $post->body = $request->input('body'); : Gets title and body value of the form

$post-save(); : Updates the post.

So you have successfully created the functions, now lets test to see if its working. Before we do so, you need to create endpoints that we call these functions. So in the routes\web.php directory, add the following codes

$app->get('/post/all' , 'PostsController@allPost');

$app->post('/post/create' , 'PostsController@createPost');

$app->delete('/post/delete' , 'PostsController@deletePost');

$app->post('/post/update' , 'PostsController@updatePost');
  

Next, lets create our first post.

Be certain that your serve is running, if not go to CMD and cd to project folder, then use the command php -S localhost:8000 -t public

Go to google chrome apps, open postman, select Request

new req.png

Then fill in the request name, create a new collection called eblog and save

create folde.png

Next, to call the endpoint,

  • Add http://localhost:8000/post/create in the Enter request URL field.

  • Select the http method to POST

  • Click on Body and add the following

    key value

    title My first post

    body Test

  • The click on send. You should get the required response as below

response.png

If you get this then it was successful. Create as many posts as possible so we can fetch all.

Next lets select all posts in the post table.

  • Set http method to GET
  • Add http://localhost:8000/post/all in the Enter request URL field.
  • Click on send

You should get a list of all existing post as JSON.

all.png

If you see this, then you have successfully created your first micro-services.

You can test other endpoints. next we will create another micro-service for comment.

I hope this was helpful.

Thanks



Posted on Utopian.io - Rewarding Open Source Contributors

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

You have a minor spelling mistake in the following sentence:

you should get the following feedback to show migration was succesful.
it should be successful instead of succesful.

Thank you for the contribution. It has been approved.

  • it seems lumen-framework is quite similar to the ThinkPHP framework

You can contact us on Discord.
[utopian-moderator]

Yea @cha0s0000
But there's still a remarkable difference in syntax.

Hey @profchydon I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x