Skip to content
Start » Laravel » PHP Laravel Framework Architectural Components

PHP Laravel Framework Architectural Components

all framework development department delivers a standardized architecture with the objective of organizing the work of software project teams with good programming practices. This is no different with the Laravel framework, and in this article you will have an overview of the components that make up its architecture.

Note that for each PHP Laravel component described here, a specific article may be suggested to go deeper and learn how to use it.

If you don't know the Laravel framework, start with the article:

Laravel Framework – What is it?

Main components of Laravel architecture

The architecture created for the framework was developed in a modular way by characteristics.

In this way, several components are delivered, each one with an objective and a solution for common problems in the development of systems for the web.

The following is an overview of the main (or most used) components available in the core of the Laravel framework:

Service Containers

Laravel service containers are a powerful tool for managing class dependencies and performing dependency injection. Through them, the dependencies of a particular class are “injected” (as instantiated objects) into the class that will use it, through the constructor or, in some cases, the “setter” methods.

Service Providers

The “service providers” are the central location of the entire bootstrap (launch) of all Laravel applications.

Your own application built with the framework, as well as all core Laravel services, are initialized through service providers.

In general this means: registering service container bindings – service containers, event listeners – listeners, middleware and even routes. In short, service providers – service providers, are the central place to configure your application.

If you open the file config/app.php you will see an array of configured providers. These are all service provider classes that will be loaded in your application. By default, a set of core Laravel service providers are listed in this array.

These providers initialize core Laravel components like mailer, queue-queue, cache, database-database and others. Many of these providers are “late providers” which means they will not load on every request, but only when the services they provide are actually needed.

facades

Facades provide a “static” interface to the classes available in the application's service container. Laravel comes with many facades that provide access to almost all of its features.

Laravel facades serve as “static proxies” for underlying classes in the service container, providing the benefit of concise and expressive syntax while maintaining more testability and flexibility than traditional static methods.

All Laravel facades are defined in the namespace Illuminate\Support\Facades.

Routing – Laravel routes

Routes are settings that teach Laravel which “routes” your application is prepared to accept in HTTP requests, and who (controller actions) will handle each of them.

All Laravel routes are defined in its route files, which are located in the directory routes. These files are automatically loaded by the App\Providers\RouteServiceProvider of your application. The file routes/web.php defines the routes that are for your web interface. These routes are assigned to the web middleware group, which provides features such as session state and CSRF protection. The routes in routes/api.php have no state and are assigned to the api middleware group.

Middlewares

Middlewares are a mechanism for inspecting and filtering HTTP requests coming into your application. For example, Laravel includes middleware that verifies that your app's user is authenticated. If not, the middleware will redirect the user to your app's login screen. However, if the user is authenticated, the middleware will allow the request to proceed through the application control flow.

You can build additional middleware to perform a variety of tasks in addition to authentication. For example, an auditing middleware can log all HTTP requests received in your application.

There are several middleware included in the Laravel framework, and they are located in the directory app/Http/Middleware.

controllers

Controllers are used so instead of defining all your request handling logic as scripts or anonymous functions in your route files, you can organize this behavior using “controller” or “controller” classes.

Controllers can group related request-handling logic into a single class. For example, a class UserController can handle all incoming requests related to users, including show, create, update and delete users. By default, controllers are stored in the directory app/Http/Controllers.

views

Obviously, it's not practical to return entire strings of HTML documents directly from your routes and controllers.

To solve this, Laravel implements the views layer. Views – views provide a convenient way to put all your HTML in separate files. In this way, views separate your controller/application logic from your presentation logic and are stored in the directory resources/views.

Blade engine template

So that you don't have to mix PHP code in your views along with HTML code, Laravel has the Blade templating engine.

He is one template engine simple yet powerful, that unlike some PHP view templating engines, Blade doesn't restrict you from using pure PHP code in them. In fact, all Blade templates are compiled into pure PHP code and cached until modified, which means Blade essentially adds zero overhead to your application. Blade template files use the file extension .blade.php and are normally stored in the directory resources/views.

HTTP Requests

The class Illuminate\Http\Request from Laravel provides an object-oriented way of interacting with the current HTTP request being handled by your application, as well as retrieving the input, cookies, and files that were sent with the request.

HTTP Responses

