Skip to content
Laravel Packagev8.0.0MIT License

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.

Quick Tip

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

Terminal
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.

Terminal
php artisan vendor:publish --tag=modulator-config

The file is written to config/pharaonic/modulator.php.

#Create Your First Module

Terminal
php artisan module:make Shop
Installation Complete

You'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).

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];
KeyDefaultDescription
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.
poolslocal, appDirectories 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.cachetrueKeep the discovery result in bootstrap/cache/modulator.php.
generation.poollocalThe pool module:make and module:publish write to. It must be an application pool with the app/ layout.
generation.stubsnullA 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:

app/Modules/TenantPool.php
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}
config/pharaonic/modulator.php
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.

Terminal
php artisan module:make Shop
php artisan module:make:model Shop Product --migration
Modules/Shop/app/Models/Product.php
1namespace Modules\Shop\Models;
2 
3use Illuminate\Database\Eloquent\Model;
4 
5class Product extends Model
6{
7 //
8}
Anywhere in the application
1use Modules\Shop\Models\Product;
2use Pharaonic\Laravel\Modulator\Facades\Modules;
3 
4Product::query()->get();
5 
6Modules::find('Shop')->isEnabled(); // true
7Modules::find('Shop')->path('routes/web.php'); // ".../Modules/Shop/routes/web.php"

#What A Module Loads

