Knowledge

Exploring Laravel HMVC: Components, Advantages, Best Practices.

Thu, 09.03.2023
Abidhusain Chidi
Co-Founder and CEO
Exploring Laravel HMVC: Components, Advantages, Best Practices

Introduction

Laravel Hierarchical Model-View-Controller (HMVC) is an extension of the popular Model-View-Controller (MVC) architecture that provides developers with a scalable and structured solution to create complex web applications. The HMVC architecture provided by Laravel enables developers to divide their code into modules, each with a unique Model, View, and Controller architecture. The components of Laravel HMVC will be examined in this blog post, along with its benefits and recommended practices for creating apps utilizing Laravel HMVC.

I. What is HMVC architecture?

The HMVC architecture is an extension of the conventional MVC design that enables programmers to write testable, reusable, and modular code for large-scale online applications. The application’s data, presentation, and control logic are separated into hierarchies, each with its own Model-View-Controller (MVC) architecture, according to the HMVC design. These hierarchies may be nested inside of one another, enabling programmers to easily build strong and complicated applications.

HMVC is a modular design, while MVC is a linear architecture, which is the main distinction between the two. In the typical MVC design, the Model interacts with the database, the View displays the data, and the Controller oversees the communication between the Model and View. Nevertheless, with HMVC, each module has its own Model, View, and Controller, making the program more modular and reusable.

HMVC architecture benefits

Using the HMVC architecture in Laravel has a number of benefits, including:

  1. Modularity: HMVC enables programmers to write testable, maintainable code that is modular. Each module may be created individually, and modifications to one module do not affect the other modules.
  2. Code reuse: HMVC makes it simple to reuse code across many modules. Model, View, and Controller components that developers may reuse in other modules can be created.
  3. Easy maintenance: By segmenting the code into modules, HMVC makes application maintenance simple. Each module may be tested individually, and modifications to one module do not affect the other modules.
  4. Improved scalability: By breaking the program up into modules, HMVC makes scaling the application simple. Additional modules may be added to the application without impacting the current modules.
  5. Quicker development: By enabling developers to work on many modules at once, HMVC makes it simple to construct the application. This shortens the time to market and accelerates the development process.

II. Recognizing the Laravel HMVC architecture

Now that we have a fundamental idea of what HMVC is, let’s see how Laravel implements it. The Model, View, Controller, and Hierarchy are the four key parts of the Laravel HMVC architecture.

The Model serves as the application’s data layer and is in charge of communicating with the database. The View, which stands in for the presentation layer, is in charge of showing the user the data. In order to handle user requests and update the Model and View appropriately, the Controller serves as a bridge between the Model and View. The Hierarchy component specifies the application’s structure and provides the connections between the various components.

Let’s examine each of these elements in more detail and how they fit within the HMVC architecture of Laravel.

The Laravel HMVC data flow

With Laravel’s HMVC architecture, the data goes via the following steps:

  1. Using the web server, the user submits a request to the application.
  2. The Router receives the request and, using the configured routes, maps it to the relevant Controller method.
  3. The Controller method receives the request and communicates with the Model to obtain or change data.
  4. The Model interacts with the database to obtain or update the data.
  5. The Model transmits the data back to the Controller when it has been obtained or changed.
  6. The Controller transmits the data to the relevant View.
  7. The View presents the data to the viewer.

III. The Model component in Laravel HMVC

The data layer of the application is represented by the Model component in Laravel HMVC. It is in charge of communicating with the database and managing data activities such as record creation, reading, updating, and deletion. Each model class in the Laravel HMVC Model component correlates to a database table using the Active Record pattern.

1. Model definition in Laravel HMVC

A Model class in Laravel HMVC is a PHP class that extends the Eloquent Model class. Methods for accessing and altering the database are provided by the Eloquent Model class. An interface for working with the table’s data is provided by the Model class, which represents a table in the database. Each instance of the Model class represents a row in the table, and each Model class includes characteristics that correspond to the columns of the table.

