search
HomePHP FrameworkLaravelLaravel implements API architecture based on Module

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;));
    }
}

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;));

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);

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());
    }
}

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,
        ];
    }
}

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);

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());
    }
}

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);
            })
        ];
    }
}

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
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Using Laravel: Streamlining Web Development with PHPUsing Laravel: Streamlining Web Development with PHPApr 19, 2025 am 12:18 AM

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

Laravel: An Introduction to the PHP Web FrameworkLaravel: An Introduction to the PHP Web FrameworkApr 19, 2025 am 12:15 AM

Laravel is a modern PHP framework that provides a powerful tool set, simplifies development processes and improves maintainability and scalability of code. 1) EloquentORM simplifies database operations; 2) Blade template engine makes front-end development intuitive; 3) Artisan command line tools improve development efficiency; 4) Performance optimization includes using EagerLoading, caching mechanism, following MVC architecture, queue processing and writing test cases.

Laravel: MVC Architecture and Best PracticesLaravel: MVC Architecture and Best PracticesApr 19, 2025 am 12:13 AM

Laravel's MVC architecture improves the structure and maintainability of the code through models, views, and controllers for separation of data logic, presentation and business processing. 1) The model processes data, 2) The view is responsible for display, 3) The controller processes user input and business logic. This architecture allows developers to focus on business logic and avoid falling into the quagmire of code.

Laravel: Key Features and Advantages ExplainedLaravel: Key Features and Advantages ExplainedApr 19, 2025 am 12:12 AM

Laravel is a PHP framework based on MVC architecture, with concise syntax, powerful command line tools, convenient data operation and flexible template engine. 1. Elegant syntax and easy-to-use API make development quick and easy to use. 2. Artisan command line tool simplifies code generation and database management. 3.EloquentORM makes data operation intuitive and simple. 4. The Blade template engine supports advanced view logic.

Building Backend with Laravel: A GuideBuilding Backend with Laravel: A GuideApr 19, 2025 am 12:02 AM

Laravel is suitable for building backend services because it provides elegant syntax, rich functionality and strong community support. 1) Laravel is based on the MVC architecture, simplifying the development process. 2) It contains EloquentORM, optimizes database operations. 3) Laravel's ecosystem provides tools such as Artisan, Blade and routing systems to improve development efficiency.

Laravel framework skills sharingLaravel framework skills sharingApr 18, 2025 pm 01:12 PM

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

The difference between laravel and thinkphpThe difference between laravel and thinkphpApr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

Laravel user login function listLaravel user login function listApr 18, 2025 pm 01:06 PM

Building user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.