Laravel Lumen: An In-Depth Guide

By Mohit Surati Laravel, PHP 43 Views

What Is Laravel Lumen?

Lumen is a new age and stunningly fast PHP micro-framework developed by the creator of Laravel, Taylor Otwell with the aim of developing microservices & APIs that can provide support to large and complex Laravel applications.

Microservices are small and loosely-coupled components that support & enhance a core application. In a microservice architecture, you might have a scenario where several Lumen apps provide support to a Laravel application.

It’s a “micro-framework,” and that’s why you can say that Lumen is a smaller, faster and leaner version of the full stack web-application framework. Lumen gets its basis from Laravel, and therefore, you will find many components in Lumen similar to Laravel.

Lumen is suitable for projects or components that want to leverage the convenience & power of Laravel but also wants to boost up the speed of their application and for that, they’re even ready to sacrifice some configuration & flexibility that comes with Laravel.

Lumen Version History

Lumen 5.0

The very first Lumen framework, i.e., Lumen 5.0 came into the picture in 2015, and it takes its base from Laravel 5.x series of PHP components.

Lumen 5.0.4

When you’re upgrading to Lumen 5.0.4, you should make the following changes to the bootstrap/app.php file as shown in the snippet below:

$app = new Laravel\Lumen\Application(
 	realpath(__DIR__.'/../')
 );
Lumen 5.1.0

Lumen 5.1.0 upgrades the framework to utilize Laravel 5.1 components. With the release of this version features like event broadcasting, middleware parameters, and testing improvements became the part of Lumen.

Lumen 5.2.0

Lumen 5.2.0 upgrades the framework to utilize Laravel 5.2 components. In addition to that, there were some major changes to the framework as listed below:

● Only Stateless APIs
Lumen 5.2 was focused on serving stateless JSON APIs and therefore, the concept of sessions & views were eliminated from this version. If you want these features in your application, then you should utilize Laravel Development Services.

● Authentication
With sessions no longer being a part of Lumen 5.2, authentication has to be done statelessly using API tokens or headers. The user has complete control over the process in the new AuthServiceProvider that comes with Lumen 5.2

● Testing Helpers
Since there is no concept of a session in Lumen 5.2, all the testing helpers related to the form of interaction has been removed.

Lumen 5.3.0 – Lumen 5.6.0

From Lumen 5.3 to Lumen 5.6, the framework has come a long way.

Lumen Installation Process

The Lumen framework has a few system requirements which you need to fulfill to install it on your machine.

System Requirements

  • PHP >= 7.1.3
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension

However, if you’re using Laravel Homestead, i.e., a virtual machine, then you don’t need to satisfy these requirements explicitly as it’s already set up as per your needs.

From Where You Can Download Lumen?

To download lumen framework, please refer this link

Installing Lumen

One thing that you should keep in mind while installing Lumen is that it uses Composer, i.e., dependency manager for PHP to manage its dependencies. Therefore, you need to ensure that there is a Composer installed on your machine before installing Lumen.

If you’re having any trouble with the installation of Lumen, you can Hire Laravel Developer. He/She will definitely help you in this matter.

Now, there are two major ways of installing Lumen:

  • Via Lumen Installer
  • Via Composer Create-Project
Via Lumen Installer

To proceed with the first method, you need to download the Lumen Installer using the Composer. For that purpose, use the command as shown in the snippet below:

composer global require “laravel/lumen-installer”

Always make sure that you’re placing ~/.composer/vendor/bin in your PATH. It will allow your system to locate the lumen executable.

Once you install the Lumen framework on your computer, then you can use lumen new command to create an instance of Lumen in the directory specified by you. For example, lumen new ABC will create a directory named ABC which contains a fresh installation of Lumen with all the dependencies being taken care.

Via Composer Create-Project

Another way of installing Lumen is by running the Composer create-project command in the terminal as shown in the snippet below:

composer create-project –prefer-dist laravel/lumen blog

Configuration In Lumen

The configuration options for Lumen are in a .env file.

How To Access Configuration Values?

To access configuration values, you can use the global config helper function. You should use the following syntax for this purpose:

$value = config(‘filename.option’)