Typically, you won't just return simple strings or arrays from your route actions or from your controllers. Instead you will return full object instances or views Illuminate\Http\Response.

By returning a complete response instance, the object allows you to customize the response's HTTP status code and headers. A Response instance is inherited from the class Symfony\Component\HttpFoundation\Response, which provides a variety of methods for building HTTP responses.

session

Because HTTP-based applications are stateless, sessions provide a way to store user information between client requests. This information is typically placed in a persistent storage/backend that can be accessed from subsequent requests.

Laravel comes with a variety of session backends that are accessed through an expressive, unified API. Includes support for popular backends such as Memcached, Redis, and databases.

Validations

Laravel provides several different approaches to validating your application's input data. The most common is the use of the validation method available in all incoming HTTP requests, but the framework allows other strategies to validate and sanitize user data input.

It also includes a wide variety of validation rules that make it easy for you to apply to data, even providing the ability to validate that values are unique within a given database table.

In addition to these advanced features in data validation, it is still possible to write your own rules for reuse throughout the application.

error handling

When you start a new Laravel project, error and exception handling is already configured natively for you in your application.

The class App\Exceptions\Handler this is where all exceptions thrown by your application are logged and then processed and managed for the user.

logging

To help you keep track of what is happening in your application, Laravel provides robust (historical) logging services that allow you to write messages to files, the operating system error log, database, and even even to Slack to notify your entire team.

Laravel logging is based on "channels". Each channel represents a specific way of recording log information. For example, the single channel writes log files to a single log file, while the slack channel sends log messages to Slack. Log messages can be written to multiple channels simultaneously and based on their severity.

Inside, Laravel uses the Monolog library, which provides support for a variety of powerful log handlers. Laravel makes it easy to configure these handlers, allowing you to mix and match them to customize your application's log management.

Database – Databases

Virtually all modern web or mobile applications interact with a database.

Laravel makes using databases for information management extremely simple, supporting a variety of databases through: pure SQL, a query builder (Query Builder) fluent and the Eloquent ORM.

Currently, Laravel provides native support for four databases:

  • MySQL 5.7+
  • PostgreSQL 9.6+
  • SQLite 3.8.8+
  • SQL Server 2017+

Other databases are supported using framework extension packages such as:

Query Builder

The Database Query Builder (Query Builder) is a component of Laravel that provides a convenient and fluent interface for creating and executing SQL queries against databases.

It can be used to perform most database operations in your application and works seamlessly with all database systems supported by Laravel or extended with packages.

Query Builder Laravel uses parameter binding RDP (PHP Data Objects) to protect your application from SQL injection attacks – SQL injection. So there is no need for you to worry about cleaning or sanitizing (sanitizing) the user inputs (inputs) with the strings passed to the query builder as query bindings.

Eloquent ORM

Laravel includes Eloquent, an object-relational mapper (ORM – Object Relational Mapping) that makes using and interacting with your database a simple and flexible task.

When using the Laravel Eloquent component, each database table has a corresponding “Model” (from MVC – Model View Controller) that is used to interact with that table.

Eloquent is an ORM that applies the design pattern Active Record.

In addition to retrieving records from the database table, Eloquent models also allow you to insert, update and delete records from the table, directly and with high code productivity.

Advanced Laravel Components

In addition to the most common and essential components for any Laravel application, described above, the framework delivers a rich architecture of components of a more advanced nature, allowing developers to build large-scale web applications with high productivity and reduced complexity.

Here are some of the advanced components that you can use with Laravel and are natively delivered by the framework:

artisan console

Artisan is the command line interface included in Laravel.

Artisan exists at the root of your app as the script artisan and provides several useful commands that can help you as you build your application.

To see a list of all available Artisan commands, you can use the command list at the project root:

php artisan list

In addition to delivering a number of useful commands with Artisan, you can build your own commands into your application, making administrative tasks easier to perform from the command line.

Tinker (REPL)

Laravel Tinker is a powerful REPL for the framework, developed with the PsySH package.

All Laravel apps include Tinker by default.

Tinker lets you interact with your entire Laravel application from the command line, including your Eloquent templates, Jobs, events, and more.

To enter the Tinker environment, run the command tinker from Artisan:

php artisan tinker

broadcasting

In many modern web applications, WebSockets are used to implement real-time updated user interfaces.

