首頁 > 後端開發 > php教程 > 「領域驅動的 laravel」 建構可擴展且功能強大的出色系統

「領域驅動的 laravel」 建構可擴展且功能強大的出色系統

WBOY
發布: 2024-08-19 06:47:02
原創
452 人瀏覽過

在不斷擴展的軟體開發領域,創建可擴展、可維護且功能強大的系統絕非易事。有這麼多的框架、工具和模式爭奪您的注意力,您很容易感覺自己就像一個迷失的太空旅行者,在沒有方向的軌道上飛行。但不要害怕,開發者同行! ?領域驅動的 Laravel 儲存庫可使用領域驅動設計 (DDD) 方法來引導您完成 RESTful API 開發的整個過程。

https://github.com/oskhar/domain-driven-laravel

奧斯哈爾 / 域驅動 Laravel

? ?預先配置的 Laravel 11.x 模板,旨在促進遵循領域驅動設計 (DDD) 原則的 Web 應用程式的開發。

域驅動的 Laravel ? ?

一個健全、可擴展且靈活的架構,用於使用領域驅動設計 (DDD) 原則透過 Laravel 開發 RESTful API。

簡介

Laravel 是一個用於建立強大的應用程式的優秀框架,提供了一組豐富的功能和簡潔的語法。然而,隨著專案複雜性的增加,程式碼庫很容易變得難以管理。缺乏清晰的架構模式可能會導致職責混合,使程式碼更難以維護和擴展。

此儲存庫提供了一種使用領域驅動設計 (DDD) 原則來建構 Laravel 專案的方法,從而實現更好的組織、可擴展性和關注點分離。這裡展示的方法受到最佳實踐的啟發,旨在以實用且可維護的方式解決現實世界的挑戰。

目標是為建立 Laravel 應用程式提供堅實的基礎。

  • ?易於理解。組織良好、邊界清晰的程式碼庫。
  • ? ️ 可維護。遵循 DDD 原則...
在 GitHub 上查看

在本文中,我們將探索這個非凡的 Laravel 套件的星系,揭示其獨特的功能,並了解為什麼它非常適合想要建立複雜系統的開發人員。繫好安全帶,太空牛仔,因為我們即將發射! ?

目錄結構:https://github.com/oskhar/domain-driven-laravel/blob/main/docs/project-struct.md

什麼是領域驅動的 Laravel?

「領域驅動的 Laravel ??」是一種使用 Laravel 建構 RESTful API 的結構化方法,以領域驅動設計 (DDD) 原則為中心。該軟體包可讓您透過將相關業務邏輯分組到網域中來邏輯地建立應用程序,使您的系統更易於擴展和維護。

透過利用 Laravel 強大的架構和 DDD 的組織能力,此儲存庫可協助開發人員創建組織良好的 API,這些 API 既高效又強大。

為什麼採用領域驅動設計?

領域驅動設計提供了一個清晰的結構,用於分離關注點並將應用程式組織成可管理、可理解的部分。它專注於定義核心域和域邏輯(業務邏輯的核心)並保持應用程式模組化。

想像一下,您的系統就像圍繞恆星運行的行星一樣組織起來,每個行星都有明確的目的並與更大的系統連接。借助 DDD,您將擁有用戶管理、產品管理等領域,每個領域都在 API 生態系統中管理自己的引力。

「領域驅動的 Laravel 的真正魔力??」正在深思熟慮地實施這些概念,將 Laravel 轉變為一個運作良好的互連領域機器。現在您可以建立可擴展並為現實世界的複雜性做好準備的應用程式。

錯誤處理的力量:笑遍宇宙?

如果您像大多數開發人員一樣,您一定遇到過相當多的錯誤訊息。但是您是否遇到過錯誤處理程序因為您犯了錯誤而侮辱您?歡迎來到「領域驅動的 Laravel ??」的世界,在這裡,錯誤處理不僅僅是功能性的,而且是個性化且有趣的!

這個 repo 提供了內建的錯誤處理機制,不僅回傳預期的 HTTP 狀態碼,還會責罵你犯了錯。讓我們來分解其中一些回應:

$exceptions->render(
    fn(QueryException $exception, $request) => ($response)(
        APIResponseData::from([
            "status" => false,
            "errors" => [
                "Bro wrote the wrong database query. Backend skills issue.",
                $exception->getMessage()
            ]
        ]),
        APIStatusEnum::INTERNAL_SERVER_ERROR
    )
);
登入後複製