You can also set the default value which will return if the configuration option doesn’t exist.

To set configuration values at runtime, you should pass an array to the config helper:

config(['app.timezone' => 'America/Chicago']);
Setting Up Application Key

Once the Lumen is on your machine, the first thing you should do is set up your application key to a random string. Generally, this string is 32 characters long. The key can be in the environment (.env) file.

If your application key is not active, your data will not be secured. Therefore, you should never forget this step while working with Lumen.

Key Features Of Lumen

1. Routing

Lumen provides routing facility via Fast Route. For those who don’t know, Fast Route is a library that provides a quick implementation of regular expression based router.

You should define all the routes of your app in the routes/web.php file. The most basic route syntax is in the snippet below:

$app = new Laravel\Lumen\Application(
realpath(__DIR__.'/../') 
);

The lumen routes simply accept a URI & a closure.

Available Router Methods

Following are the list of router methods utilized for Lumen framework:

$app->get($uri, $callback);
$app->post($uri, $callback);
$app->put($uri, $callback);
$app->patch($uri, $callback);
$app->delete($uri, $callback);
$app->options($uri, $callback);
2. Authentication

As we have already discussed, Lumen does not support the concept of sessions. Therefore, all the requests authenticates via the stateless mechanism such as API tokens.

Authentication Service Provider

The AuthServiceProvider is in the app/providers consists of a single call to Auth::viaRequest. This method will accept a closure which comes into play when a request for authentication arrives. If there is no authentication is found for a request, then the method will return null.

Here’s how it works:

$this->app['auth']->viaRequest('api', function ($request) {
// Return User or null...
});
Accessing The Authenticated User

Now, to obtain the authenticated user, you can use the Auth:user() method. You can also use $request->user() method on an Illuminate\Http\Request instance as shown in the snippet below:

use Illuminate\Http\Request;
$app->get('/post/{id}', ['middleware' => 'auth', function (Request $request, $id\
) {
$user = Auth::user();
$user = $request->user();
 //
}]);
3. Authorization

Lumen provides a straightforward way to organize the authorization logic and also provides an easy way to access those resources. Authorization in Lumen is very similar to how it is in the Laravel framework. However, there are a few adjustments that you need to make while working with Lumen. So, let’s analyze that in detail.

Defining Abilities

he first major difference between Lumen and Laravel as far as authorization is in the way how abilities are defined. In Lumen, you can simply use the Gate facade in AuthServiceProvider to define abilities as shown below in the snippet:

Gate::define('update-post', function ($user, $post) {
return $user->id === $post->user_id;
});
Defining Policies

Unlike Laravel, you can’t define $policies array on the AuthServiceProvider in the Lumen framework. However, you can call the policy on the Gate facade as shown in the snippet below:

Gate::policy(Post::class, PostPolicy::class);
4. Caching

Caching mechanism for Lumen is very similar to the Laravel framework. There is a unique API for various caching systems. Your cache configuration file is located inside the .env file. The Lumen cache driver utilizes the same code as Laravel and also supports popular caching backends like Memcached & Redis.

However, using Redis with Lumen is slightly different compared to Laravel. In Lumen, before using a Redis cache, you should install the illuminate/Redis (5.5.*) package via Composer.

Once you peform this task, register Illuminate\Redis\RedisServiceProvider in your bootstrap/app.php file. At the end, call $app->configure(‘database’); in the bootstrap/app.php file to ensure that Redis database configuration is properly loaded.

5. Encryption

Before utilizing Lumen’s encrypter, always set the application key option of your .env file to a random 32 character string.

How To Encrypt?

You can encrypt a value in Lumen using Crypt facade. All values are encrypted using the OpenSSL and AES-256-CBC cypher. In addition to all these, all the values are signed with a MAC (Message Authentication Code) to detect any modification.

Here’s how it works:

<?php
  
  namespace App\Http\Controllers;
  
  use Crypt;
  use App\User;
  use Illuminate\Http\Request;
 
  class UserController extends Controller
 {
 	/**
 	 * Store a secret message for the user.
 	 *
 	 * @param  Request  $request
   * @param  int  $id
   * @return Response
 	 */
 	public function storeSecret(Request $request, $id)
 	{
 		$user = User::findOrFail($id);
 
    $user->fill([
'secret' => Crypt::encrypt($request->secret)
])->save();
}
 }
