2

AdonisJs – A Laravel-ish Node Framework

As a web application developer, I mostly work using PHP and Laravel framework as a back end developer and use Javascript for front end, mostly jQuery and other micro libraries. Also, love to code using Angular. So, I’ve a good understanding of Javascript as well but never use it for back end. Well, as Node provides us the ability to use Javascript to write web application which runs on server. This is really awesome and I’ve played with it using Express framework.

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js allows the creation of Web servers and networking tools using JavaScript and a collection of “modules” that comes with Node (written in javascript) to handle the various core functionality. So, it’s a platform where we can run web applications written in Javascript.

So, as a Node framework, Express is very popular one and most of the Node developers use it and I’ve tried it as well. It’s really nice. The most used technologies to build a web application by the Javascript developers are Mongo (NoSql Database), Express (Javascript Back End Framework), Angular (Javascript Front End Framework) and Node (JavaScript Web Development Platform) and these are known as MEAN stack tools or who uses these technologies known as MEAN stack developers. Anyways, it’s not a new concept and I’m not going to write how to develope web application using Node or MEAN stack tools. Instead, I’m writing (introductory) about another awesome framework for writing Node applications.

Before I write about the framework, let’s check the following code:

// app.js
var http = require('http');
http.createServer(function(req, res) {
  res.writeHead(200, {'content-type':'text/plain'});
  res.end('Hello World!\n');
})
.listen(3000);
console.log('Running Node Server...');

Well, this is a very basic example of a Node server. Now, to run the server all I need to run the following command from the command line/terminal:

node app

This will start the server on port 3000 and I can navigate the app from my browser using http://localhost:3000 which will show “Hello World!” on the browser. Alternatively, using Express framework a very basic example may look something like this:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

Well, these are very basic examples to clerify the idea if you are not familiar with these technologies but that’s enough. If you are interested then you may read documentations and lots of useful tutorials all over the web to learn more about these. So, now, let’s talk about the AdonisJS.

As I used the word Laravel-ish so if you are familiar with Laravel framework then you will get the idea. So, at first, let’s check the following code written using AdonisJS

const Route = use('Route');

Route.get('/', function * () {
  // handle request
});

Route.post('/', function * () {
  // handle request
});

This is a route declaration in AdonisJS framework but this is not all but you may use something like this as well, for example:

const Route = use('Route');
Route.get('/users', 'UserController.index');

// Named Route
Route.get('/users/profile/:id', ... ).as('profile')

// Generate the URL for previous named route
Route.url('profile', {id:1}); // example.com/users/profile/1

Also, you can define a RESTful resource by using the resource method, for example:

Route.resource('users', 'UsersController');

// This is equals to
// Route.get('users', 'UsersController.index').as('users.index')
// Route.get('users/:id', 'UsersController.show').as('users.show')
// Route.get('users/create' 'UsersController.create').as('users.create')
// Route.get('users/:id/edit', 'UsersController.edit').as('users.edit')
// Route.post('users', 'UsersController.store').as('users.store')
// Route.put('users/:id', 'UsersController.update').as('users.update')
// Route.patch('users/:id', 'UsersController.update')
// Route.delete('users/:id', 'UsersController.destroy').as('users.destroy')

This is an example of optional route parameter, notice the ? to make it optional:

Route.get('/make/:drink?', function (request, response) {
  const drink = request.param('drink', 'coffee');
  response.send(`I will make ${drink} for you`);
});

What about route grouping, prefixing and route middleware? It’s possible:

Route.group('name', function () {
  // all routes under this callback are part of this group
});

Route.group('version1', function () {
  Route.get('/', ...);
}).prefix('/v1')

Route.group('blog', function () {
  Route.get('/post', ...);
})
.middlewares(['auth']);

Well, this is only the routing part but there are so many other things that looks really cool and give me the exact feeling of coding using Laravel but only difference is that, this is Javascript. So, that’s why I used the word Laravel-ish and if you are familiar with that framework then you’ve already realized that, I’m not wrong. Anyways, I’m just writing an introductory article here so probably this is not the best place to learn AdonisJS so please check the documentation for more details. Before I finish I would like to show you some more examples, so let’s check it out.

Let’s see how can we create a controller in AdonisJS:

class UserController {