2. Relationship between the Model and the Database

Eloquent ORM (Object-Relational Mapping) is used by the Model component of Laravel HMVC to communicate with the database. The robust ORM Eloquent makes working with databases in Laravel simple. It enables programmers to build associations between tables, access data with sophisticated queries, and manage databases with clear and straightforward syntax.

3. Laravel HMVC Model CRUD operations

With the Model component, Laravel HMVC offers a simple and practical method for carrying out CRUD (Create, Read, Update, Delete) actions on the database. Here are some examples of CRUD activities utilizing the Model component:

  • Creating a new record
$post = new Post;
$post->title = 'New post';
$post->content = 'This is the content of the new post';
$post->save();
  • Reading records
$post = Post::find(1);
$posts = Post::all();
  • Updating records
$post = Post::find(1);
$post->title = 'Updated title';
$post->save();
  • Deleting records
$post = Post::find(1);
$post->delete();

4. Relationships in the Laravel HMVC Model

Developers may specify associations between database tables using the Model component of Laravel HMVC. Relationships may be one-to-one, one-to-many, or many-to-many. Here are some instances of relationships in Laravel HMVC:

  • One-to-one relationship
class User extends Model
{
    public function phone()
    {
        return $this->hasOne('App\Models\Phone');
    }
}
  • One-to-many relationship
class Post extends Model
{
    public function comments()
    {
        return $this->hasMany('App\Models\Comment');
    }
}
  • Many-to-many relationship
class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany('App\Models\Role');
    }
}

IV. The View component in Laravel HMVC

1. Laravel HMVC View Definition

A View in Laravel HMVC is a template file that includes HTML markup and placeholders for dynamic information. Views are used to deliver facts to the user in an aesthetically pleasing and user-friendly fashion. Views may be created using the Blade templating engine or simple HTML.

2. Laravel HMVC View types

There are three sorts of Views in Laravel HMVC:

  • Complete Views: These are finished HTML pages with the header, footer, and primary content. Complete Views are used to show pages that do not need extra data to be loaded.
  • Partial Views are subsets of Whole Views. Partial Views are used to show dynamic material like comments, likes, and shares.
  • Layouts are the views that specify the page’s general structure. The header and footer, for example, are reused across several pages in layouts.

3. How to construct Views with Laravel HMVC

Laravel HMVC View creation is simple. The ‘resources/views’ directory is normally where Views are kept. To build a new view, you may create a new file with the ‘.blade.php’ suffix in the ‘resources/views’ directory. For instance, you might create a file named ‘home.blade.php’ in the ‘resources/views’ directory to serve as a new View for the home page.

To render a View in Laravel HMVC, you may use the ‘view()’ method. The ‘view()’ method accepts the name of the View as its first parameter and an optional array of data as its second argument. For instance, you may use the following code to display the ‘home.blade.php’ View

return view('home');

An associative array may be sent as the second parameter to the ‘view()’ method if you need to give data to the View. For instance, the following code may be used to provide a variable named ‘$message’ to the ‘home.blade.php’ View

return view('home', ['message' => 'Welcome to my website']);

The value of the ‘$message’ variable may then be shown in the ‘home.blade.php’ View using the following code

<h1>{{ $message }}</h1>

4. Blade Templating engine in Laravel HMVC

Laravel HMVC comes with a templating engine called Blade. By enabling developers to utilize simple, expressive syntax, Blade offers a quick and straightforward approach to design Views. Blade templates are very effective since they are compiled into plain PHP code and cached until they are updated.

Blade has a number of features that make it simple to design Views, including:

  • Template inheritance: Blade enables developers to design a basic template that may be enhanced by additional templates. This makes it simple to develop layouts that are shared across numerous pages.
  • Blade has control structures like if/else statements and loops that make it simple to change the data in the View.
  • Blade enables developers to include partial templates inside of other templates. This makes it possible to reuse code across several Views.

