Monday, February 29, 2016

Building a Hacker News Reader with Lumen

In this tutorial, we’re going to build a reader for Hacker News. We will be using the Hacker News API and the Lumen framework to implement this.

The final output looks something like this:

Working Hacker News Reader

If you’re excited, let’s go ahead and jump right into it.

Installing and Configuring Lumen

The first thing that you need to do is to install Lumen. You can do so with the following command:

composer create-project laravel/lumen hnreader --prefer-dist

Create an .env file with the contents:

APP_DEBUG=true

APP_TITLE=HnReader

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=hnreader
DB_USERNAME=homestead
DB_PASSWORD=secret

APP_DEBUG allows us to turn on debugging in Lumen so that we can see the errors in the app. And the DB_* is for the database configuration. We will be using the MySQL database for storing the items that we will be getting from the Hacker News API. This way, we won’t need to make a separate HTTP request every time a user accesses the app. You will probably just leave the values for DB_CONNECTION, DB_HOST, DB_PORT as they are if you’re using Homestead Improved. Of course, we need to create the database, too.

mysql -u homestead -psecret
CREATE DATABASE hnreader;

Next, let’s open the bootstrap/app.php file and uncomment the following line:

Dotenv::load(__DIR__.'/../');

This specific line loads the configuration options from the .env file created earlier.

Also uncomment the following line so that you can use facades such as DB:

$app->withFacades();

Database

For this app, we’re only going to need one table for storing the items that we’ve fetched from the API. You can create the table by creating a new migration with the following command:

php artisan make:migration create_items_table

That will create a new migration in the database/migrations directory. Open the file and update the contents of the up and down method to the following:

public function up()
{
    Schema::create('items', function(Blueprint $table){
        $table->integer('id')->primary();
        $table->string('title');
        $table->text('description');
        $table->string('username');
        $table->char('item_type', 20);
        $table->string('url');
        $table->integer('time_stamp');
        $table->integer('score');
        $table->boolean('is_top');
        $table->boolean('is_show');
        $table->boolean('is_ask');
        $table->boolean('is_job');
        $table->boolean('is_new');
    });
}

public function down()
{
    Schema::drop('items');
}

What the up method does is create the items table.

Continue reading %Building a Hacker News Reader with Lumen%


by Wern Ancheta via SitePoint

No comments:

Post a Comment