  *index (request, response) {
    let users = yield Users.all();
    response.json(users.toJSON());
  }

}

module.exports = HomeController

Well, the keyword class is now available in Javascript as of ES6 feature. Also, *index is a generator function in ES6, you may think it as a normal method of a class and to learn more about this generator function and it’s syntax you may visit MDN and this blog post as well. Now, what about Users.all(), does it look familiar? Yes, this called Lucid, which is an implementation of ActiveRecord for working with your database. Just like Eloquent in Laravel. To create an Eloquent Model, Oops! to create a Lucid model all you need to do is extend the base model like:

const Lucid = use('Lucid');

class User extends Lucid {

}

Now, this model will assume the users is the table name for this User model unless you define a method like this to explicitly tell the table name:

class User extends Lucid {

  static get table () {
    return 'my_users';
  }

}

What about Query Builder, well here it is:

class UserController {

    * home (request, response) {

        const Database = use('Database');

        const users = yield Database.table('users').select('*');
        // const users = yield Database.select('name', 'email').from('users');
        // const users = yield Database('users').where('age','>',20);

        // Make view and send response
        const view = yield response.view('users', { users:users });
        response.send(view);
    }
}

Okay, so this was an example of querying the database using the Query Builder and also, you can see the use of View, it’s similar but templating syntax is different. Let’s check that now:

{# resources/views/master.html #}



  
  {% block title %} {% endblock %}


  {% block content %}
  {% endblock %}


This was the master layout and it’s possible to extend the layout using extend just like Laravel, for example:

{# resources/views/users.html #}

{% extends 'layouts/master' %}

{% block title %}Users{% endblock %}

{% block content %}
    
    {% for user in users %}
  • {{ user.name }}
  • {% endfor %}
{% endblock %}

Well, there are more to check but like I said, it’s like an introdductory article and not possible to demonstrate every component/module. So, check the documentation. You’ll definitely love it. Even if you are not a Laravel developer then it’ll not take much time to get the idea of this awesome MVC framework for Node, but in case, you are a Laravel developer then this is a good option to play with because it’s not new to you and you’ll learnt it very easily.

This framework follows the exact same application structure and the term Service Provider and IoC/Service Container as well. Also, the use of automatic dependency injection is available but it’s slightly different here and it’s okay. Also, it comes with migration feature and yes it has ace command line tool just like the Artisan in Laravel.

Also, the config directory is available outside of the app folder and it contains configuration files like app.js, database.js and many other configuration files to configure various parts of you application.

To, use this framework you must install Node and npm (Node Package manager) and very likely you’ve those already installed on your system but if not, then unstall these, will take 1 or 2 minutes only.

Some syntax may look a little bit different in AdonisJS and it’s because of ECMA Script-6/ES6 features. So, if you are not familiar with the new features of ES6 then you should also check that first.

I’ve just checked it for one hour max and implemented a little application using this framework (one controller and a mySQL database) to check the framework. It also supports PostgreSQL, Sqlite and MariaDB as well. To use, any database you’ve to install the driver using npm. The installation of the framework is very easy, just follow the installation guide.

I’ve used the adonis-cli command line tool to install it but before you use this tool you have to install the tool using npm install -g adonis-cli from the command line but you’ve to install npm at first. Then to create a project using this tool and it is same as Laravel, which is for example (from the terminal):

adonis new project-name
cd project-name
npm start

Also, this article is written by keeping the Laravel developers on mind but it could be helpful for anyone who is not even familiar with Laravel PHP framework. Also, this is not a comparission of two languages or framework but I’ve discussed about similarities to make it easy to Laravel developers who are new to this technology.

I really love to code using Laravel and PHP (PHP-7 is awesome) but I also miss one thing that Javascript provides out of the box which is Asyncronousity but yes, we can mimic it in PHP as well but that’s another topic I think. Anyways, that’s enough for now. I would like to Muhammad Usman for mentioning about AdonisJS on a chat so I started digging into it and found it amazing.

Latest Blog

0
Php

PHP – 8.0 Match Expression

In PHP 8.0 there is a new feature or I should say a new language construct (keyword) going to be introduced,  which has been implemented depending […]

0
Php

New Union Type in PHP – 8

A new RFC has been finished voting and accepted for PHP – 8. That is “Union Types”, which is an extension of PHP’s type system. […]