當您進行錯誤的資料庫查詢時,您會收到以下回應:

"Bro wrote the wrong database query. Backend skills issue."
登入後複製

系統會鼓勵您提高後端技能,而不是典型的、乾巴巴的錯誤訊息——有時還帶著一點態度!

其他回覆包括:

  • 陣列結構出錯:

    "Ayyo, looks like your backend messed up the array structure."
    
    登入後複製
  • 錯誤的方法呼叫:

    "Are you sure backend bro? The method you called doesn't exist."
    
    登入後複製
  • 未定義的異常:

    "Your backend is dumb, bro."
    
    登入後複製

這種獨特的方法不僅為您提供有用的信息,而且為您的調試體驗增添了有趣的變化。它將那些可怕的錯誤變成了輕鬆的時刻,提醒您即使在浩瀚的程式碼中,一點幽默也能大有幫助。

響應結構。

由於 API 回應定義良好的結構,所有錯誤(包括這些個人化錯誤)都將遵循一致的格式。 APIResponseData 類別確保回應的結構如下:

class APIResponseData extends Data
{
    public function __construct(
        readonly ?bool $status = true,
        readonly ?string $message,
        readonly mixed $data = null,
        /** @var array<string> */
        readonly ?array $errors,
        readonly ?PaginationData $pagination,
        readonly ?APIMetaData $meta,
    ) {
    }
}
登入後複製

以下是 500 內部伺服器錯誤的外觀:

// Example 500 Internal Server Error
{
    "status": false,
    "message": "Galactic disruption. An unexpected cosmic event occurred!",
    "errors": [
        "Bro wrote the wrong database query. Backend skills issue",
        "{{ Query error messages specifically }}"
    ],
    "meta": {
        "request_id": "string",
        "response_size": "integer|byte"
    }
}
登入後複製

這種結構提供了清晰度和一致性,確保每個回應,無論成功或失敗,都是可預測的並且易於在客戶端處理。

預設訊息:宇宙智慧?

此儲存庫的另一個亮點功能是 API 回應的預設訊息處理。如果您忘記在回應中設定訊息,您將不僅僅是得到一個通用的回退訊息,您還會收到一條銀河主題的訊息,讓您的 API 感覺就像一次穿越星空的旅行。

以下是預設訊息的範例:

  • 200 成功:「成功!您的請求已安全返回地球。」
  • 201 已建立:「新實體發射到宇宙中。」
  • 400 BAD_REQUEST:「您的要求偏離了方向,無法逃脫地球引力!」
  • 401 未經授權:「您的憑證沒有通過宇宙看門人!」
  • 404 NOT_FOUND:「您正在尋找的資料超出了空間範圍!」
  • 500 INTERNAL_SERVER_ERROR:「銀河系中斷。發生了意外的宇宙事件!」

這些主題回應不僅為您的 API 提供了有趣的風格,還讓客戶和使用者更清楚地了解幕後發生的事情。

For example, if your request hits a 404, instead of a boring "Not Found" message, you’ll receive a cosmic-themed error:

"The data you're seeking is beyond the bounds of space!"
登入後複製

This approach not only enriches the developer experience but also makes the API more user-friendly. Your clients and users will enjoy these little touches of humor and personality.

Going Beyond: What Else Makes This Repository Stellar? ?

"Domain-Driven Laravel ? ?" isn't just about humor and cosmic messages. It's a fully fleshed-out package that makes it easier to manage your Laravel applications using DDD principles. Let’s take a look at some of the other key features:

1. Modular Domain Design.

With a clean and modular architecture, you can easily organize your application into domains, each with its own logic and responsibility. This separation allows for better scaling, testing, and maintenance.

2. Built-in API Response Management.

Handling API responses is a breeze with a consistent structure that ensures all responses are formatted correctly. Whether you’re returning success, error, or validation messages, the built-in API response handler will make sure everything is in its right place.

3. Error Handling that Learns.

While the humorous error handling adds personality, it also comes with a solid system that tracks and logs exceptions in a way that helps you debug and improve your code.

4. Advanced Middleware.

The repository includes advanced middleware implementations that ensure all parts of your application are in sync with the domain rules and API structure. With these middleware hooks, you can ensure that your application always behaves as expected.

5. Integration with Spatie's Packages.