Its common use is for when some data is updated on the server, a message is sent over a WebSocket connection to be received and handled by the client – web browser or mobile application.

WebSockets provide a more efficient alternative to continually querying your application's server for data changes that should be reflected in your UI – user interface.

For example, imagine that your application is able to export a user's data to a CSV file and send it via email.

However, creating this CSV file takes several minutes, so you choose to create and submit the CSV in a one-queue job – queue job.

After the Job runs, and the CSV is created and sent to the user, we can use event streaming to dispatch an event App\Events\UserDataExported that is received by our application's JavaScript.

Once the event is received, we can either display a message to the user that their CSV has been emailed without them having to constantly refresh the browser page, or that we implement timed Ajax calls asking the server if the export is complete.

To help you build features of this nature into your application, Laravel makes it easy to “broadcast” your server-side events over a WebSocket connection.

Streaming your Laravel events allows you to share the same event names and data between your server-side Laravel application and your client-side JavaScript application.

The basics behind broadcasting are simple: clients connect to named channels on the frontend, while your Laravel app broadcasts events to those channels on the backend. These events can contain any additional data you want to make available to the frontend.

cache

Some of the data retrieval or processing tasks performed by your application may be CPU intensive or take several seconds to complete.

For these cases, it is common to cache the retrieved data for a certain amount of time so that it can be retrieved quickly in subsequent requests for the same data contexts.

Cached data is usually persisted to a very fast data store such as memcached or redis.

Fortunately, Laravel provides an expressive, unified API for multiple caching backends, allowing you to enjoy lightning-fast data retrieval and speed up your web application.

Collections – Collections

The class Illuminate\Support\Collection provides a convenient and fluent wrapper for working with arrays and vectors of data.

For example, check the following code. We will use the helper collect to create a new array collection instance, run the function strtoupper on each element and then remove all empty elements:

$collection = collect(['taylor', 'abigail', null])->map(function ($name) { return strtoupper($name); })->reject(function ($name) { return empty($name); }) ;

As you can see, the Collection class allows you to chain its methods (chain of methods) to perform fluent mapping and reduction of the underlying array. In general, collections are immutable, which means that each Collection method returns an entirely new Collection instance.

events

Laravel events provide an implementation of the design pattern of observer, allowing you to subscribe to and listen to various events that take place within your application.

Event classes are normally stored in the directory app/Events, while its listeners are stored in app/Listeners.

Events serve as a great way to decouple various aspects of your application, as a single event can have multiple listeners that don't depend on each other.

For example, you can send a Slack notification to your user whenever an order is placed. Instead of coupling your order processing code to Slack's notification code, you can generate an event App\Events\OrderShipped that a listener can receive and use to execute the logic for sending a Slack notification.

File Storage

Laravel provides a powerful filesystem abstraction component thanks to the package flysystem PHP by Frank de Jonge.

Laravel Flysystem integration provides simple drivers to work with local, SFTP, and Amazon S3 file systems.

It's incredibly simple to switch between these storage options between the local development machine and the production server, as the API remains the same call for each system.

Within the component's configuration file, you can configure all the “disks” of your filesystem. Each disk represents a specific storage driver and storage location.

Example settings for each supported driver are included in the configuration file so you can modify the configuration to reflect your storage preferences and credentials.

For example, the local driver interacts with files stored locally on the server running the Laravel application while the s3 driver is used to write to Amazon's S3 cloud storage service.

HTTP Client

Laravel provides a minimal and expressive API around the Guzzle HTTP client, allowing you to make HTTP requests to communicate with other web applications.

Laravel's wrapper around Guzzle focuses on its most common use cases and a smooth developer experience.

localization

Laravel's localization features provide a convenient way to retrieve strings in multiple languages, allowing you to easily support multiple languages in your application.

It offers two ways to manage translation strings.

First, language strings can be stored in files in the directory resources/lang.

Within this directory, there may be subdirectories for each language supported by the application. This is the approach Laravel uses to manage translation strings for built-in Laravel features such as validation error messages.

The other way is translation strings which can be defined in JSON files which are placed in the directory resources/lang.

By taking this approach, each language supported by your application would have a corresponding JSON file in this directory. This approach is recommended for applications that have a large number of translatable strings.

mail

