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 the case of 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 exhibits unique functionalities very similar to Laravel and therefore it has become one of the trustworthy technology for development purpose. This article will drive you through the vitals of Lumen and also talking about the current development approach, it has become very easy with developers for hire.

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 LaravelLumenApplication(
  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 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 approach any Best Laravel Development Company and they 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, 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

Routing

Lumen provides a routing facility via Fast Route. For those who don’t know, Fast Route is a library that provides a quick implementation of a 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 LaravelLumenApplication(
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);

Authentication

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

Authentication Service Provider

The AuthServiceProvider is in the app/providers that consists of a single call to Auth::viaRequest. This method will accept a closure that comes into play when a request for authentication arrives. If there is no authentication 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 IlluminateHttpRequest instance as shown in the snippet below:

use IlluminateHttpRequest;
$app->get('/post/{id}', ['middleware' => 'auth', function (Request $request, $id
) {
$user = Auth::user();
$user = $request->user();
 //
}]);

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

The first major difference between Lumen and Laravel, as far as authorization is concerned is 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);

Caching

The 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 perform this task, register IlluminateRedisRedisServiceProvider in your bootstrap/app.php file. In the end, call $app->configure(‘database’); in the bootstrap/app.php file to ensure that Redis database configuration is properly loaded.

Encryption

Before utilizing Lumen’s encrypter, always set the application key option of your .env file to a random 32 character string. In fact, Authentication & Authorization are one of the ways to Uplift Business With Laravel App Development.

How To Encrypt?

You can encrypt a value in Lumen using the 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 AppHttpControllers;
  
  use Crypt;
  use AppUser;
  use IlluminateHttpRequest;
 
  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();
}
 }

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

use IlluminateContractsEncryptionDecryptException;
 
 try {
  $decrypted = Crypt::decrypt($encryptedValue);
 } catch (DecryptException $e) {
  //
 }

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 that provides the support for a variety of log handlers. So, you don’t need to worry about managing any errors explicitly.

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

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 = [
      'AppEventsExampleEvent' => [
          'AppListenersExampleListener',
      ],
 ];
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);