Wern Ancheta

Adventures in Web Development.

Getting Started With Lumen

| Comments

In this tutorial I’ll walk you through Lumen, a lightweight framework from the same guys that made Laravel. Lumen is basically a lighter version of Laravel.

Installation

You can install Lumen by using composer’s create-project command. Simply execute the following command on your preferred install directory:

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

Once the installation is done, you can navigate to the lumen directory and execute the following:

1
php artisan serve --port=7771

This will serve the project on port 7771 of your localhost:

1
http://localhost:7771/

If the installation completed successfully, you will be greeted by the default screen.

Using Third Party Libraries

You can use third party libraries with Lumen by adding the package that you want to install in the composer.json file. Here’s an example:

1
2
3
4
5
6
"require": {
    "laravel/lumen-framework": "5.0.*",
    "vlucas/phpdotenv": "~1.0",
    "elasticsearch/elasticsearch": "~1.0",
    "guzzlehttp/guzzle": "~5.0"
},

Note that the lumen-framework and phpdotenv is there by default since those are needed in order for Lumen to work. In the above file we have added elasticsearch and guzzlehttp as our dependencies.

You can then make Lumen aware of these libraries by initializing them on the files where you want to use them:

1
2
3
4
<?php
$http_client = new \GuzzleHttp\Client();
$es_client = new \Elasticsearch\Client();
?>

Configuration

By default Lumen is pretty bare-bones. Which means that we need to do some configuration if we want to use some of the features that we usually have in Laravel. In Lumen you can enable most of those functionalities by editing the bootstrap/app.php file.

Enabling Sessions

You can enable sessions by removing the comment on the middleware which says Illuminate\Session\Middleware\StartSession:

1
2
3
4
5
6
7
8
9
<?php
$app->middleware([
    //'Illuminate\Cookie\Middleware\EncryptCookies',
    //'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
    'Illuminate\Session\Middleware\StartSession',
    //'Illuminate\View\Middleware\ShareErrorsFromSession',
    //'Laravel\Lumen\Http\Middleware\VerifyCsrfToken',
]);
?>

Enabling Eloquent

If you need to use Eloquent in your app, you can enable it by removing the comment on the following lines:

1
2
3
4
<?php
$app->withFacades();
$app->withEloquent();
?>

Dot Env

Lumen uses a .env file to set the environment configuration for the project. This way you can have a different .env file on your local machine and on your server. And then you can set git to ignore this file so that it doesn’t get pushed along to the server when you deploy your changes. Here’s how the .env file looks by default:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
APP_ENV=local
APP_DEBUG=false
APP_KEY=SomeRandomKey!!!

APP_LOCALE=en
APP_FALLBACK_LOCALE=en

DB_CONNECTION=mysql
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

CACHE_DRIVER=memcached
SESSION_DRIVER=memcached
QUEUE_DRIVER=database

As you can see from the file above, you can set the name of the environment by setting the value for APP_ENV. The next one right after that is the APP_DEBUG configuration which is set to false by default. If you’re developing you need to set this to true so you have an idea what’s wrong when testing your app. Next is APP_KEY which is basically used as a salt for sessions. You can use a random string generator for this. APP_LOCALE and APP_FALLBACK_LOCALE are used for setting the language of your app. This is set to english by default. Next are the database configuration. Anything which starts with DB_ is the database configuration. By default its expecting to connect to a mysql database. DB_HOST is the host in which the database is running. DB_DATABASE is the name of the database you want to connect to. DB_USERNAME is the username of the user you want to use for logging in. DB_PASSWORD is the password of the user. After the database configuration are the cache, session and queue driver configuration. The cache and session driver are using memcached by default so you’ll have to install memcached if you’re using caching and session functionalities. If memcached is not present in the system then it will just fallback to the default one which is the filesystem.

Note that before you can use the .env file, you need to uncomment the following line in your bootstrap/app.php file. This way Lumen will load the .env file on the root of your project.

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

Directory Structure

Here’s what the default directory structure looks like in Lumen. The one’s with * are files:

1
2
3
4
5
6
7
8
9
10
11
app
bootstrap
database
public
resources
storage
tests
vendor
*artisan
*server.php
*composer.json

The app directory is where you will usually work with. This is where the routes, controllers and middlewares are stored.

The bootstrap directory only contains one file by default, the app.php file. As you have seen earlier, its where you can configure and add new functionality to Lumen.

The database directory is where the database migrations and seeders are stored. You use migrations to easily jump from previous database version to another. Its like version control for your database. Seeds on the other hand are used to populate the database with dummy data so that you can easily test your app without having to enter the information through the app itself.

The public directory is where your public assets are stored. Things like css, javascript and images are stored in this directory.

The resources directory is where you store the views that you use for your app.

The storage directory is where logs, sessions and cache files are stored.

The tests directory is where you put your test files.

