# Laravel Modulator documentation (v6.x)

> Canonical: https://pharaonic.dev/packages/laravel/modulator/6.x  
> Version: v6.x (latest release 6.0.1, 2026-11-21)  
> Install: composer require pharaonic/laravel-modulator  
> Requires: PHP 8.0, Laravel 6  
> Repository: https://github.com/Pharaonic/laravel-modulator  
> All versions: https://pharaonic.dev/packages/laravel/modulator/6.x.md

:::badges
- Laravel Package {color=blue}
- v6.0.1 {color=green}
- MIT License {color=purple}
:::

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

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

:::info 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
- Laravel >= 6.20

### Composer Installation

```bash title="Terminal" no-line-numbers
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.

```bash title="Terminal" no-line-numbers
php artisan vendor:publish --tag=modulator-config
```

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

### Create Your First Module

```bash title="Terminal" no-line-numbers
php artisan module:make Shop
```

:::success 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`).

```php title="config/pharaonic/modulator.php"
return [
    'disabled' => [
        // 'Shop/Orders',
    ],

    'pools' => [
        'local' => [
            'path' => base_path('Modules'),
            'namespace' => 'Modules',
            'priority' => 100,
        ],
        'app' => [
            'path' => app_path('Modules'),
            'namespace' => 'App\\Modules',
            'priority' => 90,
            'legacy' => true,
        ],
    ],

    'discovery' => [
        'cache' => true,
    ],

    'generation' => [
        'pool' => 'local',
        'stubs' => null,
    ],
];
```

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

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

```php title="app/Modules/TenantPool.php"
use Pharaonic\Laravel\Modulator\Contracts\Pool;

final class TenantPool implements Pool
{
    public function name(): string { return 'tenant'; }
    public function priority(): int { return 80; }
    public function path(): string { return storage_path('tenant/modules'); }
    public function namespace(): string { return 'Tenant\\Modules'; }
    public function package(): ?string { return null; }
}
```

```php title="config/pharaonic/modulator.php"
'pools' => [
    // ...
    'tenant' => App\Modules\TenantPool::class,
],
```

## Basic Usage

Create a module, add a class, and use it. Nothing needs to be registered in `composer.json`.

```bash title="Terminal" no-line-numbers
php artisan module:make Shop
php artisan module:make:model Shop Product --migration
```

```php title="Modules/Shop/app/Models/Product.php"
namespace Modules\Shop\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    //
}
```

```php title="Anywhere in the application"
use Modules\Shop\Models\Product;
use Pharaonic\Laravel\Modulator\Facades\Modules;

Product::query()->get();

Modules::find('Shop')->isEnabled(); // true
Modules::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`.

:::tip
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.

```text title="Layout" no-copy
Modules/
├── Shop/                         Shop (module)
│   ├── app/                      Modules\Shop\
│   │   ├── Models/Product.php    Modules\Shop\Models\Product
│   │   └── Providers/ShopServiceProvider.php
│   ├── database/{migrations,factories,seeders}/
│   ├── resources/{views,lang}/
│   ├── routes/{web.php,api.php}
│   ├── tests/
│   ├── helpers.php               optional
│   ├── module.php                optional
│   ├── module.lock               only in a published copy (module:publish)
│   └── Modules/                  only when it has child modules
│       └── Orders/app/           Shop/Orders → Modules\Shop\Orders\
└── Platform/                     namespace group (no app/)
    └── 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.

:::warning
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`.

```php title="Modules/Shop/helpers.php"
<?php

if (! function_exists('shop_currency')) {
    function shop_currency(): string
    {
        return config('modules.shop.store.currency', 'EGP');
    }
}
```

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

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

```bash title="Terminal" no-line-numbers
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.

```php title="Modules/Shop/module.php"
return [
    'dependencies' => ['Catalog', 'Commerce/Checkout'],
    'exposes' => ['Contracts', 'Events'],
];
```

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

:::warning
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.

```json title="vendor/acme/shop/composer.json"
{
    "name": "acme/shop",
    "extra": {
        "pharaonic": {
            "modulator": {
                "pools": [
                    { "path": "modules" }
                ]
            }
        }
    }
}
```

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

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

```bash title="Terminal" no-line-numbers
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.

