Because of my work at developerjoy.co, I have created over 10 Laravel projects from scratch in the last year, and worked on more than 25 and I have seem one common thing in all of them.
The Laravel default directory structure only works when your project it's really small.
As the project grows, the default directory structure becomes a problem because it does not scale properly.
After a few use cases, models, policies, and so on, you will end with something similar to this:
app/ ├── Actions │ ├── Actionable.php │ ├── Graph │ │ └── ... │ ├── MonthlyResume │ │ └── GenerateMonthlyResumeAssets.php │ ├── User │ │ └── UpdateUser.php │ └── VoidActionable.php ├── Console │ ├── Commands │ │ ├── CalculateUserCryptoPortfolioBalanceCommand.php │ │ ├── CategorizeTransactionsIaCommand.php │ │ ├── GenerateMonthlyReportAssetsCommand.php │ │ ├── IdeHelperAllCommand.php │ │ ├── PruneNotificationsCommand.php │ │ ├── SendMonthlyReportNotificationCommand.php │ │ ├── SendNewUpdateChangeLogNotificationCommand.php │ │ └── TrainCategorizationIaCommand.php │ └── Kernel.php ├── Contracts │ └── Pipe.php ├── Events │ ├── SharingConfigurationSaved.php │ ├── SupportMessageCreated.php │ └── VisitIncreased.php ├── Exceptions │ ├── GetBankAccountTransactionError.php │ ├── Handler.php │ └── RenderableApiError.php ├── Http │ ├── Controllers │ │ ├── Banks │ │ ├── Controller.php │ │ ├── CryptoCurrency │ │ ├── Notification │ │ ├── SupportMessage │ │ └── User │ │ ├── DeleteUserController.php │ │ ├── GetUserController.php │ │ └── PutUserController.php │ ├── Kernel.php │ ├── Middleware │ │ ├── Authenticate.php │ │ ├── DefaultLocale.php │ │ ├── TrustProxies.php │ │ ├── ValidateSignature.php │ │ └── VerifyCsrfToken.php │ ├── Requests │ │ ├── PostSupportMessageRequest.php │ │ └── PutUserRequest.php │ └── Resources ├── Jobs │ ├── CalculateUserCryptoPortfolioBalanceJob.php │ ├── GenerateMonthlyResumeAssetsJob.php │ ├── GetBankAccountDetails.php │ └── GetCoinGeckoValuesJob.php ├── Listeners │ ├── SendAdminNotificationOnSupportMessageCreated.php │ ├── SendEmailToUserOnVisitIncremented.php │ └── SendMailOnSupportMessageCreated.phpphp ├── Mail │ ├── SupportMessage │ └── Visits ├── Models │ ├── Bank.php │ ├── SharingConfiguration.php │ ├── SupportMessage.php │ ├── User.php │ └── UserCryptoPortfolioBalance.php ├── Notifications │ ├── Notifiable.php │ ├── ThrottledNotification.php │ ├── UncategorizedTransactionNotification.php │ └── UpdateChangeLogNotification.php ├── Policies │ └── CryptoCurrencyOrderPolicy.php ├── Providers │ ├── AppServiceProvider.php │ ├── EventServiceProvider.php │ ├── HorizonServiceProvider.php │ └── RouteServiceProvider.php ├── Services │ └── CategorizationAi.php └── Support ├── OrderType.php ├── SafeNumberFromStringParser.php ├── ShortNumberFormatter.php ├── StockAssets └── helpers.php
I removed a lot of files and directories from tree, but you can imagine that it's impossible to see all the code related to users.
As you can see, it's really difficult to know what's happening there. You are working in a users controller, for example, and you don't have all the relevant classes close to it.
You can't see, at a glance, all the relevant classes and models for your current use case.
A better directory structure in our Laravel project
The main key, to properly scale your app, is to being able to see al the related code to the current use case you're working on at a glance.
For example, if you're working on the user registration use case, you should have the user model, user policies, registration request, the registered event, and more, close to you.
src/ ├── Leads ├── Teams └── Users ├── Actions │ ├── CreateUser │ │ ├── CreateUser.php │ │ └── CreateUserAction.php │ ├── LoginUserAction.php │ ├── LogoutUserAction.php │ └── RefreshAuthenticationTokenAction.php ├── Authenticatable.php ├── Authentication.php ├── Events │ └── UserRegistered.php ├── Http │ ├── Controllers │ │ └── Api │ │ ├── PostAuthenticationLoginApiController.php │ │ ├── PostAuthenticationLogoutApiController.php │ │ ├── PostAuthenticationRefreshApiController.php │ │ └── PostAuthenticationRegisterApiController.php │ ├── Requests │ │ ├── PostAuthenticationLoginRequest.php │ │ └── PostUserRequest.php │ └── routes │ └── api.php ├── Infrastructure │ └── UserEventServiceProvider.php ├── InvalidCredentials.php ├── Listeners │ └── SendWelcomeEmailOnUserRegistered.php ├── Mail │ └── WelcomeMail.php └── User.php
But know, you're wondering, how can I achieve this architecture easily on Laravel.
How to implement a domain directory architecture on Laravel
The start point is composer.json file. We are going to create a new folder ./src to store all our new code.
Adding the directory to the psr-4 key in the composer.json we are going to autoimport all our files easily.
"autoload": { "psr-4": { "App\\": "app/", "DeveloperJoy\\": "src/", // ... }, // ... }
Just with this, you can put all your models, controllers, requests, policies, and more, in a custom domain folder under src/User, for example.
There are only a few things missing: routes, and providers, so let's go one by one.
Move routes to a custom folder
For routes we have multiple options, for me, the most simpler and easier is to import them in the web.php or in the api.php file.
I usually write a helper file inside routes folder that looks like this:
<?php function domain_web_routes(string $domain): void { require __DIR__."/../src/{$domain}/Http/routes/web.php"; } function domain_api_routes(string $domain): void { require __DIR__."/../src/{$domain}/Http/routes/api.php"; }
and imported in my composer.json file just adding it to the files array.
"autoload": { // ... "files": [ "routes/helpers.php" ] },
A them, in my default web.php or api.php I just import each new domain folder when it has any route.
This is, for example, my web.php file:
<?php use Illuminate\Support\Facades\Route; Route::inertia('/', 'Welcome'); domain_web_routes('Leads');
Inside src/Leads/Http/routes y have a web.php file with all my routes related to leads.
Is really that simple.
Move service providers, to a custom domain folder
With providers is actually pretty easy.
We have a file under bootstrap/app.php that has an array of all our providers.
You just have to add new providers to it, and it will be processed automatically on load time.
return Application::configure(basePath: dirname(__DIR__)) ->withProviders([ DeveloperJoy\Users\Infrastructure\UserEventServiceProvider::class, ]) ->create();
以上是如何用 4 小时组织你的 Laravel 项目的详细内容。更多信息请关注PHP中文网其他相关文章!

Laravel使用其直观的闪存方法简化了处理临时会话数据。这非常适合在您的应用程序中显示简短的消息,警报或通知。 默认情况下,数据仅针对后续请求: $请求 -

PHP客户端URL(curl)扩展是开发人员的强大工具,可以与远程服务器和REST API无缝交互。通过利用Libcurl(备受尊敬的多协议文件传输库),PHP curl促进了有效的执行

PHP日志记录对于监视和调试Web应用程序以及捕获关键事件,错误和运行时行为至关重要。它为系统性能提供了宝贵的见解,有助于识别问题并支持更快的故障排除

Laravel 提供简洁的 HTTP 响应模拟语法,简化了 HTTP 交互测试。这种方法显着减少了代码冗余,同时使您的测试模拟更直观。 基本实现提供了多种响应类型快捷方式: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

您是否想为客户最紧迫的问题提供实时的即时解决方案? 实时聊天使您可以与客户进行实时对话,并立即解决他们的问题。它允许您为您的自定义提供更快的服务

文章讨论了PHP 5.3中引入的PHP中的晚期静态结合(LSB),从而允许静态方法的运行时分辨率调用以获得更灵活的继承。 LSB的实用应用和潜在的触摸


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3汉化版
中文版,非常好用

Dreamweaver Mac版
视觉化网页开发工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。