How To Decrypt?

You can decrypt any value by using the decrypt method on Crypt facade. If the value can’t be decrypted, then Illuminate\Contracts\Encryption\DecryptException will be thrown as shown in the snippet below:

use Illuminate\Contracts\Encryption\DecryptException;
 
 try {
 	$decrypted = Crypt::decrypt($encryptedValue);
 } catch (DecryptException $e) {
 	//
 }
6. Errors & Logging

When you start any new project in the Lumen framework, the error & exceptional handling mechanism is by default inherited in your project. In addition to that, Lumen has been integrated with Monolog, a logging library which provides the support for a variety of log handlers. So, you don’t need to worry about managing any error explicitly.

Read also: How Can You Effectively Work With Laravel Helpers?

7. Events

Lumen’s events provide you with a very simple observer implementation which helps you to subscribe and listen to the events in your app. The events classes are stored in app/event directory and listeners are stored in app/Listeners.

How To Register Event/Listener?

Like the Laravel framework, the EventServiceProvider included within the Lumen app provides a way to register event listeners. Here’s how the event listener mapping should take place:

/**
   * The event listener mappings for the application.
   *
   * @var array
   */
 protected $listen = [
      'App\Events\ExampleEvent' => [
          'App\Listeners\ExampleListener',
      ],
 ];
Firing Events

You can use event helper function or Event facade to fire the events throughout your Lumen app. Here’s how it works:

event(new ExampleEvent);
 
Event::fire(new ExampleEvent);

Closing Thoughts

In recent times when there is a massive demand for agile web applications, Lumen could be your best possible option. You may not be able to create large and complex applications as you can do in Laravel, but for creating small & lightweight apps, this is your best bet.

In this blog, we have tried to provide you with an in-depth guide on Lumen framework. We hope that it will be helpful to any Laravel Development Company. If you have any query regarding this article, then feel free to ask them in our comment section. Thank you!

looking-for-result-driven-laravel-app-development-services

Disclaimer: We at eSparkBiz Technologies have created this blog with all the consideration and utmost care. We always strive for excellence in each of our blog posts and for that purpose, we ensure that all the information written in the blog is complete, correct, comprehensible, accurate and up-to-date. However, we can’t always guarantee that the information written in the blog correct, accurate or up-to-date. Therefore, we always advise our valuable readers not to take any kind of decisions based on the information as well as the views shared by our authors. The readers should always conduct an in-depth research before making the final decision. In addition to these, all the logos, 3rd part trademarks and screenshots of websites & mobile apps are the property of the individual owners. We’re not associated with any of them.

Mohit Surati

Mohit Surati

A post-graduate in Computer Engineering. Passionate about innovative writing & Content Marketing. A rich vein of experience in writing articles related to WordPress right from plugins, themes, customization, security, WooCommerce & Gutenberg. Pens down his thoughts for eSparkBiz @Custom WordPress Development Company where you can Hire WordPress Developer as per your requirements.

Related Post

22% Faster, A New Era Of Web Development-PHP 7.3 (New Features, Changing Functionalities)

22% Faster, A New Era Of Web Development-PHP 7.3 (New Features, Changing Functionalities)

Today where technology is the pilot of our digital world, PHP in Web Development is capturing attention for its capability to build dynamic websites. But…

How Can You Effectively Work With Laravel Helpers?

How Can You Effectively Work With Laravel Helpers?

Hello.! and Welcome to another edition of our blog series where we discuss some of the most common problems, tips & tricks, and the latest…

Why Choose Laravel For Enterprise Business?

Why Choose Laravel For Enterprise Business?

Are you an owner of a company who is providing enterprise business solutions to all the clients around the globe? Are you looking to develop…

get in touch image

Growth Is Just One Click Away

Don’t feel like calling? Just share some project details & our company representative will get in touch. Schedule A Meeting with our Director of New Business

How long would you like the meeting to be?
Get In Touch