Sending email doesn't have to be complicated, so Laravel provides a clean and simple email API powered by the popular library SwiftMailer.

Laravel and SwiftMailer provide drivers for sending email via SMTP, Mailgun, Postmark, Amazon SES and sendmail, allowing you to quickly start sending emails via a local or cloud-based service of your choice.

notifications

In addition to support for sending email, Laravel supports sending notifications through a variety of delivery channels, including email, SMS (via Vonage, formerly known as Nexmo), and Slack.

Additionally, a variety of community-created notification channels are available as packages and can provide push notifications to dozens of different channels.

Notifications can also be stored in a database so they can be displayed in your web interface.

Typically, notifications should be short, informative messages that notify users of something that has occurred in your app. For example, if you are writing a billing app, you can send an “Invoice Paid” notification to your users via email and SMS channels.

Package Development

Packages are the main way to add functionality to Laravel by extending its native functions.

Packages can solve any software problem, from a great way to work with dates like Carbon or a package that lets you associate files with Eloquent models like Spatie's Laravel media library.

There are different types of packages. Some packages are standalone, meaning they work with any PHP framework. Carbon and PHPUnit are examples of standalone packages. Any of these packages can be used with Laravel, just insert them into the requires de in your composer.json file.

On the other hand, other packages are specifically intended for use with Laravel. These may have routes, controllers, views, and settings specifically intended to enhance a Laravel application.

All this means that you can write packages with reusable logics or modules within your company, or even distribute them to the community.

Queues – Execution Queues

When building your web application, you may have some tasks that take time to perform on HTTP requests, such as parsing and storing a CSV file.

Laravel makes it possible to create “late” running queues, allowing you to create queued jobs that can be processed in the background.

By moving time-consuming tasks to a queue, your application can respond to HTTP requests from the web with high speed and provide a better user experience for your customers.

Laravel queues provide a unified queuing API across a variety of different queue backends such as Amazon SQS, Redis, or even a relational database.

Laravel queue configuration options are stored in the configuration file config/queue.php of your application.

In this file, you'll find connection settings for each of the queue drivers included in the framework, such as database, Amazon SQS, Redis, and Beanstalkd drivers, as well as a synchronous driver that will run jobs right away (for use during local development).

A null queue driver is also included, to be used in tests as it discards queued jobs.

Task Scheduling – Task Scheduling

Chances are you wrote a cron configuration script for every task you needed to schedule on your server. However, this can quickly become complex to manage because your task schedule is not in the same source control location on the system, so you must SSH into your server to view your existing cron entries or add additional entries.

Laravel's command scheduler offers a new approach to managing scheduled tasks on your server.

The scheduler allows you to fluently and expressively define your schedule of commands within your own Laravel application.

When using the scheduler of Laravel, only a single cron entry is needed on your server.

In this way, your schedule of periodically executing tasks is defined in the file's schedule method. app/Console/Kernel.php.

Tests – Automated testing

Laravel was built with testing in mind.

In fact, support for testing with PHPUnit is included “out of the box" in the file phpunit.xml, and is already configured for your application.

The framework also provides convenient helper methods that allow you to expressively test your applications.

By default, your app's tests directory contains two subdirectories: Feature and unit.

Unit tests are tests that focus on a very small, isolated part of your code. In fact, most unit tests are likely to focus on a single method. Tests inside your “Unit” test directory do not initialize your Laravel application and therefore cannot access your application's database or other framework services.

The feature tests – Feature, can test more of your code, including how various objects interact with each other. yourself or even a full HTTP request to a JSON endpoint.

Generally, most of your tests should be tests of system features or functionality. These types of tests provide the greatest confidence that the system as a whole is performing as expected.


Final considerations

The Laravel framework is an excellent addition to any stack of Web application development based on PHP programming language.

In this article I presented the most common components in the use of applications developed with Laravel, as well as some of the advanced components that can facilitate the scalability of your systems without necessarily making you developer responsible for implementing all the logic complexity necessary for this.


To know and learn more read the articles about Laravel on this blog.

keep up to date

Don't forget to follow me on twitter and sign the Mazer.dev channel on Youtube to receive updates on new articles, video classes and free courses in web development, programming in general and software engineering.

Leave a Reply

Your email address will not be published.

en_USEnglish
%d bloggers like this: