@ishit I wouldn’t use a package to create modules. It’s just completely overkill and unnecessary.
If you really wanted to carve your codebase up into modules, then this is how I would personally approach it.
- Create a /modules directory.
- Create modules inside this source directory with their own service providers.
- Add entries to my composer.json to auto-load classes from those modules.
Classes in each sub-directory under the /modules directory could then have their own namespace, and any classes related to that “module” (such as models, controllers, jobs, console commands, etc). You’d register those modules’ assets (migrations, views, etc) using the helper methods available in the service provider class.
So, if you have a “shop” module at modules/shop then you’d have a ShopServiceProvider class that could register all of the resources for that module:
// File: modules/shop/src/ShopServiceProvider.php
namespace Vendor\Shop;
class ShopServiceProvider extends ServiceProvider
{
public function register(): void
{
// Register any shop-related services like payment gateways, etc here...
}
public function boot(): void
{
$this->publishesMigrations([
__DIR__ . '/../database/migrations' => $this->app->databasePath('migrations'),
]);
$this->loadRoutesFrom(__DIR__ . '/../routes/web.php');
$this->loadViewsFrom(__DIR__ . '/../resources/views', 'shop');
}
}
You‘d then need to add an entry to the autoload section of your application’s composer.json file to tell Laravel where to find this module’s files:
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
- "Database\\Seeders\\": "database/seeders/"
+ "Database\\Seeders\\": "database/seeders/",
+ "Vendor\\Shop\\": "modules/shop/"
}
},
You’d also need to add your modules’ service providers to the array in your bootstrap/providers.php file:
return [
App\Providers\AppServiceProvider::class,
+ Vendor\Shop\ShopServiceProvider::class,
];