ConventionLoaded as
app/Providers/<Name>ServiceProvider.phpThe module service provider (optional; only this one is registered automatically)
config/*.phpconfig('modules.<slug>.<file>')
resources/viewsview('<slug>::name')
lang or resources/lang__('<slug>::file.key'), plus JSON translations
database/migrationsRun by php artisan migrate
database/factories, database/seedersModules\Shop\Database\Factories\, Modules\Shop\Database\Seeders\
routes/web.phpThe web middleware group
routes/api.phpThe api middleware group and the api prefix
routes/console.php, app/Console/CommandsRegistered in the console
testsModules\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.

Layout
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 optional
11│ ├── module.php optional
12│ ├── module.lock only in a published copy (module:publish)
13│ └── Modules/ only when it has child modules
14│ └── 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. Modules is reserved.
  • At most 16 levels.
  • The namespace is the pool namespace followed by the segments: Commerce/Checkout is Modules\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.

Modules/Shop/helpers.php
1<?php
2 
3if (! function_exists('shop_currency')) {
4 function shop_currency(): string
5 {
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.

ClassName
Modules\Shop\Http\Livewire\Cartshop::cart
Modules\Shop\Http\Livewire\Admin\UserTableshop::admin.user-table
Modules\Shop\Orders\Http\Livewire\OrderListshop-orders::order-list
Blade
1<livewire:shop::cart />
2@livewire('shop::admin.user-table')
  • Only enabled modules register components; abstract classes and classes that are not Livewire\Component are 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:

DirectoryRegistered as
app/Filament/Resourcesresources (their pages, relation managers and widgets too)
app/Filament/Pagespages
app/Filament/Widgetsdashboard 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).

Terminal
php artisan module:make Commerce
php 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/Checkout under a package Commerce.

#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.

Modules/Shop/module.php
1return [
2 'dependencies' => ['Catalog', 'Commerce/Checkout'],
3 'exposes' => ['Contracts', 'Events'],
4];
KeyDescription
dependenciesModule identities this module needs. A missing, disabled or cyclic dependency disables the module, with the reason.
exposesNamespaces, 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.

PoolPathNamespacePriority
localModules/Modules100
app (1.x layout)app/Modules/App\Modules90
Packagesdeclared by each packageModules by default50 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.

vendor/acme/shop/composer.json
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).

Do not autoload package modules yourself

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:

Terminal
php artisan module:pools
php 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.

Terminal
php artisan module:publish Shop --dry-run
php artisan module:publish Shop
php artisan module:publish Shop/Orders # one child only
php artisan module:publish Shop --with-children
php 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; --force replaces it and keeps the old copy in storage/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.

Modules/Shop/Modules/Orders/module.lock
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.
php artisan module:doctor
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:

Terminal
php artisan module:delete Shop --force

Restart 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.

Terminal
php artisan module:disable Shop
php artisan module:enable Commerce/Checkout
php artisan module:status
php artisan module:status Commerce/Checkout

#Rules

SituationResult
Disable a parentIts children are disabled too; the config lists only the parent.
Enable a child of a disabled parentRefused. Add --with-parents to enable the parents too.
Enable a module whose dependency is disabledRefused. Add --with-dependencies.
Disable a module others depend onRefused, with the list. --cascade disables them too (confirm, or add --force).
ProductionAsks for confirmation; --force skips it.

#Configured And Effective State

module:status shows both, with the chain of reasons:

php artisan module:status Shop/Orders
1Module: Shop/Orders
2Configured: enabled
3Effective: disabled
4 Shop/Orders: Disabled because its parent [Shop] is disabled.
5 Shop: Disabled in configuration (pharaonic.modulator.disabled).
Computed lists are not edited

When disabled is computed (for example explode(',', env('MODULES_DISABLED'))), the commands refuse and leave the file untouched. Edit it by hand.

Cached configuration

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.

Terminal
php artisan module:use Shop/Products
php artisan module:make:model Product # Shop/Products
php artisan module:make:model Blog Post # the explicit module wins
php artisan module:current
php artisan module:use --clear

Resolution 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 CI is 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.

Terminal
php artisan module:make Shop
php artisan module:make Shop/Orders --plain
php artisan module:make:controller Shop ProductController --resource --model=Product
php artisan module:make:model Shop Product --all
php artisan module:make:migration Shop create_products_table --create=products

#Generator Types

There is a module:make:* command for every make:* command of Laravel.

CommandWrites toOptions
module:make:actionapp/Actions
module:make:castapp/Casts--inbound
module:make:channelapp/Broadcasting
module:make:classapp--invokable
module:make:commandapp/Console/Commands--command=, tests
module:make:componentapp/View/Components + view--inline, --view (anonymous: only the view), --path=, tests
module:make:configconfig
module:make:controllerapp/Http/Controllers--api, --type=, --invokable, --model=, --parent=, --resource, --requests, tests
module:make:eventapp/Events
module:make:exceptionapp/Exceptions--render, --report
module:make:factorydatabase/factories--model=
module:make:filament-resourceapp/Filament/Resources + its pages--model=, --simple, --view, --soft-deletes, --generate; needs filament/filament
module:make:interfaceapp/Contracts
module:make:jobapp/Jobs--sync, --batched, tests
module:make:job-middlewareapp/Jobs/Middlewaretests
module:make:listenerapp/Listeners--event=, --queued, tests
module:make:livewireapp/Http/Livewire + resources/views/livewire--inline, tests (Livewire::test); needs livewire/livewire
module:make:mailapp/Mail--markdown[=view], --view[=view], tests
module:make:middlewareapp/Http/Middlewaretests
module:make:migrationdatabase/migrations--create=, --table=, --fullpath (runs Laravel's make:migration)
module:make:modelapp/Models--all, --controller, --factory, --migration, --morph-pivot, --policy, --seed, --pivot, --resource, --api, --requests, tests
module:make:notificationapp/Notifications--markdown[=view], tests
module:make:observerapp/Observers--model=
module:make:policyapp/Policies--model=, --guard=
module:make:providerapp/Providers
module:make:requestapp/Http/Requests
module:make:resourceapp/Http/Resources--collection
module:make:ruleapp/Rules--implicit
module:make:scopeapp/Models/Scopes
module:make:seederdatabase/seeders
module:make:serviceapp/Services
module:make:testtests/Feature or tests/Unit--unit, --pest, --phpunit
module:make:traitapp/Concerns (traits are concerns, as in Laravel)
module:make:viewresources/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

CommandTable
module:make:cache-tablecache, cache_locks
module:make:notifications-tablenotifications
module:make:queue-batches-tablejob_batches
module:make:queue-failed-tablefailed_jobs
module:make:queue-tablejobs
module:make:session-tablesessions

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.

Terminal
php artisan vendor:publish --tag=modulator-stubs

stubs/modulator is used automatically while generation.stubs is null. To keep the stubs elsewhere, point generation.stubs at that directory:

config/pharaonic/modulator.php
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.

stubs/modulator/service.stub
1<?php
2 
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.

Terminal
php artisan module:migrate Shop
php artisan module:migrate:status Shop
php artisan module:migrate:rollback Shop --step=1
php artisan module:migrate:reset Shop
php artisan module:migrate:refresh Shop --seed
php artisan module:migrate:refresh Shop --seeder=DemoSeeder
php artisan module:seed Shop --class=ProductSeeder
CommandOptions
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 \.

module:migrate:fresh is removed

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.

Shared migration table

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.

Terminal
php artisan module:routes
php artisan module:routes Shop --method=GET
php artisan module:routes Shop --json
php artisan module:routes --compact
php artisan module:routes --columns=uri,middleware --sort=uri --reverse

A module includes the routes of its children. Ownership survives route:cache.

OptionDescription
--method=Only the routes answering this method.
--compact, -cOnly 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, -rReverse the order.
--jsonOutput 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.

Terminal
php artisan module:test Shop
php artisan module:test Shop --filter=CartTest --stop-on-failure
php artisan module:test Shop --list
php artisan module:test Shop --coverage
php artisan module:test Shop --parallel --profile # Pest only

Arguments 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:

phpunit.xml
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:

Terminal
composer require --dev pestphp/pest:^1.23 pestphp/pest-plugin-laravel:^1.4 -W
php artisan pest:install

tests/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:

Modules/Shop/tests/Feature/CartTest.php
1<?php
2 
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.

Deployment
composer install --no-dev --optimize-autoloader # or --classmap-authoritative
php artisan module:cache
php artisan config:cache
php artisan route:cache
php artisan queue:restart

php 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 modeModule classes
DefaultFound through the module class map and PSR-4 prefixes; new classes work at once.
--optimizeSame.
--classmap-authoritativeOnly 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 --watch does not watch the local pool. Add it to watch in config/octane.php:
config/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

CommandDescription
module:discoverDiscover again, rebuild the manifest and list the modules.
module:cacheRebuild the manifest; fails on any error.
module:clearDelete 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.

Terminal
php artisan module:doctor

It 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.

Terminal
php artisan module:graph
php artisan module:graph --format=json
php artisan module:graph
1Catalog [enabled]
2Shop [enabled] -> needs Catalog
3└─ 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:

  1. a module uses another module only when it declares it in dependencies, or when it is one of its ancestors;
  2. a parent does not use its own child modules;
  3. when a module declares exposes, others use only classes in those namespaces.
Terminal
php artisan module:check
php artisan module:check Shop
php artisan module:check --json
Limits

Imports, fully qualified and qualified class names are checked. Names built at runtime (strings, container keys, dynamic calls) are not seen.

#Command Reference

CommandDescription
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:listList 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:currentShow the selected module.
module:poolsList 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:discoverRebuild the manifest and list the modules.
module:cacheRebuild the manifest; fails on errors.
module:clearDelete the manifest.
module:doctorCheck 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, :refreshModule 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.

MethodDescriptionReturns
Modules::all()Every resolved module, enabled or not, by identityarray<string, Module>
Modules::enabled()The enabled modules, parents and dependencies firstarray<string, Module>
Modules::find($id)The module with this identity?Module

#Module

Pharaonic\Laravel\Modulator\Module

MethodDescriptionReturns
id()The identity, e.g. Commerce/Checkoutstring
name()The last segment, e.g. Checkoutstring
namespace()The namespace root, e.g. Modules\Commerce\Checkoutstring
slug()The view, translation and config namespace, e.g. commerce-checkoutstring
path($path = null)The module root, or a path inside itstring
pool()The pool it was resolved fromstring
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 moduleslist<string>
dependencies()Identities declared in module.phplist<string>
isEnabled()Whether it is effectively enabledbool
disabledReason()Why it is disabled, or null?string

#Helpers

HelperDescription
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

MethodReturns
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

  1. Require the new version: composer require pharaonic/laravel-modulator:^8.0 (use the line of your Laravel major).
  2. App\Modules\ServiceProvider (the base class 1.x generated) must extend Illuminate\Support\ServiceProvider: Core\ServiceProvider is removed, and Modulator loads module resources itself.
  3. Replace the removed helpers: modules() → Modules::all(), getModuleDirectories() → Modules::find($id)->children(), studlyToSlug() → Modules::find($id)->slug(), getFiles() → the File facade.
  4. If you published the 1.x config, publish the new one (--tag=modulator-config); it lives in config/pharaonic/modulator.php.
  5. On deployment, add php artisan module:cache after composer install.

#Before And After

1.x8.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/ registeredOne conventional <Name>ServiceProvider (1.x modules: every provider, as before)
module:make Shop → app/Modules/Shopmodule:make Shop → Modules/Shop, new layout
module:make:* → 1.x foldersLaravel folders in new modules; 1.x folders in 1.x modules
module:migrate:freshRemoved: use module:migrate:refresh
module:make:translatableRemoved: use module:make:model and module:make:migration with the laravel-translatable docs
module:make:enumNot on this line: enums need PHP 8.1, and this line runs on PHP 8.0
module:routes by name prefixBy real ownership
module:seed Shop → App\Modules\Shop\database\seeders\DatabaseSeederSame for 1.x modules; Modules\Shop\Database\Seeders\DatabaseSeeder for new ones
modules(), getFiles(), getModuleDirectories(), studlyToSlug()Removed
Disabled state: nonepharaonic.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:

  1. php artisan module:make Shop --plain creates Modules/Shop with app/Providers/ShopServiceProvider.php.
  2. Move the class folders (Http, Models, ...) into Modules/Shop/app, and database, resources, routes, config, lang to Modules/Shop.
  3. Replace App\Modules\Shop\ with Modules\Shop\ in the module and in the code that uses it; database classes become Modules\Shop\Database\Factories\ and Modules\Shop\Database\Seeders\.
  4. Remove the module's own RouteServiceProvider: routes/web.php and routes/api.php load automatically. Move other provider code into ShopServiceProvider.
  5. Move Commands/ to app/Console/Commands with the Modules\Shop\Console\Commands namespace.
  6. Delete app/Modules/Shop, then run php artisan module:doctor and 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

Modules/Shop/routes/web.php
1use Illuminate\Support\Facades\Route;
2use Modules\Shop\Http\Controllers\ProductController;
3 
4Route::get('/shop', [ProductController::class, 'index'])->name('shop.index');
Modules/Shop/app/Http/Controllers/ProductController.php
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}
Modules/Shop/resources/views/products/index.blade.php
1@foreach ($products as $product)
2 <p>{{ $product->name }}</p>
3@endforeach

#2. Override A Module From A Package

Terminal
composer require acme/shop
php artisan module:source Shop # active: acme/shop
php artisan module:publish Shop
php artisan module:source Shop # active: local, shadowed: acme/shop

Change Modules/Shop freely; composer update never touches it.

#3. A Public Contract Between Modules

Modules/Catalog/module.php
1return ['exposes' => ['Contracts']];
Modules/Shop/module.php
1return ['dependencies' => ['Catalog']];
Terminal
php artisan module:check

Shop may use Modules\Catalog\Contracts\...; using Modules\Catalog\Models\Product fails the check.

#4. Switch A Feature Off

Terminal
php artisan module:disable Analytics
php artisan config:cache
php artisan queue:restart

#5. Deploy With An Authoritative Class Map

Deployment
composer install --no-dev --classmap-authoritative
php 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!

Moamen Eltouny

@MoamenEltouny

132 contributions

Elsayed Elbeshry

@Elsayed93

11 contributions

Omar Attya Pero

@omar95-pero

2 contributions

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?

Something wrong or missing? Report it on GitHub .