Laravel Modulator
Modulator splits a Laravel application into modules that are found by convention. A directory with an app/ folder is a module: its classes autoload with no composer.json, its provider, routes, views, translations, config and migrations load the Laravel way, and Composer packages can ship modules that your application overrides with a local copy.
Convention Discovery
A folder with app/ under Modules/ is a module. No manifest, no composer.json per module.
Nested Modules
Commerce/Checkout/Payments: child modules at any depth, with namespaces that follow the path.
Package Modules
Composer packages declare module pools; publish a module to override it locally under the same identity.
Every Composer Mode
Tested with the default, optimized and authoritative Composer autoloaders.
Safe State Changes
module:enable and module:disable edit your config file in place and refuse what they cannot edit safely.
Architecture Checks
module:doctor, module:graph and module:check find broken sources, cycles and undeclared module dependencies.
Run php artisan module:make Shop, then php artisan module:make:model Shop Product, and use Modules\Shop\Models\Product right away.
#Installation
Install the package with Composer; the service provider registers itself.
#Requirements
- PHP 8.0 or 8.1
- Laravel 8.75 or newer within 8.x
#Composer Installation
composer require pharaonic/laravel-modulator#Publish Configuration
Publish the configuration when you need to change the pools or the generation settings. module:enable and module:disable publish it for you the first time they change it.
php artisan vendor:publish --tag=modulator-configThe file is written to config/pharaonic/modulator.php.
#Create Your First Module
php artisan module:make ShopYou're all set! Modules/Shop is a module: add classes under Modules/Shop/app and they autoload as Modules\Shop\....
#Configuration
The configuration lives under pharaonic.modulator (published to config/pharaonic/modulator.php).
1return [ 2 'disabled' => [ 3 // 'Shop/Orders', 4 ], 5 6 'pools' => [ 7 'local' => [ 8 'path' => base_path('Modules'), 9 'namespace' => 'Modules',10 'priority' => 100,11 ],12 'app' => [13 'path' => app_path('Modules'),14 'namespace' => 'App\\Modules',15 'priority' => 90,16 'legacy' => true,17 ],18 ],19 20 'discovery' => [21 'cache' => true,22 ],23 24 'generation' => [25 'pool' => 'local',26 'stubs' => null,27 ],28];| Key | Default | Description |
|---|---|---|
disabled | [] | Module identities to disable. Every other discovered module is enabled. Keep it a plain list of strings so module:enable / module:disable can edit it. |
pools | local, app | Directories that hold modules. Each pool has a path, a namespace root, a priority, and optionally legacy => true (1.x layout). A pool may also be the class name of a Pharaonic\Laravel\Modulator\Contracts\Pool. |
discovery.cache | true | Keep the discovery result in bootstrap/cache/modulator.php. |
generation.pool | local | The pool module:make and module:publish write to. It must be an application pool with the app/ layout. |
generation.stubs | null | A directory of stubs that replace the package stubs with the same name. When null, stubs/modulator is used if it exists. |
A pool namespace is the namespace root of its modules: Modules/Shop/app/Models/Product.php in the local pool is Modules\Shop\Models\Product. app/ never appears in the namespace.
#Custom Pool Classes
A class implementing Contracts\Pool provides a pool whose path is computed at runtime, for example per tenant:
1use Pharaonic\Laravel\Modulator\Contracts\Pool; 2 3final class TenantPool implements Pool 4{ 5 public function name(): string { return 'tenant'; } 6 public function priority(): int { return 80; } 7 public function path(): string { return storage_path('tenant/modules'); } 8 public function namespace(): string { return 'Tenant\\Modules'; } 9 public function package(): ?string { return null; }10}1'pools' => [2 // ...3 'tenant' => App\Modules\TenantPool::class,4],#Basic Usage
Create a module, add a class, and use it. Nothing needs to be registered in composer.json.
php artisan module:make Shopphp artisan module:make:model Shop Product --migration1namespace Modules\Shop\Models;2 3use Illuminate\Database\Eloquent\Model;4 5class Product extends Model6{7 //8}1use Modules\Shop\Models\Product;2use Pharaonic\Laravel\Modulator\Facades\Modules;3 4Product::query()->get();5 6Modules::find('Shop')->isEnabled(); // true7Modules::find('Shop')->path('routes/web.php'); // ".../Modules/Shop/routes/web.php"#What A Module Loads
| Convention | Loaded as |
|---|---|
app/Providers/<Name>ServiceProvider.php | The module service provider (optional; only this one is registered automatically) |
config/*.php | config('modules.<slug>.<file>') |
resources/views | view('<slug>::name') |
lang or resources/lang | __('<slug>::file.key'), plus JSON translations |
database/migrations | Run by php artisan migrate |
database/factories, database/seeders | Modules\Shop\Database\Factories\, Modules\Shop\Database\Seeders\ |
routes/web.php | The web middleware group |
routes/api.php | The api middleware group and the api prefix |
routes/console.php, app/Console/Commands | Registered in the console |
tests | Modules\Shop\Tests\ |
The slug is the identity in kebab case: Shop is shop, Commerce/Checkout is commerce-checkout.
Routes get no automatic URL prefix: write the URIs you want in the module route files.
#Module Conventions
A module is a directory under a pool that contains app/. A directory without app/ is a namespace group: it holds modules but has no provider, routes or state.
1Modules/ 2├── Shop/ Shop (module) 3│ ├── app/ Modules\Shop\ 4│ │ ├── Models/Product.php Modules\Shop\Models\Product 5│ │ └── Providers/ShopServiceProvider.php 6│ ├── database/{migrations,factories,seeders}/ 7│ ├── resources/{views,lang}/ 8│ ├── routes/{web.php,api.php} 9│ ├── tests/10│ ├── helpers.php optional11│ ├── module.php optional12│ ├── module.lock only in a published copy (module:publish)13│ └── Modules/ only when it has child modules14│ └── Orders/app/ Shop/Orders → Modules\Shop\Orders\15└── Platform/ namespace group (no app/)16 └── Billing/app/ Platform/Billing → Modules\Platform\Billing\#Identities
- An identity is one or more StudlyCase segments joined by
/:Shop,Commerce/Checkout. - Each segment starts with an uppercase letter and holds letters and digits only.
Modulesis reserved. - At most 16 levels.
- The namespace is the pool namespace followed by the segments:
Commerce/CheckoutisModules\Commerce\Checkout. - An identity is stable across pools: a package module and its local copy share it, and the state is keyed by it.
#The Service Provider
A module has at most one conventional provider, app/Providers/<Name>ServiceProvider.php, where <Name> is the last identity segment. A module without one is valid. Register any other provider from it.
Two identities that differ only by case (Shop and SHOP) are rejected, since they cannot both exist on a case-insensitive filesystem.
#Helpers
A module can define global functions in helpers.php at its root (next to app/, not inside it). The file is required once, when the module registers, and only while the module is enabled. A child module loads its own helpers.php.
1<?php2 3if (! function_exists('shop_currency')) {4 function shop_currency(): string5 {6 return config('modules.shop.store.currency', 'EGP');7 }8}- Functions are global. Prefix them with the module slug and wrap each one in
function_exists(), so two modules cannot collide with a fatal "Cannot redeclare" error. - The file loads after the application's config files, so a helper cannot be used inside
config/*.php. It is available in providers, routes, views and everything after them. - Disabling a module stops loading its helpers the next time the application boots. A function already defined in a running process (a queue worker, Octane) stays until it restarts.
#Livewire Components
With livewire/livewire installed (Livewire 2), the components in a module's app/Http/Livewire are registered for you, named after the module slug. Nothing to configure, and nothing happens without Livewire.
| Class | Name |
|---|---|
Modules\Shop\Http\Livewire\Cart | shop::cart |
Modules\Shop\Http\Livewire\Admin\UserTable | shop::admin.user-table |
Modules\Shop\Orders\Http\Livewire\OrderList | shop-orders::order-list |
1<livewire:shop::cart />2@livewire('shop::admin.user-table')- Only enabled modules register components; abstract classes and classes that are not
Livewire\Componentare skipped. - The classes come from the module class map, so a cached manifest (
module:cache) needs no scan. - Create one with
module:make:livewire(see Generators).
#Filament Resources, Pages And Widgets
With filament/filament installed (Filament 2), a module's Filament classes join the admin panel on their own, the way a Filament plugin's do:
| Directory | Registered as |
|---|---|
app/Filament/Resources | resources (their pages, relation managers and widgets too) |
app/Filament/Pages | pages |
app/Filament/Widgets | dashboard widgets |
- Only enabled modules register them; abstract classes, and classes that are not a resource, page or widget, are skipped.
- Only classes directly in each directory count:
Resources/ProductResource/Pages/*are the resource's pages, not standalone pages. - The classes come from the module class map, so nothing is scanned.
- Create a resource with
module:make:filament-resource(see Generators).
#Nested Modules
A child module lives in its parent's Modules/ folder. A folder named Modules never adds an identity segment, so Commerce/Checkout may live at Commerce/Checkout (when Commerce is a group) or at Commerce/Modules/Checkout (when Commerce is a module).
php artisan module:make Commercephp artisan module:make Commerce/Checkout# creates Modules/Commerce/Modules/Checkout#Hierarchy Is Not A Dependency
- A disabled parent disables its children. Their own configured state is kept, so they come back with the parent.
- A child is not enabled when its parent is disabled, even if the child itself is enabled in the configuration.
- A parent is not a business dependency: declare the modules a child uses in its
module.php. - A child may come from another pool than its parent, e.g. a local
Commerce/Checkoutunder a packageCommerce.
#Reserved Child Names
Database and Tests cannot be children of a module, because the parent maps Modules\Commerce\Database\ and Modules\Commerce\Tests\ itself. A child also cannot share a namespace with a folder of its parent's app/ (for example Commerce/Models next to Commerce/app/Models).
#Module Definition
An optional module.php at the module root declares dependencies and the public namespaces of the module. It returns a plain array: no class is loaded during discovery.
1return [2 'dependencies' => ['Catalog', 'Commerce/Checkout'],3 'exposes' => ['Contracts', 'Events'],4];| Key | Description |
|---|---|
dependencies | Module identities this module needs. A missing, disabled or cyclic dependency disables the module, with the reason. |
exposes | Namespaces, relative to the module, that other modules may use. Empty means everything; module:check enforces it. |
Load order follows the requirements: parents and dependencies register before the modules that need them.
Unknown keys are reported and ignored. A dependency cycle disables every module of the cycle.
#Pools And Packages
Pools are the directories modules are discovered in. When several pools hold the same identity, the pool with the highest priority wins and the other copies are shadowed.
| Pool | Path | Namespace | Priority |
|---|---|---|---|
local | Modules/ | Modules | 100 |
app (1.x layout) | app/Modules/ | App\Modules | 90 |
| Packages | declared by each package | Modules by default | 50 by default |
#Rules
- Equal priorities for the same identity are an error: the identity is not resolved until you change a priority or remove a copy.
- State is computed after selection: a disabled winner never falls back to a shadowed copy.
- Providers, routes, resources and classes come only from the selected copy.
#Shipping Modules In A Package
A Composer package declares its pools in its own composer.json. Modulator reads them from vendor/composer/installed.json; the package needs no service provider.
1{ 2 "name": "acme/shop", 3 "extra": { 4 "pharaonic": { 5 "modulator": { 6 "pools": [ 7 { "path": "modules" } 8 ] 9 }10 }11 }12}Each pool accepts path (relative to the package), namespace (default Modules) and priority (default 50). The pool is named after the package (acme/shop, then acme/shop:2 for a second pool).
A package must not map its module namespaces in its own autoload section. Modulator autoloads the selected copy only; module:cache refuses Composer mappings that point at a shadowed copy.
Inspect the pools and the copies of a module:
php artisan module:poolsphp artisan module:source Shop#Publishing Package Modules
module:publish copies a package module into the generation pool. The local copy keeps the identity and the namespace, and overrides the package copy.
php artisan module:publish Shop --dry-runphp artisan module:publish Shopphp artisan module:publish Shop/Orders # one child onlyphp artisan module:publish Shop --with-childrenphp artisan module:publish Shop --force # replace a local copy that differs- The package in
vendor/is only read. - The copy is assembled in
storage/framework/modulator/tmp, then moved into place. - When a local copy exists and differs, the command lists the added, changed and removed files and stops;
--forcereplaces it and keeps the old copy instorage/framework/modulator/backups. - Child modules are published only with
--with-children; local children stay where they are.
#Keeping A Copy Up To Date
Every published copy gets a module.lock next to its app/: the package and version it came from, and the hash of each copied file. Commit it with the copy. It is written by module:publish only; do not edit it.
1{ 2 "module": "Shop/Orders", 3 "package": "acme/shop", 4 "version": "1.0.0", 5 "reference": "4f2c1e0", 6 "children": false, 7 "files": { 8 "app/Models/Order.php": "9a8b…", 9 "routes/web.php": "1c2d…"10 }11}After a composer update, module:doctor compares the copy, its lock and the package:
- files you changed and the package did not are fine: that is what the copy is for;
- files the package changed since the copy are reported, with both versions;
- files changed on both sides are reported separately: merge those by hand.
1[Shop/Orders] was published from acme/shop 1.0.0, and the package (now 2.0.0) changed since: app/Models/Order.php. Changed in both the package and your copy: app/Models/Order.php. ...Bring the package changes into your copy, or take the package version with module:publish Shop/Orders --force (your copy is kept as a backup). Publishing again rewrites the lock. module:source shows where a copy came from.
To go back to the package copy, delete the local copy and rebuild the manifest:
php artisan module:delete Shop --forceRestart queue workers (and run php artisan octane:reload with Octane) after publishing, and rebuild route and config caches if you use them.
#Enabling And Disabling Modules
Every discovered module is enabled unless its identity is in pharaonic.modulator.disabled. The commands edit that list in config/pharaonic/modulator.php and keep the rest of the file as it is.
php artisan module:disable Shopphp artisan module:enable Commerce/Checkoutphp artisan module:statusphp artisan module:status Commerce/Checkout#Rules
| Situation | Result |
|---|---|
| Disable a parent | Its children are disabled too; the config lists only the parent. |
| Enable a child of a disabled parent | Refused. Add --with-parents to enable the parents too. |
| Enable a module whose dependency is disabled | Refused. Add --with-dependencies. |
| Disable a module others depend on | Refused, with the list. --cascade disables them too (confirm, or add --force). |
| Production | Asks for confirmation; --force skips it. |
#Configured And Effective State
module:status shows both, with the chain of reasons:
1Module: Shop/Orders2Configured: enabled3Effective: disabled4 Shop/Orders: Disabled because its parent [Shop] is disabled.5 Shop: Disabled in configuration (pharaonic.modulator.disabled).When disabled is computed (for example explode(',', env('MODULES_DISABLED'))), the commands refuse and leave the file untouched. Edit it by hand.
Changing the file does not change a running application. With config:cache, run php artisan config:cache again; restart queue workers, and run php artisan octane:reload if you use Octane.
#Current Module
Select a module for your console, then leave the module out of module commands.
php artisan module:use Shop/Productsphp artisan module:make:model Product # Shop/Productsphp artisan module:make:model Blog Post # the explicit module winsphp artisan module:currentphp artisan module:use --clearResolution order: the explicit argument, then the selected module, then an interactive choice; otherwise the command fails and asks for the identity.
- The selection is stored per operating-system user in
storage/framework/modulator/context, kept out of version control. - It is used only on interactive consoles, never when
CIis set, in production, or with--no-interaction. Scripts and deployments must give the module explicitly. - An explicit module never changes the selection.
- A selected module that no longer exists is reported.
#Generators
module:make creates a module; module:make:* creates classes inside one. Generators take {module} {name}, or only {name} to use the module selected with module:use.
php artisan module:make Shopphp artisan module:make Shop/Orders --plainphp artisan module:make:controller Shop ProductController --resource --model=Productphp artisan module:make:model Shop Product --allphp artisan module:make:migration Shop create_products_table --create=products#Generator Types
There is a module:make:* command for every make:* command of Laravel.
| Command | Writes to | Options |
|---|---|---|
module:make:action | app/Actions | |
module:make:cast | app/Casts | --inbound |
module:make:channel | app/Broadcasting | |
module:make:class | app | --invokable |
module:make:command | app/Console/Commands | --command=, tests |
module:make:component | app/View/Components + view | --inline, --view (anonymous: only the view), --path=, tests |
module:make:config | config | |
module:make:controller | app/Http/Controllers | --api, --type=, --invokable, --model=, --parent=, --resource, --requests, tests |
module:make:event | app/Events | |
module:make:exception | app/Exceptions | --render, --report |
module:make:factory | database/factories | --model= |
module:make:filament-resource | app/Filament/Resources + its pages | --model=, --simple, --view, --soft-deletes, --generate; needs filament/filament |
module:make:interface | app/Contracts | |
module:make:job | app/Jobs | --sync, --batched, tests |
module:make:job-middleware | app/Jobs/Middleware | tests |
module:make:listener | app/Listeners | --event=, --queued, tests |
module:make:livewire | app/Http/Livewire + resources/views/livewire | --inline, tests (Livewire::test); needs livewire/livewire |
module:make:mail | app/Mail | --markdown[=view], --view[=view], tests |
module:make:middleware | app/Http/Middleware | tests |
module:make:migration | database/migrations | --create=, --table=, --fullpath (runs Laravel's make:migration) |
module:make:model | app/Models | --all, --controller, --factory, --migration, --morph-pivot, --policy, --seed, --pivot, --resource, --api, --requests, tests |
module:make:notification | app/Notifications | --markdown[=view], tests |
module:make:observer | app/Observers | --model= |
module:make:policy | app/Policies | --model=, --guard= |
module:make:provider | app/Providers | |
module:make:request | app/Http/Requests | |
module:make:resource | app/Http/Resources | --collection |
module:make:rule | app/Rules | --implicit |
module:make:scope | app/Models/Scopes | |
module:make:seeder | database/seeders | |
module:make:service | app/Services | |
module:make:test | tests/Feature or tests/Unit | --unit, --pest, --phpunit |
module:make:trait | app/Concerns (traits are concerns, as in Laravel) | |
module:make:view | resources/views | --extension=, tests |
"Tests" means --test, --pest and --phpunit: they also write a matching test, e.g. tests/Feature/Http/Controllers/ProductControllerTest.php. Pest is used when it is installed, unless you pass --phpunit; --pest without Pest installed fails and writes nothing.
#Framework Table Migrations
| Command | Table |
|---|---|
module:make:cache-table | cache, cache_locks |
module:make:notifications-table | notifications |
module:make:queue-batches-table | job_batches |
module:make:queue-failed-table | failed_jobs |
module:make:queue-table | jobs |
module:make:session-table | sessions |
Each writes the migration into the module's database/migrations, with the table name from your configuration and the columns of the running Laravel version.
Every generator accepts --force to overwrite an existing file. Names may contain sub-namespaces: Admin/ProductController. Legacy (1.x) modules keep the 1.x folders (Commands, Interfaces, Traits, Scopes, Classes).
Generators never write into package modules. Publish the module first with module:publish.
#Custom Stubs
Publish the package stubs to stubs/modulator, then edit the ones you want. A file there replaces the package stub with the same name (controller.stub, model.stub, module/provider.stub, module/routes-web.stub, ...); delete the ones you keep as they are, and they keep coming from the package.
php artisan vendor:publish --tag=modulator-stubsstubs/modulator is used automatically while generation.stubs is null. To keep the stubs elsewhere, point generation.stubs at that directory:
1'generation' => [2 'pool' => 'local',3 'stubs' => base_path('resources/stubs/modules'),4],The modulator-stubs and pharaonic-stubs tags publish the stubs; the pharaonic and laravel-modulator tags do not, so publishing a package's files never adds them.
1<?php2 3namespace {{ namespace }};4 5final class {{ class }}6{7 //8}Tokens: {{ namespace }}, {{ class }}, {{ module }}, {{ slug }}, {{ rootNamespace }}, and per type {{ model }}, {{ namespacedModel }}, {{ modelVariable }}, {{ command }}, {{ view }}. Module stubs use {{ namespace }}, {{ name }}, {{ module }} and {{ slug }}.
#Factories
Module models use their module factories with HasFactory: Modules\Shop\Models\Product uses Modules\Shop\Database\Factories\ProductFactory.
#Database Commands
Each command runs Laravel's own command limited to the module's database/migrations.
php artisan module:migrate Shopphp artisan module:migrate:status Shopphp artisan module:migrate:rollback Shop --step=1php artisan module:migrate:reset Shopphp artisan module:migrate:refresh Shop --seedphp artisan module:migrate:refresh Shop --seeder=DemoSeederphp artisan module:seed Shop --class=ProductSeeder| Command | Options |
|---|---|
module:migrate | --database=, --force, --pretend, --seed, --seeder=, --step |
module:migrate:rollback | --database=, --force, --pretend, --step= |
module:migrate:status | --database= |
module:migrate:reset | --database=, --force, --pretend |
module:migrate:refresh | --database=, --force, --seed, --seeder=, --step= |
module:seed | --class= (default DatabaseSeeder, relative to Modules\Shop\Database\Seeders), --database=, --force |
--seed runs the module's DatabaseSeeder afterwards; --seeder= runs another one and implies --seed. The class is resolved like module:seed --class: relative to the module's Database\Seeders namespace, or fully qualified with a leading \.
Laravel's migrate:fresh drops every table of the database, whatever --path says. module:migrate:fresh now fails with an explanation. Use module:migrate:refresh <module>, or php artisan migrate:fresh to rebuild the whole database on purpose.
Modules and the application share Laravel's migration table and batches. A rollback reverts only this module's migrations of the last batch (or of the last --step migrations), and foreign keys between modules are not followed: roll back dependent modules first.
#Routes And Tests
#Routes
module:routes lists the routes a module owns: those loaded from its route files, and those whose controller is in the module namespace (1.x modules). A route name prefix is not ownership.
php artisan module:routesphp artisan module:routes Shop --method=GETphp artisan module:routes Shop --jsonphp artisan module:routes --compactphp artisan module:routes --columns=uri,middleware --sort=uri --reverseA module includes the routes of its children. Ownership survives route:cache.
| Option | Description |
|---|---|
--method= | Only the routes answering this method. |
--compact, -c | Only the module, method, URI and action columns. |
--columns= | The columns to show: module, domain, method, uri, name, action, middleware (repeat it or separate with commas). |
--sort= | The column to sort by; module by default. |
--reverse, -r | Reverse the order. |
--json | Output JSON, limited to the chosen columns. |
#Tests
module:test runs the module's tests directory with Pest (when vendor/bin/pest exists) or PHPUnit, and returns their exit code.
php artisan module:test Shopphp artisan module:test Shop --filter=CartTest --stop-on-failurephp artisan module:test Shop --listphp artisan module:test Shop --coveragephp artisan module:test Shop --parallel --profile # Pest onlyArguments are passed to the runner as a list, never through a shell. The runner uses the application's phpunit.xml, so module tests extend the application's Tests\TestCase and get its environment.
#Running Module Tests With The Application's Suite
Laravel's phpunit.xml only lists tests/Unit and tests/Feature, so vendor/bin/phpunit alone skips module tests. Add a suite for the local pool; nested modules are included:
1<testsuite name="Modules">2 <directory suffix="Test.php">./Modules</directory>3</testsuite>Then vendor/bin/phpunit runs everything, and vendor/bin/phpunit --testsuite Modules runs only module tests.
Pest reads the same phpunit.xml, so vendor/bin/pest --testsuite Modules works too.
#Pest
The generators write Pest tests when vendor/bin/pest exists, unless you pass --phpunit. Install Pest 1:
composer require --dev pestphp/pest:^1.23 pestphp/pest-plugin-laravel:^1.4 -Wphp artisan pest:installtests/Pest.php binds Tests\TestCase to tests/Feature only, and module tests live in the module. So a module's Pest feature test binds it itself, and the generators write it that way:
1<?php2 3uses(Tests\TestCase::class);4 5test('the cart page answers', function () {6 $this->get('/cart')->assertOk();7});Unit tests (--unit) do not. Do not also bind module folders in tests/Pest.php: Pest refuses a test case bound twice.
#Deployment And Autoloading
#The Module Manifest
Discovery is cached in bootstrap/cache/modulator.php: pools, sources, a class map per module and the diagnostics. In development it is rebuilt when the pools, the installed packages or the module directories change. In production, build it once per deployment.
composer install --no-dev --optimize-autoloader # or --classmap-authoritativephp artisan module:cachephp artisan config:cachephp artisan route:cachephp artisan queue:restartphp artisan optimize also runs module:cache, and optimize:clear runs module:clear. module:cache fails, and writes nothing, when discovery finds an error.
#Composer Modes
| Composer mode | Module classes |
|---|---|
| Default | Found through the module class map and PSR-4 prefixes; new classes work at once. |
--optimize | Same. |
--classmap-authoritative | Only classes in a class map load. Run module:cache after adding module classes. |
The manifest holds absolute paths, like Laravel's configuration cache: build it on the server path that runs it.
#Long-Running Workers
Modules are resolved once, when the application boots: discovery, the module class maps, providers, routes, config and helpers.php. A process that keeps the application booted keeps that state until it restarts. After publishing, deleting, enabling or disabling a module, run php artisan queue:restart, and rebuild route and config caches if you use them.
#Octane
Octane needs Laravel 8 or later. The module state is read-only after boot and holds no request data, so it is safe to share between requests. Two things to know:
- After publishing, deleting, enabling or disabling a module, run
php artisan octane:reload. The commands remind you when Octane is installed. octane:start --watchdoes not watch the local pool. Add it towatchinconfig/octane.php:
1'watch' => [2 'app',3 'bootstrap',4 'config/**/*.php',5 'database/**/*.php',6 'Modules',7 // ...8],The 1.x pool (app/Modules) is already watched through app. A package pool lives in vendor/ and changes with composer.lock, which Octane watches.
#Commands
| Command | Description |
|---|---|
module:discover | Discover again, rebuild the manifest and list the modules. |
module:cache | Rebuild the manifest; fails on any error. |
module:clear | Delete the manifest. |
#Diagnostics
#module:doctor
Checks source collisions, discovery and cache state, statuses, dependencies, providers, autoloading and deployment, and exits with 1 when it finds an error.
php artisan module:doctorIt reports, among others: equal-priority sources, invalid identities, missing or cyclic dependencies, a cached manifest that is out of date (an error when Composer's class map is authoritative), providers in app/Providers that are not registered automatically, a conventional provider file that does not declare its class, Composer mappings to shadowed copies, published copies whose package changed since (module.lock), discovery caching off in production, and a config file changed after config:cache.
#module:graph
Shows the hierarchy and dependencies.
php artisan module:graphphp artisan module:graph --format=json1Catalog [enabled]2Shop [enabled] -> needs Catalog3└─ Shop/Orders [enabled]The JSON output lists modules and edges (parent and dependency edges, with missing for unknown dependencies), ready for CI.
#module:check
A static check of the class references between modules. It reads each module's PHP files (not its tests or child modules) and enforces:
- a module uses another module only when it declares it in
dependencies, or when it is one of its ancestors; - a parent does not use its own child modules;
- when a module declares
exposes, others use only classes in those namespaces.
php artisan module:checkphp artisan module:check Shopphp artisan module:check --jsonImports, fully qualified and qualified class names are checked. Names built at runtime (strings, container keys, dynamic calls) are not seen.
#Command Reference
| Command | Description |
|---|---|
module:make {module} {--plain} | Create a module in the generation pool. |
module:make:<type> {module} {name?} | Create a class in a module (see Generators). |
module:delete {module} {--with-children} {--dry-run} {--force} | Delete an application module directory. |
module:list | List the modules with status, pool, package and path. |
module:enable {module?} {--with-parents} {--with-dependencies} {--force} | Remove a module from disabled. |
module:disable {module?} {--cascade} {--force} | Add a module to disabled. |
module:status {module?} | Configured and effective state, with reasons. |
module:use {module?} {--clear} | Select the module for your console. |
module:current | Show the selected module. |
module:pools | List the pools, highest priority first. |
module:source {module} | The active and shadowed copies of a module. |
module:publish {module} {--with-children} {--dry-run} {--force} | Copy a package module into the local pool. |
module:discover | Rebuild the manifest and list the modules. |
module:cache | Rebuild the manifest; fails on errors. |
module:clear | Delete the manifest. |
module:doctor | Check the whole setup. |
module:graph {--format=text} | Hierarchy and dependencies, as text or JSON. |
module:check {module?} {--json} | Static boundary check. |
module:migrate, :rollback, :status, :reset, :refresh | Module migrations (see Database Commands). |
module:seed {module?} {--class=} | Run a module seeder. |
module:test {module?} | Run the module tests. |
module:routes {module?} {--method=} {--compact} {--columns=*} {--sort=} {--reverse} {--json} | The routes modules own. |
Every command that takes a module accepts a nested identity such as Commerce/Checkout, and rejects invalid ones (.., lowercase, separators). Commands exit with 0 on success and 1 when they refuse; module:test returns the test runner's exit code.
#API Reference
#Modules Facade
Pharaonic\Laravel\Modulator\Facades\Modules resolves the ModuleRegistry.
| Method | Description | Returns |
|---|---|---|
Modules::all() | Every resolved module, enabled or not, by identity | array<string, Module> |
Modules::enabled() | The enabled modules, parents and dependencies first | array<string, Module> |
Modules::find($id) | The module with this identity | ?Module |
#Module
Pharaonic\Laravel\Modulator\Module
| Method | Description | Returns |
|---|---|---|
id() | The identity, e.g. Commerce/Checkout | string |
name() | The last segment, e.g. Checkout | string |
namespace() | The namespace root, e.g. Modules\Commerce\Checkout | string |
slug() | The view, translation and config namespace, e.g. commerce-checkout | string |
path($path = null) | The module root, or a path inside it | string |
pool() | The pool it was resolved from | string |
package() | The Composer package that provides it, or null | ?string |
parent() | The identity of the nearest ancestor module, or null | ?string |
children() | Identities of its child modules | list<string> |
dependencies() | Identities declared in module.php | list<string> |
isEnabled() | Whether it is effectively enabled | bool |
disabledReason() | Why it is disabled, or null | ?string |
#Helpers
| Helper | Description |
|---|---|
module_path($module, $path = null) | The root of a module, or a path inside it. Throws InvalidArgumentException for an invalid or unknown identity. |
module_config_path($module, $path = null) | <module>/config/... |
module_database_path($module, $path = null) | <module>/database/... |
module_resource_path($module, $path = null) | <module>/resources/... |
module_path() without a module returns app/Modules (the 1.x behaviour) and is deprecated.
#Contracts\Pool
| Method | Returns |
|---|---|
name() | string |
priority() | int |
path() | string |
namespace() | string |
package() | ?string |
DirectoryPool is the default implementation, built from each pools entry.
#Publish Tags
pharaonic, laravel-modulator, pharaonic-config, modulator-config. The 1.x tags config and modulator still work and are deprecated.
#Upgrading From 1.x
Version 8.0.0 replaces 1.x on Laravel 8 (each Laravel major has its own line, from 6.0.0 on Laravel 6). Existing app/Modules modules keep working through the app pool (1.x layout). Move them to the new layout when you want; nothing is rewritten for you.
#Required Changes
- Require the new version:
composer require pharaonic/laravel-modulator:^8.0(use the line of your Laravel major). App\Modules\ServiceProvider(the base class 1.x generated) must extendIlluminate\Support\ServiceProvider:Core\ServiceProvideris removed, and Modulator loads module resources itself.- Replace the removed helpers:
modules()→Modules::all(),getModuleDirectories()→Modules::find($id)->children(),studlyToSlug()→Modules::find($id)->slug(),getFiles()→ theFilefacade. - If you published the 1.x config, publish the new one (
--tag=modulator-config); it lives inconfig/pharaonic/modulator.php. - On deployment, add
php artisan module:cacheaftercomposer install.
#Before And After
| 1.x | 8.0.0 |
|---|---|
app/Modules/Shop, App\Modules\Shop\... | Modules/Shop/app, Modules\Shop\... (1.x layout still supported) |
A module is a folder with Providers/ | A module is a folder with app/ (the app pool keeps the 1.x rule) |
Every provider in Providers/ registered | One conventional <Name>ServiceProvider (1.x modules: every provider, as before) |
module:make Shop → app/Modules/Shop | module:make Shop → Modules/Shop, new layout |
module:make:* → 1.x folders | Laravel folders in new modules; 1.x folders in 1.x modules |
module:migrate:fresh | Removed: use module:migrate:refresh |
module:make:translatable | Removed: use module:make:model and module:make:migration with the laravel-translatable docs |
module:make:enum | Not on this line: enums need PHP 8.1, and this line runs on PHP 8.0 |
module:routes by name prefix | By real ownership |
module:seed Shop → App\Modules\Shop\database\seeders\DatabaseSeeder | Same for 1.x modules; Modules\Shop\Database\Seeders\DatabaseSeeder for new ones |
modules(), getFiles(), getModuleDirectories(), studlyToSlug() | Removed |
| Disabled state: none | pharaonic.modulator.disabled, module:enable, module:disable |
#Moving A Module To The New Layout
There is no automatic conversion: a namespace change touches your code. For each module:
php artisan module:make Shop --plaincreatesModules/Shopwithapp/Providers/ShopServiceProvider.php.- Move the class folders (
Http,Models, ...) intoModules/Shop/app, anddatabase,resources,routes,config,langtoModules/Shop. - Replace
App\Modules\Shop\withModules\Shop\in the module and in the code that uses it; database classes becomeModules\Shop\Database\Factories\andModules\Shop\Database\Seeders\. - Remove the module's own
RouteServiceProvider:routes/web.phpandroutes/api.phpload automatically. Move other provider code intoShopServiceProvider. - Move
Commands/toapp/Console/Commandswith theModules\Shop\Console\Commandsnamespace. - Delete
app/Modules/Shop, then runphp artisan module:doctorand your tests.
Keep only one copy at a time: Modules/Shop (priority 100) shadows app/Modules/Shop (priority 90), so a half-moved module runs from the new copy only.
#Examples
#1. A Module With A Route, A View And A Model
1use Illuminate\Support\Facades\Route;2use Modules\Shop\Http\Controllers\ProductController;3 4Route::get('/shop', [ProductController::class, 'index'])->name('shop.index'); 1namespace Modules\Shop\Http\Controllers; 2 3use Illuminate\Routing\Controller; 4use Modules\Shop\Models\Product; 5 6class ProductController extends Controller 7{ 8 public function index() 9 {10 return view('shop::products.index', ['products' => Product::all()]);11 }12}1@foreach ($products as $product)2 <p>{{ $product->name }}</p>3@endforeach#2. Override A Module From A Package
composer require acme/shopphp artisan module:source Shop # active: acme/shopphp artisan module:publish Shopphp artisan module:source Shop # active: local, shadowed: acme/shopChange Modules/Shop freely; composer update never touches it.
#3. A Public Contract Between Modules
1return ['exposes' => ['Contracts']];1return ['dependencies' => ['Catalog']];php artisan module:checkShop may use Modules\Catalog\Contracts\...; using Modules\Catalog\Models\Product fails the check.
#4. Switch A Feature Off
php artisan module:disable Analyticsphp artisan config:cachephp artisan queue:restart#5. Deploy With An Authoritative Class Map
composer install --no-dev --classmap-authoritativephp artisan optimize # caches config, routes and the module manifest#Troubleshooting
#A module class is not found in production
Composer's class map is authoritative and the class was added after the last module:cache. Run php artisan module:cache (or optimize) during deployment. module:doctor reports this case.
#module:cache fails with "Composer maps [...]"
A package autoloads its own module namespace in its composer.json, so Composer would load a shadowed copy. Remove that autoload entry from the package; Modulator autoloads package modules itself.
#"is provided with the same priority by pools [...]"
Two pools hold the same identity with the same priority. Change one pool's priority or remove one copy.
#module:enable says the module cannot be enabled
Its parent or a dependency is disabled; the command prints the chain. Use --with-parents or --with-dependencies, or enable the blocking module first.
#The disabled list "cannot be edited safely"
disabled is computed (env(), explode(), a variable). Edit config/pharaonic/modulator.php by hand, or make the list literal.
#The state did not change after module:disable
The configuration is cached or a worker is still running. Run php artisan config:cache, then restart queue workers, and run php artisan octane:reload if you use Octane.
#module:make:model Product says "Give the module identity"
The selected module is used only on interactive consoles outside CI and production. Pass the module: module:make:model Shop Product.
#A second provider in app/Providers does nothing
Only <Name>ServiceProvider is registered automatically. Register the other provider from it with $this->app->register(...).
Contributors
Amazing people who made this package possible
This package wouldn't exist without the contributions of our amazing community. A huge thank you to everyone who has helped improve Laravel Modulator!
Want to Contribute?
We welcome contributions from everyone! Whether it's bug fixes, new features, or documentation improvements - every contribution counts.
Was this page helpful?
Thanks, that helps us decide what to improve.
Something wrong or missing? Report it on GitHub .