Leverage the power of Spatie’s robust Laravel packages for roles, permissions, and data handling. This repo comes with pre-configured support for Spatie’s tools, giving you the best of both worlds: the organization of DDD and the strength of Laravel’s best packages.

Simple Usage: Focus on Domain Actions ?️

When working with the repository, simplicity is key. The goal is for developers to focus purely on domain actions without worrying about infrastructure concerns. This clear separation of responsibilities ensures that each domain handles its own business logic while leaving shared services and external integrations to other layers.

1. Stay Focused on Domain Actions.

In this structure, all core logic related to a specific domain is encapsulated in Actions. You don’t need to think about cross-domain interactions or infrastructure concerns—just focus on building the actions that power your domain. For example, an action like CreateUserAction lives entirely within the User domain and manages user creation. You can call this action from a controller or another action, keeping your code concise and easy to manage.

namespace Domain\User\Actions;

use Domain\User\Models\User;

class CreateUserAction
{
    public function execute(array $userData): User
    {
        return User::create($userData);
    }
}
登入後複製

This straightforward action does its job without needing to handle infrastructure-level details like logging, caching, or external API calls. Those concerns are dealt with in the Infrastructure layer or the Shared domain, keeping your actions clean and single-focused.

2. Shared Domain for Cross-Cutting Concerns.

Any service that spans across multiple domains, such as authentication, logging, or notifications, can be placed in the Shared domain. This prevents domain entanglement and ensures that the logic stays modular and focused.

For example, a notification service can live in the Shared domain, allowing any domain to trigger notifications without duplicating code.

namespace Domain\Shared\Services;

class NotificationService
{
    public function sendNotification(UserData $user, string $message): bool
    {
        // Logic for sending notifications
    }
}
登入後複製

Any domain that needs to notify users can simply call this service, ensuring that the NotificationService is consistent across the application.

3. Infrastructure for External Integrations.

The Infrastructure layer handles external services and integrations. This includes third-party APIs, payment gateways, or database configurations. By keeping external integrations here, your domain actions remain focused on business logic without worrying about how the external world works.

For instance, a payment gateway service could be handled in Infrastructure, keeping payment logic separate from core domain actions.

namespace Infrastructure\Services;

class PaymentGatewayService
{
    public function processPayment(PaymentDetailsData $details): mixed
    {
        // Payment processing logic
    }
}
登入後複製

With this structure, domain actions can call on external services when needed, but the bulk of the integration code is abstracted away, keeping your business logic clean and independent.

4. Flexibility with Interfaces.

To enhance the repository's flexibility and error prevention, developers who are comfortable using interfaces can incorporate a dedicated Interfaces folder. This addition provides a structured way to manage potential changes, such as migrations or dependency removals, without impacting the core functionality. The minimalist design of this repository ensures that it remains adaptable to various development needs, and the use of interfaces aligns with this principle by offering a safeguard against unforeseen changes.

app
├── Console                     # Custom Artisan commands
├── Domain                      # Core domain logic and business rules
├── Infrastructure              # Infrastructure-related code
└── Interfaces                  # Additional Folder
登入後複製

This approach allows developers to define contracts for their actions, services, or any other components that may evolve over time, ensuring that the code remains stable and maintainable across different stages of development.

5. No Domain Interference.

One of the core principles of "Domain-Driven Laravel ? ?" is that each domain should remain isolated from others. Domains should not interfere with each other’s logic or responsibilities. If multiple domains need to share services or data, those services should either be abstracted into the Shared domain or handled in Infrastructure.

This ensures that no domain unintentionally “leaks” logic or affects the behavior of another. It makes your codebase easier to maintain and scale as each domain evolves independently.

Conclusion: Take Your Laravel Development to the Stars ?

If you’re ready to build Laravel applications that are not only scalable and powerful but also fun to work with, "Domain-Driven Laravel ? ?" is the repository for you. It combines the elegance of Domain-Driven Design with Laravel's strength, all while adding a dash of cosmic humor ?

Whether you’re a seasoned developer or just getting started with DDD, this package will help you organize your code, streamline your APIs, and provide a delightful development experience.

So what are you waiting for? Head over to the Domain-Driven Laravel ? ? repository, and start building systems that are out of this world!

May your code always compile, and your APIs always return a 200! ?✨

以上是「領域驅動的 laravel」 建構可擴展且功能強大的出色系統的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板