CREATE MICRO-SERVICES USING LUMEN FRAMEWORK: PART II

in #utopian-io7 years ago (edited)

CREATE MICRO-SERVICES USING LUMEN FRAMEWORK: PART II

Untitled-1.jpg


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 create standalone services


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 the last tutorial, we explained the following:

  • What is a micro-service.
  • Why you need to make use of micro-services.
  • What is lumen.
  • Why you need lumen for building micro-services
  • How to install and set up lumen

You can find the previous tutorial here.

Remember you can have different micro-services acting as one larger system but behind the scenes it is micro-services all the way acting as loosely-coupled systems . Lets take amazon.com for example; all we see is just the website but behind the scenes amazon.com has a service for accepting orders, a service to handle wishlist, a service for authenticating credit cards and so on. All of these services are mini applications performing a single business capability. If at any time they decide to carryout upgrade, maintenance, or replace a micro-service, there's no need to bring down the whole system and rebuild, they can successfully work on the affected service while the whole system stays online.

Right now, we are building micro-services for a blog website and we can identify the business capabilities as posts, comments, discussions. We built a service to handle posts in our last tutorial and in this tutorial we will build a service to handle comments. At the later end of this series, we will develop a core system that integrates all the different micro-services we successfully built to make it a complete blog website.

So lets start building the comment-service. I will advise you checkout the first part of this tutorial here if you haven't.

First, you will install new lumen project folder and name it comment. Refer the first part of this tutorial here to see how to install a new lumen project.

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

php artisan make:migration create_table_comments --create=comments

comments.png

This creates a migration file containing your comment 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_comments.php and add the following code to your schema

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


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

post_id: This is the unique id that identifies the post been commented on

user_id: This is unique id that identifies the user making the comment

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

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

So your XXXX_create_table_comments.php should look this way.

<?php

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

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

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

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

php artisan migrate

you should get the following feedback to show migration was successful

`Migration table created successfully.

Migrating: 2018_03_26_170819_create_table_comments

Migrated: 2018_03_26_170819_create_table_comments` .

Next, you will create a model for comments. 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 Comment 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 Comment.php then copy the following lines of codes in the Comment.php file.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class Comment extends Model
{

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


}

At this stage, you should kindly return to the post-service (eblog) we built in our first tutorial and add these lines of code in Post.php

public function comments()
{
      return $this->hasMany(Comment::class);
}

public function user ()
{
      return $this->belongsTo(User::class);
}

$this->hasMany(Comment::class); - This means a post can have one or many comments. Using the helper function hasMany and injecting the comment model Comment::class tells lumen that an instance of a post can have one or many comments.

$this->belongsTo(User::class); - This means a post belongs to a User. Using the helper function belongsTo and injecting the User model User::class tells lumen that an instance of a post belongs to only one user.

Next, in the User.php of the post-service, add these lines of code

public function posts ()
{
   return $this->hasMany(Post::class);
}

$this->hasMany(Post::class); - This means a user can have one or many posts. Using the helper function hasMany and injecting the comment model Post::class tells lumen that an instance of a User can have one or many posts.

So back to your comment service, in Comment.php add this code

public function post ()
{
   return $this->belongsTo(Post::class);
}

public function user ()
{
   return $this->belongsTo(User::class);
}

I am sure you understand the interpretation of the codes as it has been explained above.

So your comment.php file should look like this

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class Comment extends Model
{

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


    public function post ()
    {
        return $this->belongsTo(Post::class);
    }

    public function user ()
    {
        return $this->belongsTo(User::class);
    }

}

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 CommentsController.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 CommentsController 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 comment service, you will need a

  • createComment function : To create a new comment
  • updateComment function : To update an existing comment on a post
  • deleteComment function: To delete a comment on a post

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

    // Create new comment
    public function createComment (Request $request)
    {

        $comment = Comment::create($request->all());
        return response()->json($comment);

    }

    // Update an existing comment
    public function updateComment  (Request $request)
    {

       $comment = Comment::find($request->input('id'));
       $comment->body = $request->input('body');
       $comment->save();
       return response()->json($comment);

    }

    // Delete an existing comment
    public function deleteComment  ($id)
    {

       $comment = Comment::find($id);
       $comment->delete();
       return response()->json("Comment has been successfully deleted");

    }

Let me explain the following lines code

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

Comment::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 Comment model on the respective 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->post('/comment/create' , 'CommentsController@createComment');

$app->delete('/comment/delete' , 'CommentsController@deleteComment');

$app->post('/comment/update' , 'CommentsController@updateComment');

Next, lets create a comment for a 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, and add to the eblog collection and save

Screenshot_1.png

Next, to call the endpoint,

  • Add http://localhost:8000/comment/create in the Enter request URL field.
  • Select the http method to POST
  • Click on Body and add the following
    key value
    user_id 1
    post_id 1
    body This is a very good post
  • The click on send. You should get the required response as below

comment done.png

Next lets update a comment in the comment table.

  • Set http method to POST
  • Add http://localhost:8000/comment/update in the Enter request URL field.
  • Click on Body and add the following
    key value
    comment_id 1
    body I just updated the body of my first comment
  • Click on send

updatecomment.png

You should get a response as JSON.

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

You can test other endpoints. In subsequent tutorials, we will build a core system to integrates all the micro-services.

Curriculum:

Tutorial 1

I hope this was helpful.

Thanks



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

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

Hey @fuzeh, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

As a follower of @followforupvotes this post has been randomly selected and upvoted! Enjoy your upvote and have a great day!

Thanks

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