Home PHP Framework Laravel Laravel implements API architecture based on Module

Laravel implements API architecture based on Module

May 23, 2020 am 10:03 AM
laravel

Laravel implements API architecture based on Module

I really like writing software and programming based on modular design, but I don’t really like relying on third-party software packages and libraries to handle some trivial things, because they don’t Let your programming level be greatly improved. So I've been writing module-based software in Laravel for the past two years, and I'm very happy with the results.

The decisive factor that drives me towards software and programming methods based on modular design is that I want to continue to improve my programming level. Imagine you build a project structure and 6 months later you discover that the project has a lot of bugs. Project architecture is usually not easily changed without affecting 6 months of existing code. While analyzing this project, I noticed two main points: you either have a standard throughout the project and stick to it, or you modularize and improve it module by module.

Some people tend to develop at all costs and adhere to standards, even if it may mean adhering to a standard you no longer like. Personally, I prefer continuous improvement, and it doesn't matter if the 20th module is completely different from the first module. If one day I need to go back to module 1 to fix a bug or refactor, I can improve it to the latest standard used by module 20.

Suppose, like me, you like to develop Laravel applications based on modularity and avoid adding unnecessary third-party dependencies to the project as much as possible - this article is a bit of my experience.

1- Routing service provider

Laravel routing system can be said to be the entrance to the entire application. The first thing that needs to be modified is the default RouteServiceProvider.php file, which should modularize the existing routes.

<?php
namespace App\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
    /**
     * 定义应用路由。
     *
     * @return void
     */
    public function map()
    {
        $this->mapModulesRoutes();
    }
    protected function mapModulesRoutes()
    {
        // 如果你在编写传统 Web 应用而非 HTTP API,请使用 `web` 中间件。 
        Route::middleware(&#39;api&#39;)
             ->group(base_path(&#39;routes/modules.php&#39;));
    }
}
Copy after login

As above, we can directly get rid of the entire boilerplate of this file and just set up a modular routing file.

2- Module files

Laravel comes with some files in the routes folder. Since we no longer map these routes in the RouteServiceProvider, we can delete them directly. Next, we create a modules.php routing file.

<?php
use Illuminate\Support\Facades\Route;
Route::group([], base_path(&#39;app/Modules/Books/routes.php&#39;));
Route::group([], base_path(&#39;app/Modules/Authors/routes.php&#39;));
Copy after login

3- Books module

In the app folder, create the Modules/Books/routes.php file. In this file we can define routing rules for the Books module of the application.

<?php
use App\Modules\Books\ListBooks;
use Illuminate\Support\Facades\Route;
Route::get(&#39;/books&#39;, ListBooks::class);
Copy after login

You can use controller-based routing, which is the default standard routing method in Laravel, but I personally prefer the method of Good bye controllers, hello Request Handlers (abandon controllers and use request handlers). The following is the implementation of ListBooks.

<?php
namespace App\Modules\Books;
use App\Eloquent\Book;
use App\Modules\Books\Resources\BookResource;
class ListBooks
{
    public function __invoke(Book $book)
    {
        return BookResource::collection($book->paginate());
    }
}
Copy after login

In the above code, BookResource is the resource conversion layer of Laravel. Following the official recommendation for namespaces, we can create it in the app/Modules/Books/Resources folder.

<?php
namespace App\Modules\Books\Resources;
use Illuminate\Http\Resources\Json\Resource;
class BookResource extends Resource
{
    public function toArray($request)
    {
        return [
            &#39;id&#39; => $this->resource->id,
            &#39;title&#39; => $this->resource->title,
        ];
    }
}
Copy after login

4- Authors module

We can also start the Authors module through the Routes file.

<?php
use App\Modules\Authors\ListAuthors;
use Illuminate\Support\Facades\Route;
Route::get(&#39;/authors&#39;, ListAuthors::class);
Copy after login

Note: The namespace app/Modules/Authors represents the file we wrote and is also very simple for the request handler.

<?php
namespace App\Modules\Authors;
use App\Eloquent\Author;
use App\Modules\Authors\Resources\AuthorResource;
class ListAuthors
{
    public function __invoke(Author $author)
    {
        return AuthorResource::collection($author->paginate());
    }
}
Copy after login

Finally, we convert the Resource class we wrote into responsive JSON format.

<?php
namespace App\Modules\Authors\Resources;
use App\Modules\Books\Resources\BookResource;
use Illuminate\Http\Resources\Json\Resource;
class AuthorResource extends Resource
{
    public function toArray($request)
    {
        return [
            &#39;id&#39; => $this->resource->id,
            &#39;name&#39; => $this->resource->name,
            &#39;books&#39; => $this->whenLoaded(&#39;books&#39;, function () {
                return BookResource::collection($this->resource->books);
            })
        ];
    }
}
Copy after login

Notice how the resource goes into another module to reuse the BookResource . This is usually not a good choice since modules should be completely self-sufficient and can only reuse standard classes such as Eloquent Models or generic components designed to be common across any module. The solution to this problem is usually to copy the BookResource into the Authors module so that changes can be made without using another module and vice versa. I decided to keep this cross-module usage, this example shows a good rule of thumb to keep modules isolated from each other, but if you think the above example is simple and unlikely to cause any problems. Always make sure to write tests to cover the functionality you write to avoid others from unknowingly modifying your application.

5- Conclusion

Although this is a very simple example, I hope it allows people to easily manipulate the structural standards of the Laravel framework according to their own needs. . You can change the location of files very easily in order to build modular based applications. Most of my projects come with App/Components module, which can be used for reusable generic base classes for any module; App/Eloquent, the Modules folder can be used to hold Eloquent models and database relational models in which we can build Any functionality based on modularity. Here is the folder directory structure for an application I recently started working on:

Laravel implements API architecture based on Module

I hope everyone can get this concept from it, each module has its own needs and can have its own folders/entities/classes/methods/properties. There is no need to standardize all modules exactly the same, as some modules are much simpler than others and do not require extensive structural design. This example shows the AccountChurn module providing the API through an HTTP folder while still providing Artisan commands through the console. AccountOverview, on the other hand, only provides HTTP API and relies on warehouses, value objects (bags), and service classes (paginators) to provide greater data value.

Recommended tutorials: "PHP Tutorial" "Laravel Tutorial"

The above is the detailed content of Laravel implements API architecture based on Module. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to effectively check the validity of Redis connections in Laravel6 project? How to effectively check the validity of Redis connections in Laravel6 project? Apr 01, 2025 pm 02:00 PM

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Apr 01, 2025 pm 12:21 PM

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

See all articles