The blade is incredibly strong and can be used to design complicated Views with ease. Please see the Laravel docs for further details about Blade.

V. The Laravel HMVC Controller component

In Laravel HMVC, the Controller component is in charge of processing the user’s request and delivering the proper answer. It serves as a go-between between the Model and View components. The Controller gets a request from the user and obtains the requested data from the Model when the user submits a request to the application. The appropriate View receives the data from the Controller and delivers the answer.

1. Laravel HMVC Controller Definition

In Laravel HMVC, a Controller is a class that deals with a particular HTTP request. It accepts the request, communicates with the Model to obtain the data, and then provides the information to the relevant View for rendering. The Controller is in charge of managing the application’s business logic and making choices depending on user input.

2. The relationship between the Controller and the Model and View

To get the information required to display the View, the Controller communicates with the Model. The data is then sent to the relevant View for drawing after being requested from the Model. The Controller is in charge of ensuring that the data obtained from the Model is in the proper format for presentation in the View. It also handles any errors that may occur during the retrieval of data.

To render the answer, the Controller also communicates with the View. It passes the data collected from the Model to the relevant View for rendering. The answer is then rendered by the View and delivered back to the user.

3. Laravel HMVC Controller Creation

You must develop a new PHP class that extends the basic Controller class given by Laravel in order to construct a Controller in Laravel HMVC. The Controller class may then be used to construct methods that respond appropriately to certain user requests. In Laravel HMVC, the following is an example of a simple Controller class:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::all();

        return view('users.index', ['users' => $users]);
    }

    public function create()
    {
        return view('users.create');
    }

    public function store(Request $request)
    {
        $user = new User;
        $user->name = $request->input('name');
        $user->email = $request->input('email');
        $user->password = bcrypt($request->input('password'));
        $user->save();

        return redirect()->route('users.index');
    }
}

In this example, we construct a User Controller class that can do the three tasks of indexing, creating, and storing. The index method obtains all users from the database using the User model and provides them with the index View. The create method just renders the create View, which shows a form for establishing a new user. The store function then takes care of the form submission, adding a new user to the database, and sending the user back to the index page.

4. Middleware in Laravel HMVC

Middleware is a potent Laravel feature that enables you to extend the functionality of the HTTP request/response cycle in your application. Middleware may be used to manage authentication, logging, and other general issues that apply to any Controller or View.

Middleware is a distinct PHP class that is registered with the application’s global middleware stack in Laravel HMVC. By adding them to the Controller or View’s middleware property, you may apply Middleware to specific Controllers or Views. Here is an example of a Middleware class that records all incoming requests in a file:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class LogRequests
{
    public function handle($request, Closure $next)
    {
        Log::info('Incoming request: ' . $request->fullUrl());

        return $next($request);
    }
}

You would add this Middleware to the Controller’s middleware field as follows to apply it to the Controller:

class UserController

VI. The Hierarchy component in Laravel HMVC

The HMVC design is all about organizing components into hierarchies that interact to form complicated web applications. The hierarchy component in Laravel HMVC is essential to making sure that each component is ordered and works well with the others.

1. Definition of Hierarchy in Laravel HMVC

The organization and interconnection of the many components of Laravel HMVC are referred to as the hierarchy. Each module in HMVC has its own hierarchy, which in turn has its own Model, View, and Controller. To build sophisticated applications, each hierarchy may communicate with other hierarchies.

2. How to establish a Hierarchy in Laravel HMVC

With Laravel HMVC, creating a hierarchy is simple. The first step is to namelessly create a new directory in the app directory. You create subdirectories for the Model, View, and Controller in this directory. Consider the scenario if you wished to organize goods into a hierarchy. In that situation, you might create a directory called “Products” and then subdirectories called “Model,” “View,” and “Controller” inside of it.

3. Advantages of Using Hierarchy in Laravel HMVC

Hierarchies in Laravel HMVC provide a number of advantages, including:

  • Modularity: Each hierarchy is self-contained and may be utilized in other areas of the program.
  • Scalability: As the program expands, additional hierarchies may be added, making it simpler to manage and maintain the software.
  • Separation of concerns: As each hierarchy is in charge of a single job, finding and fixing issues is much simpler.
  • Testability: makes it simpler to develop unit tests and integration tests since each hierarchy may be tested separately.

VII. Laravel HMVC routing

Routing is an essential aspect of every online application, and Laravel HMVC is no exception. In Laravel HMVC, routing is used to link URLs to particular actions in the application.

1. What is routing in Laravel HMVC?

In Laravel HMVC, routing is the process of connecting URLs to certain application operations. For instance, Laravel HMVC will utilize routing to link a user’s request for the URL “/products” to a particular action inside the application.

2. How Laravel HMVC handles routing

With Laravel HMVC, routes are defined in the routes file for the application. The routes file is stored in the app directory and is called “routes.php” by default. The URL pattern and the action that should be executed when that URL is visited are defined in the routes file.

3. Laravel HMVC route definition

To define a route in Laravel HMVC, you utilize the “Route” facade offered by Laravel. You may create routes using the “get”, “post”, “put,” and “delete” methods of the Route façade. The following is an example of how to define a route in Laravel HMVC:

Route::get('/products', 'ProductController@index');

In this example, we’re creating a route that associates the URL “/products” with the “index” method of the “Product Controller” controller.

VIII. Laravel HMVC security

One of the most crucial components of any online application is security. To guard against typical security vulnerabilities, Laravel HMVC has a number of built-in security measures.

1. CSRF prevention in Laravel HMVC

Attacks known as “CSRF” (Cross-Site Request Forgery) include tricking a user into doing an action on a website without their knowledge or agreement. To guard against these kinds of assaults, Laravel HMVC has built-in CSRF security.

For each form request, Laravel HMVC produces a CSRF token, which is then appended to the form as a hidden field. Laravel HMVC checks that the token in the request matches the one created for the form when the form is submitted. Laravel HMVC will refuse the request if the tokens do not match.

Just add the @csrf directive to your form to enable CSRF protection in Laravel HMVC.

<form method="POST" action="/profile">
    @csrf

    <!-- form fields -->
</form>

2. Laravel HMVC’s protection against Cross-Site Scripting (XSS)

Another frequent security risk is Cross-Site Scripting (XSS) assaults, in which an attacker inserts malicious code into a web page. Laravel HMVC has built-in XSS protection to avoid these sorts of attacks.

All user input that is presented in your views utilizing the Blade templating engine is automatically escaped by Laravel HMVC. This implies that any HTML, JavaScript, or other code a user writes will be presented as plain text rather than being executed as code.

Just use the double curly brackets syntax to output user input in a view:

<p>{{ $userInput }}</p>

3. Laravel HMVC role-based access control

Role-based access control (RBAC) is a security method that limits access to certain areas of an application depending on a user’s role. Laravel HMVC includes built-in support for RBAC, enabling you to quickly manage access to your application’s resources.

Roles and permissions may be defined in Laravel HMVC using middleware. Before HTTP requests get to the routes of your application, middleware acts as a filter. You may manage which users have access to which areas of your application by implementing middleware that validates a user’s role or permissions.

Use the following code to construct a middleware that verifies a user’s role:

public function handle($request, Closure $next, $role)
{
    if (! $request->user()->hasRole($role)) {
        // Redirect the user to a 403 error page.
        abort(403, 'Unauthorized action.');
    }

    return $next($request);
}

The middleware in the aforementioned code verifies that the user has the required role. The middleware routes users to a 403 error page if they do not have the required role.

To apply the middleware to a route, you may use the middleware() method:

Route::get('/admin', function () {
    //
})->middleware('role:admin');

The middleware in the code above determines if the user has the “admin” role. The user will be led to a 403 error page if they do not have the required role.

You can safeguard your application from typical security risks and guarantee the protection of your customers’ data by using the built-in security capabilities in Laravel HMVC.

VIII. Benefits of Using Laravel HMVC

Let’s look at the advantages of using the Laravel HMVC architecture for developing web apps now that we have covered its main components.

  1. Separation of concerns: One of the main benefits of employing the HMVC design is that it facilitates the separation of concerns or the division of labor between various components of the program. The code becomes more modular as a result of the separation of concerns, which also makes it simpler to scale and maintain.
  2. Code reusability: The HMVC design also has the benefit of encouraging code reuse. By separating the program into modules, developers may reuse these modules in other portions of the application, saving time and effort.
  3. Easy maintenance: As we have described before, the HMVC design helps to segregate issues and encourage code reusability, making the code simpler to maintain. As a result, modifications to the program may be done fast and simply without impacting other sections of the code.
  4. More scalability: The HMVC design is extremely scalable, making it possible to quickly support the expansion of the program as new features are introduced. The architecture’s modular design makes it simple to add new features to the application without changing the current code.
  5. Quicker development: The HMVC design encourages quick development since it allows developers to work on several application components concurrently without worrying about conflicts between various modules.
  6. Better code organization and management: The HMVC design, in conclusion, aids in better code organization and administration. By separating concerns and increasing code reusability, the code becomes more modular and simpler to maintain.

X. Recommended practices for designing apps with Laravel HMVC

While the Laravel HMVC architecture offers developers an effective tool for creating web apps, there are a number of best practices that developers should adhere to guarantee that their applications are of a high caliber and satisfy the needs and expectations of their clients.

  1. Adhere to the Single Responsibility Principle (SRP): According to this basic tenet of software development, each class or module should be responsible for just one thing. Developers may write code that is more modular, simpler to maintain, and less prone to problems by adhering to this approach.
  2. Employ Dependency Injection (DI): Dependency Injection is a design technique that enables developers to insert dependencies into their code rather than hardcoding them. This makes the code simpler to maintain, more tested, and more modular.
  3. Create clear and readable code: Creating high-quality apps requires clear and understandable code. Clean code is easier to read, comprehend, and maintain, and it decreases the likelihood of problems and mistakes.
  4. Create unit tests: Unit testing is a crucial component of software development because it enables programmers to check that individual lines of code are functioning as intended. Doing unit tests allows developers to find faults and mistakes early in the development cycle, making bug fixes simpler and less costly.

XI. Conclusion

In conclusion, the Laravel HMVC architecture is a strong tool for developing large-scale online applications in PHP, and it is crucial for developers to grasp its capabilities and advantages. By utilizing Laravel HMVC, developers can construct applications that are resilient, scalable, and maintainable, and they can also enhance their productivity and efficiency by employing built-in features and best practices.

Check another blog on Laravel Model-View-Controller (MVC).

Abidhusain Chidi

FAQs

Frequently asked questions

chevron down How does Laravel implement the HMVC architecture?

Laravel uses a combination of PHP classes and objects to implement the HMVC architecture. The application is organized into hierarchies, with each module containing its own Model, View, and Controller components. The components communicate with each other through defined interfaces, allowing them to work together seamlessly.

chevron down Can I use Laravel HMVC for small-scale applications?

Yes, you can use Laravel HMVC for small-scale applications, but it is designed to handle large-scale applications more efficiently.

chevron down How does Laravel HMVC help in code organization?

Laravel HMVC helps in code organization by separating the application's data, presentation, and control logic into hierarchies, making it easier to manage and maintain the codebase.

chevron down How does Laravel HMVC ensure security?

Laravel HMVC includes built-in features for ensuring security, such as Cross-Site Request Forgery (CSRF) protection, Cross-Site Scripting (XSS) protection, and role-based access control. Developers can also add their own middleware to further enhance security.