```bash title="Terminal" no-line-numbers
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.

```json title="Modules/Shop/Modules/Orders/module.lock"
{
    "module": "Shop/Orders",
    "package": "acme/shop",
    "version": "1.0.0",
    "reference": "4f2c1e0",
    "children": false,
    "files": {
        "app/Models/Order.php": "9a8b…",
        "routes/web.php": "1c2d…"
    }
}
```

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.

```text title="php artisan module:doctor" no-copy
[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:

```bash title="Terminal" no-line-numbers
php artisan module:delete Shop --force
```

:::warning
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.

```bash title="Terminal" no-line-numbers
php artisan module:disable Shop
php artisan module:enable Commerce/Checkout
php artisan module:status
php 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:

```text title="php artisan module:status Shop/Orders" no-copy
Module:     Shop/Orders
Configured: enabled
Effective:  disabled
  Shop/Orders: Disabled because its parent [Shop] is disabled.
  Shop: Disabled in configuration (pharaonic.modulator.disabled).
```

:::warning 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.
:::

:::info 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.

```bash title="Terminal" no-line-numbers
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`.

```bash title="Terminal" no-line-numbers
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.

| Command | Writes to | Options |
| --- | --- | --- |
| `module:make:action` | `app/Actions` | |
| `module:make:channel` | `app/Broadcasting` | |
| `module:make:class` | `app` | `--invokable` |
| `module:make:command` | `app/Console/Commands` | `--command=`, 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:interface` | `app/Contracts` | |
| `module:make:job` | `app/Jobs` | `--sync`, tests |
| `module:make:job-middleware` | `app/Jobs/Middleware` | tests |
| `module:make:listener` | `app/Listeners` | `--event=`, `--queued`, tests |
| `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` |
| `module:make:notifications-table` | `notifications` |
| `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`).

:::warning
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.

```bash title="Terminal" no-line-numbers
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:

```php title="config/pharaonic/modulator.php"
'generation' => [
    'pool' => 'local',
    'stubs' => base_path('resources/stubs/modules'),
],
```

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.

```php title="stubs/modulator/service.stub"
<?php

namespace {{ namespace }};

final class {{ class }}
{
    //
}
```

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` (Laravel 8+): `Modules\Shop\Models\Product` uses `Modules\Shop\Database\Factories\ProductFactory`. On Laravel 6 and 7, module `database/factories` closures are loaded.

## Database Commands

Each command runs Laravel's own command limited to the module's `database/migrations`.

```bash title="Terminal" no-line-numbers
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
```

| 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 `\`.

:::danger 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.
:::

:::warning 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.

```bash title="Terminal" no-line-numbers
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`.

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

```bash title="Terminal" no-line-numbers
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:

```xml title="phpunit.xml"
<testsuite name="Modules">
    <directory suffix="Test.php">./Modules</directory>
</testsuite>
```

Then `vendor/bin/phpunit` runs everything, and `vendor/bin/phpunit --testsuite Modules` runs only module tests.

:::note
Pest cannot be installed with Laravel 6: every Pest release needs a newer `nunomaduro/collision` than Laravel 6 allows. On this line, tests are PHPUnit tests, and `--pest` refuses to write a Pest file.
:::

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

```bash title="Deployment" no-line-numbers
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 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 --watch` does not watch the local pool. Add it to `watch` in `config/octane.php`:

```php title="config/octane.php"
'watch' => [
    'app',
    'bootstrap',
    'config/**/*.php',
    'database/**/*.php',
    'Modules',
    // ...
],
```

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.

```bash title="Terminal" no-line-numbers
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.

```bash title="Terminal" no-line-numbers
php artisan module:graph
php artisan module:graph --format=json
```

```text title="php artisan module:graph" no-copy
Catalog [enabled]
Shop [enabled] -> needs Catalog
└─ 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.

```bash title="Terminal" no-line-numbers
php artisan module:check
php artisan module:check Shop
php artisan module:check --json
```

:::info Limits
Imports, 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/...` |

:::warning
`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 6.0.0 replaces 1.x. 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:^6.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.x | 6.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:make:cast`, `module:make:component` | Not on this line: custom casts and Blade components need Laravel 7 |
| `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:

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.

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

- ===Route

  ```php title="Modules/Shop/routes/web.php"
  use Illuminate\Support\Facades\Route;
  use Modules\Shop\Http\Controllers\ProductController;

  Route::get('/shop', [ProductController::class, 'index'])->name('shop.index');
  ```

- ===Controller

  ```php title="Modules/Shop/app/Http/Controllers/ProductController.php"
  namespace Modules\Shop\Http\Controllers;

  use Illuminate\Routing\Controller;
  use Modules\Shop\Models\Product;

  class ProductController extends Controller
  {
      public function index()
      {
          return view('shop::products.index', ['products' => Product::all()]);
      }
  }
  ```

- ===View

  ```blade title="Modules/Shop/resources/views/products/index.blade.php"
  @foreach ($products as $product)
      <p>{{ $product->name }}</p>
  @endforeach
  ```

### 2. Override A Module From A Package

```bash title="Terminal" no-line-numbers
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

- ===Catalog

  ```php title="Modules/Catalog/module.php"
  return ['exposes' => ['Contracts']];
  ```

- ===Shop

  ```php title="Modules/Shop/module.php"
  return ['dependencies' => ['Catalog']];
  ```

- ===CI

  ```bash title="Terminal" no-line-numbers
  php artisan module:check
  ```

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

### 4. Switch A Feature Off

```bash title="Terminal" no-line-numbers
php artisan module:disable Analytics
php artisan config:cache
php artisan queue:restart
```

### 5. Deploy With An Authoritative Class Map

```bash title="Deployment" no-line-numbers
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(...)`.