The vendor directory is where the dependencies of your app is stored. This is where composer installs the packages that you specified in your composer.json file.

The artisan file is the file that is used for command line tasks for your project. We have used it earlier when we served the project. The artisan file can also be used to create migrations, seeds and other tasks that you usually perform through the command line.

The server.php file is used for serving the files without the use of a web server like Apache.

Routes

Routes are stored in the app/Http/routes.php file. Here’s how you would declare a route in Lumen:

1
2
3
4
5
<?php
$app->get('/', functionn(){
    return 'Hello World!';
});
?>

If you want to use a controller method to handle the response for a specific route then you can do something like this:

1
2
3
<?php
$app->get('/', 'App\Http\Controllers\HomeController@index');
?>

Then you would need to create a HomeController controller and then declare an index method. This will then be used to return a response.

Controllers

Controllers are stored in the app/Http/Controllers directory. Needless to say, the convention is one file per controller. Otherwise it would be really confusing. Here’s the basic structure of a controller:

1
2
3
4
5
6
7
8
9
10
<?php
<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller as BaseController;

class HomeController extends BaseController{

}
?>

Note that we need to use Illuminate\Http\Request to be able to access the request parameters for each request. We also need to use Laravel\Lumen\Routing\Controller. This allows us to extend the functionality of the base controller class.

Views

Lumen still comes with blade templating, all you have to do is create your views under the resources/views directory and then use .blade.php as the file extension. Though unlike Laravel you return views this way:

1
2
3
4
5
<?php
public function index(){
    return view('index');
}
?>

In the example above were returning the index view that is stored in the root of the resources/views directory. If we want to return some data, then we can pass it by supplying the array or object that we want to pass:

1
2
3
4
5
6
7
8
<?php
$array = array(
    'name' => 'Ash Ketchum',
    'pokemon' => 'Pikachu'
);

return view('index', $array);
?>

It can then be rendered in the view like so:

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
    Hi my name is , my Pokemon is 
</body>
</html>

Database

When working with a database you first need to edit the database configuration values in your .env file.

Migrations

Once that’s done you can try if your app can connect to your database by creating a database migration. You can do that by executing the following command in the root directory of your project:

1
php artisan migrate:install

The command above creates the migration table in your database. The migration table is used by Lumen to keep track of which database migrations are currently applied to your database. If that worked without problem and you see that a migrations table has been created in your database then you’re good to go.

Next you can create a new table by using the make:migration command. This takes up the action that you wish to do. In this case we want to create a new table so we use --create and then supply the name of the table as the value. The second argument will be the name that will be assigned to the migration class.

1
php artisan make:migration --create=users create_users_table

The command above will create a file which looks like the following in the database/migrations directory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php

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

class CreateUsersTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function(Blueprint $table)
        {
            $table->increments('id');
            $table->timestamps();
        });
    }

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

}
?>

The only thing that we need to edit here are the method calls inside the up method:

1
2
3
4
5
6
7
8
<?php
Schema::create('users', function(Blueprint $table)
{
    $table->increments('id');
    $table->string('name');
    $table->integer('age');
});
?>

That is where we specify the fields that we need to add to the users table.

Once you’re happy with the file, save it and then run:

1
php artisan migrate

This will create the table in your database and add a new row to the migrations table.

Seeds

You can create a new database seeder file inside the database/seeds directory. Here’s the usual structure of a seeder:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php

use Illuminate\Database\Seeder;

class UserTableSeeder extends Seeder
{
    public function run()
    {

        //seeding code       

    }
}
?>

Inside the run method is the actual seeding code. We can use your usual Laravel flavored database queries inside of it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
DB::table('users')->insert(
    array(
        'name' => 'Ash Ketchum',
        'age' => 10
    )
);

 DB::table('users')->insert(
    array(
        'name' => 'Brock',
        'age' => 15
    )
);

DB::table('users')->insert(
    array(
        'name' => 'Misty',
        'age' => 12
    )
);
?>

Once that’s done, save the file and open up the DatabaseSeeder.php file. This is where you specify which seeders you want to execute whenever you execute the php artisan db:seed command. In this case we want to add the UserTableSeeder:

1
$this->call('UserTableSeeder');

Before we execute the php artisan db:seed command we will first need to reload the autoloaded files by executing the composer dump-autoload command. We need to do this every time we add a new seeder so that Lumen will take care of loading the seeder.

Getting Data

From your routes file you can now try fetching the users that we’ve added:

1
2
3
4
5
6
7
<?php
$app->get('/db-testing', function(){

    $users = DB::table('users')->get();
    return $users;
});
?>

With Lumen you can use the query builder, basic queries and even Eloquent. So if you already know how to work with those then you’re good to go.

Conclusion

That’s it! In this tutorial I’ve walked you through Lumen and how you can install, configure and work with the different functionalities that it can offer.

Comments