Home  >  Article  >  PHP Framework  >  Laravel implements API architecture based on Module

Laravel implements API architecture based on Module

Guanhui
Guanhuiforward
2020-05-23 10:03:492968browse

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.com. If there is any infringement, please contact admin@php.cn delete