DEV Community

Cover image for Installed Does Not Mean Enabled: Separating Package Installation from Application Composition in PHP
Vladyslav
Vladyslav

Posted on

Installed Does Not Mean Enabled: Separating Package Installation from Application Composition in PHP

Coretsia Engineering Notes — 03

Different applications can share exactly the same Composer installation while requiring different sets of services. An HTTP application may need a request handler, a command-line application may need a command registry, and a scheduler may require command execution without exposing an HTTP entry point. If package discovery automatically enables every available module, the installed package inventory determines module activation rather than allowing each application to express its own composition.

The first two notes explored dependency ordering and enforceable package boundaries. The next question is what happens after dependencies are installed: which of their capabilities are actually part of a particular application?

1. Installation is not composition

Composer resolves package requirements and generates autoloading infrastructure. It can ensure that a package and its declared dependencies are available under the selected constraints. Its extra metadata can also carry information for tools that interpret it. But an ordinary library's presence does not, by itself, decide whether a framework should register its service providers, routes or background jobs. Those are application-level decisions. A framework may deliberately choose automatic registration, but that is a policy implemented above package installation, not a necessary consequence of installing a package.

There are at least three different questions to answer:

Layer Question
Package installation Which packages and versions are available?
Module selection and resolution Which modules are enabled for this application, including their required modules?
Runtime compatibility Can the selected composition execute in the intended environment?

A package can be installed without its module being selected, and a module can be selected even though its package is not installed. Even when a module is both available and enabled, it may require runtime capabilities that are not captured by ordinary Composer requirements. Composer can check declared PHP and extension constraints, but that is distinct from verifying the application's behavior in its intended runtime. This article focuses on module selection and resolution rather than implementing a runtime compatibility checker.

An explicit composition model is especially useful when several application targets share a single vendor/ directory. Physical installation may satisfy the combined needs of those targets, while each target retains its own smaller set of enabled modules. Treating that union as the activation list for every application loses the target-specific intent.

2. A minimal experiment

Consider three synthetic packages: acme/http, acme/console and acme/scheduler. The scheduler needs the console module. The root project requires HTTP and Scheduler, so Composer should resolve Console transitively. The application-level module relationship is declared separately in custom extra.demo metadata. Composer does not interpret that metadata as an activation instruction.

Physical package requirements:
  root -> acme/http
  root -> acme/scheduler -> acme/console

Application module requirement:
  scheduler -> console
Enter fullscreen mode Exit fullscreen mode

All three packages are available to the same project, but there are three desired application compositions:

Target Selected roots Enabled modules (dependency-first order)
Web http http
CLI console console
Scheduler scheduler console, scheduler

The labels in this example are illustrative, not names of actual Coretsia presets. The distinction is important: a package name identifies an installation unit, whereas a module identifier participates in the application's composition policy. We deliberately use one module per package to keep the example small; the two concepts remain distinct.

Each provider returns a service identifier instead of defining a real HTTP handler or scheduler. This makes activation observable without starting a web server or depending on a framework. The test can ask whether the provider actually ran, rather than merely whether its class is autoloadable. A plan is just an ordered mapping from enabled module identifiers to provider classes. The registration step consumes that plan.

3. Make activation an explicit decision

A naive implementation can treat every discovered module as a root. If the dependency graph is otherwise valid, the resulting plan includes HTTP, Console and Scheduler, and all three providers execute. That may be the intended policy in a single-purpose application. In a shared installation, however, it also invokes providers belonging to modules the target never selected.

Instead, pass an explicit root set to a resolver. The resolver walks only reachable module dependencies, rejects missing or explicitly excluded modules, and emits providers in dependency-first order. Sorting roots and each dependency list makes the traversal reproducible even if the package records arrive in another order. It is a deterministic depth-first topological traversal, not a global alphabetical sort of the final output. As in the first note, ordering must preserve the relationship between a dependent and its prerequisites.

The resolver receives metadata and produces data without constructing providers during traversal. This separation prevents a missing dependency from causing partial provider registration during graph resolution. In the implementation below, moduleIndex() builds an inventory of discovered modules, plan() computes the enabled closure, and registerProviders() applies the successfully resolved plan. These are deliberately small fixture functions rather than general-purpose package discovery or dependency-injection components. Provider execution itself can still fail; atomic service registration is outside the scope of this experiment.

plan.php:

<?php

declare(strict_types=1);

/** Index demo modules from package metadata, not from class discovery. */
function moduleIndex(array $packages): array
{
    $modules = [];
    foreach ($packages as $package) {
        $demo = $package['extra']['demo'] ?? null;
        if ($demo === null) {
            continue;
        }
        if (!is_array($demo)
            || !is_string($demo['module'] ?? null)
            || $demo['module'] === ''
            || !is_array($demo['requires'] ?? null)
            || !array_is_list($demo['requires'])
            || !is_string($demo['provider'] ?? null)
            || $demo['provider'] === '') {
            throw new LogicException('invalid-metadata');
        }
        $id = $demo['module'];
        if (isset($modules[$id])) {
            throw new LogicException("duplicate-module:$id");
        }
        foreach ($demo['requires'] as $dependency) {
            if (!is_string($dependency) || $dependency === '') {
                throw new LogicException('invalid-metadata');
            }
        }
        $modules[$id] = [
            'requires' => $demo['requires'],
            'provider' => $demo['provider'],
        ];
    }
    ksort($modules, SORT_STRING);

    return $modules;
}

/** Resolve selected roots and required modules, dependencies first. */
function plan(array $modules, array $roots, array $excluded = []): array
{
    $state = [];
    $ordered = [];
    $visit = function (string $id) use (
        &$visit, &$state, &$ordered, $modules, $excluded
    ): void {
        if (in_array($id, $excluded, true)) {
            throw new LogicException("excluded:$id");
        }
        if (!isset($modules[$id])) {
            throw new LogicException("missing:$id");
        }
        if (($state[$id] ?? 0) === 1) {
            throw new LogicException("cycle:$id");
        }
        if (($state[$id] ?? 0) === 2) {
            return;
        }
        $state[$id] = 1;
        $requires = $modules[$id]['requires'];
        sort($requires, SORT_STRING);
        foreach ($requires as $dependency) {
            $visit($dependency);
        }
        $state[$id] = 2;
        $ordered[$id] = $modules[$id]['provider'];
    };

    sort($roots, SORT_STRING);
    foreach ($roots as $root) {
        $visit($root);
    }

    return $ordered;
}

/** Apply only the resolved provider plan. */
function registerProviders(array $plan): array
{
    $services = [];
    foreach ($plan as $providerClass) {
        $service = (new $providerClass())->register();
        if (in_array($service, $services, true)) {
            throw new LogicException("duplicate-service:$service");
        }
        $services[] = $service;
    }

    return $services;
}
Enter fullscreen mode Exit fullscreen mode

The excluded input is a hard prohibition in this fixture: a selected root or a required dependency that is excluded causes resolution to fail. It is not a second way to silently remove graph edges. A missing module and a cycle also fail explicitly. The metadata checks are limited to the example's schema; a production resolver needs stronger validation, an explicit conflict policy and appropriate failure semantics.

4. What the experiment verifies

The test suite compares three plans obtained from the same inventory. It checks both the module identifiers in the plan and the exact service identifiers emitted by the providers. For the Web case, it additionally verifies that the Console and Scheduler provider classes have not been loaded in that process at that point. The default Composer-backed mode first checks that all three package identities are installed and that their provider files are autoloadable, without loading those provider classes. This illustrates the distinction between availability and activation without claiming that arbitrary installed PHP code can never execute.

The suite also tests the intentionally naive all-discovered policy and four negative graph cases. A missing required module is simulated by removing its descriptor from a copy of the inventory, and the cycle is introduced into another copy. Neither negative test edits the installed packages on disk. Each negative test must receive the exact expected diagnostic, not simply any exception.

I verified the complete experiment on Windows PowerShell 5.1 using PHP 8.4.24 and Composer 2.10.2. Composer reported that the root manifest was valid, with warnings about exact package version constraints, which are intentional in this controlled fixture. All three local packages were successfully installed through the path repository, and the source-fixture mode was independently verified on PHP 8.4.24. The Composer-backed verification completed successfully in two consecutive runs of the following command:

composer run matrix
Enter fullscreen mode Exit fullscreen mode

Verification script output:

Mode: Composer-installed metadata and autoloader
web: http.handler; inactive providers not loaded
cli: console.command
scheduler: console.command, scheduler.job
all-discovered: console.command, http.handler, scheduler.job
rejected: missing:missing
rejected: excluded:console
rejected: missing:console
rejected: cycle:scheduler
deterministic: reversed inventory and roots
Matrix PASS
Enter fullscreen mode Exit fullscreen mode

The observed results were:

Scenario Observed outcome
Web only http.handler; Console and Scheduler provider classes not loaded at this stage
CLI only console.command
Scheduler console.command, then scheduler.job
Enable all discovered modules all three service identifiers
Select absent module missing:missing
Exclude Console while selecting Scheduler excluded:console
Remove Console descriptor, select Scheduler missing:console
Introduce a Console–Scheduler cycle cycle:scheduler
Reverse package metadata order and selected root order identical ordered plan

The naive approach provides a control case: the same provider implementations can produce all three service identifiers. Their absence from the smaller compositions is therefore a consequence of module selection, not a missing class or a provider that cannot execute. The negative cases verify that the resolver rejects invalid selections instead of returning an incomplete provider plan.

The important result is not a reduction in the number of installed packages. All three simulated application targets were resolved sequentially in the same PHP process against the same Composer installation. The number and order of invoked providers depended on the selected roots and module requirements. This demonstrates why disabling a module for one target does not necessarily imply uninstalling its package: another target may still need it.

5. How Coretsia separates the two graphs

These are not merely abstract distinctions in the design of Coretsia, the PHP framework I am developing. In the repository snapshot reviewed for this article, the Kernel distinguishes pre-install planning, installed discovery, target-local selection and provider planning. The synthetic example is independent of Coretsia and simplifies its graph policy considerably.

The ModuleSelectionFactory combines preset-required modules, preset modules and explicit target inclusions into an effective root set, while retaining explicit exclusions. It rejects exclusion of preset-required modules and filters other excluded modules out of the root set before graph resolution. If an enabled module subsequently requires an excluded dependency, graph resolution fails. Unlike the simplified resolver in this article, Coretsia therefore applies exclusion policy at both the selection and graph resolution stages. The resulting selection does not depend on the installed manifest and is not itself a package installation request.

The ComposerManifestReader reads Composer installed metadata through its metadata provider. A package is classified as a Coretsia runtime module through a valid extra.coretsia.moduleId and kind: runtime. Module dependency and conflict relationships come from extra.coretsia.requires and extra.coretsia.conflicts, rather than Composer's package-level require and conflict declarations.

The ModuleResolutionOrchestrator obtains the effective selection and reads one installed manifest. It delegates resolution of the target's ModulePlan to the ModulePlanResolver, which invokes the ModuleGraphResolver. The graph resolver expands the required dependency closure, rejects excluded dependencies and enabled-module conflicts, detects cycles and establishes deterministic dependency-first order. It validates installed graph descriptors before resolving the selected closure; selection is not a way to bypass descriptor validation.

A related but earlier stage is DependencySync. The ProjectPackagePlanner takes an explicit set of application targets and resolves each target separately against a release installation catalog. It retains each target's enabled and excluded module identifiers and unions the enabled identifiers to derive desired Coretsia root requirements. This is a project-wide physical installation plan, not a target-local runtime plan. Composer still resolves its own package constraints and may install additional dependencies. After installation, the InstalledProjectVerifier resolves installed target-local plans and compares them with the approved expectations; the design calls for post-install verification in a fresh PHP process.

The distinction reaches the container compiler. ContainerProviderPlanResolver walks the resolved module plan's topological order and reads each enabled module's declared providers from the same manifest snapshot. It preserves provider declaration order within each module, rejects duplicate provider identities and validates class existence, canonical class names, instantiability and conformance to ContainerDefinitionProviderInterface. These checks may trigger class autoloading, but the resolver does not instantiate providers. RuntimeContainerGraphCompiler consumes the provider plan, instantiates the selected definition providers, collects and merges their definition sets, compiles the container graph and validates its completeness.

This is the concrete significance of the separation: a package installed for another target need not contribute its providers to the current target's container graph. The repository includes graph-selection regression tests, a provider-order regression test and project package planning tests.

One particularly relevant case is testPerTargetExclusionDoesNotRemovePackageRequiredByAnotherTarget(). It asserts that platform.worker is excluded from the Web target, remains enabled for the Worker target and remains present in the project-wide union of enabled module identifiers. This is the same architectural distinction illustrated by the independent experiment: target-local exclusion does not imply project-wide package removal. These observations are based on the implementation and test assertions in the reviewed repository snapshot, not on a newly executed Coretsia test suite or a claim of production readiness.

6. The limits of module activation

An explicit activation model is not a security sandbox. Installed packages may expose autoloadable classes regardless of selection; Composer autoload.files can execute eager initialization code, and enabled components can interact with other code if permitted by the surrounding application. The guarantee demonstrated here concerns provider planning and invocation, not universal process isolation. If packages require isolation at the source level, that is a separate architecture policy, as discussed in the second Engineering Note.

Similarly, a module plan does not prove that a target is compatible with every runtime. A production application may need an additional validation step for execution models, extension capabilities or supported drivers. Package installation, module activation and runtime compatibility should remain distinct decisions even when a tool orchestrates them in one workflow.

7. Conclusion

Composer resolves package dependencies and makes the installed packages available to the application. Module selection and graph resolution determine which modules participate in a particular application composition. Keeping these responsibilities separate allows several applications to share a package installation without automatically sharing every service, while making invalid module selections observable before provider execution. Explicit activation does not replace package dependency resolution; it supplies an application-level decision that package installation alone cannot make.

Appendix: reproduce the experiment

The example requires PHP 8.4 and Composer 2 for the installed-package verification. No framework, remote packages or separate repository are needed. Create an empty directory named composition-demo to avoid interference from an earlier lock file or installation. All file paths in the reproduction are relative to this project root. Save plan.php from section 3 alongside the root composer.json and checks.php provided below. Each local package has its own Composer manifest and provider class. The complete source layout is:

composition-demo/
├── composer.json
├── plan.php
├── checks.php
└── packages/
    ├── http/
    │   ├── composer.json
    │   └── src/
    │       └── Provider.php
    ├── console/
    │   ├── composer.json
    │   └── src/
    │       └── Provider.php
    └── scheduler/
        ├── composer.json
        └── src/
            └── Provider.php
Enter fullscreen mode Exit fullscreen mode

The root manifest uses a local path repository with mirroring instead of symlinks and disables Packagist. Scripts and plugins are disabled during installation; the matrix script is executed explicitly afterward.

composer.json:

{
    "name": "acme/composition-demo",
    "description": "Local package installation versus module activation experiment",
    "type": "project",
    "license": "MIT",
    "require": {
        "php": "~8.4.0",
        "acme/http": "1.0.0",
        "acme/scheduler": "1.0.0"
    },
    "repositories": [
        {
            "type": "path",
            "url": "packages/*",
            "options": {
                "symlink": false,
                "reference": "config"
            }
        },
        {
            "packagist.org": false
        }
    ],
    "config": {
        "allow-plugins": false
    },
    "scripts": {
        "matrix": "@php checks.php"
    }
}
Enter fullscreen mode Exit fullscreen mode

packages/http/composer.json:

{
    "name": "acme/http",
    "description": "Local http module fixture",
    "license": "MIT",
    "version": "1.0.0",
    "require": {
        "php": "~8.4.0"
    },
    "autoload": {
        "psr-4": {
            "Acme\\Http\\": "src/"
        }
    },
    "extra": {
        "demo": {
            "module": "http",
            "requires": [],
            "provider": "Acme\\Http\\Provider"
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

packages/http/src/Provider.php:

<?php

declare(strict_types=1);

namespace Acme\Http;

final class Provider
{
    public function register(): string
    {
        return 'http.handler';
    }
}
Enter fullscreen mode Exit fullscreen mode

packages/console/composer.json:

{
    "name": "acme/console",
    "description": "Local console module fixture",
    "license": "MIT",
    "version": "1.0.0",
    "require": {
        "php": "~8.4.0"
    },
    "autoload": {
        "psr-4": {
            "Acme\\Console\\": "src/"
        }
    },
    "extra": {
        "demo": {
            "module": "console",
            "requires": [],
            "provider": "Acme\\Console\\Provider"
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

packages/console/src/Provider.php:

<?php

declare(strict_types=1);

namespace Acme\Console;

final class Provider
{
    public function register(): string
    {
        return 'console.command';
    }
}
Enter fullscreen mode Exit fullscreen mode

packages/scheduler/composer.json:

{
    "name": "acme/scheduler",
    "description": "Local scheduler module fixture",
    "license": "MIT",
    "version": "1.0.0",
    "require": {
        "php": "~8.4.0",
        "acme/console": "1.0.0"
    },
    "autoload": {
        "psr-4": {
            "Acme\\Scheduler\\": "src/"
        }
    },
    "extra": {
        "demo": {
            "module": "scheduler",
            "requires": [
                "console"
            ],
            "provider": "Acme\\Scheduler\\Provider"
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

packages/scheduler/src/Provider.php:

<?php

declare(strict_types=1);

namespace Acme\Scheduler;

final class Provider
{
    public function register(): string
    {
        return 'scheduler.job';
    }
}
Enter fullscreen mode Exit fullscreen mode

The following verification script is the same one used by the matrix Composer script. It reads actual installed metadata in its default mode. The optional --source-fixture mode reads the three source manifests and registers a minimal local class loader; it verifies the planner and provider behavior without claiming that Composer installed anything.

checks.php:

<?php

declare(strict_types=1);

require __DIR__ . '/plan.php';

function check(bool $ok, string $message): void
{
    if (!$ok) {
        throw new RuntimeException($message);
    }
}

function readJson(string $path): array
{
    $data = file_get_contents($path);
    if ($data === false) {
        throw new RuntimeException("Cannot read $path");
    }

    return json_decode($data, true, 512, JSON_THROW_ON_ERROR);
}

// An optional source-only test mode is not a Composer installation.
if ($argc === 2 && $argv[1] === '--source-fixture') {
    $packages = [];
    foreach (['http', 'console', 'scheduler'] as $name) {
        $packages[] = readJson(__DIR__ . "/packages/$name/composer.json");
    }
    spl_autoload_register(static function (string $class): void {
        $paths = [
            'Acme\\Http\\Provider' => 'http',
            'Acme\\Console\\Provider' => 'console',
            'Acme\\Scheduler\\Provider' => 'scheduler',
        ];
        if (isset($paths[$class])) {
            require __DIR__ . '/packages/' . $paths[$class] . '/src/Provider.php';
        }
    });
    echo "Mode: source fixture (not Composer)\n";
} elseif ($argc === 1) {
    $loader = require __DIR__ . '/vendor/autoload.php';
    $packages = readJson(__DIR__ . '/vendor/composer/installed.json')['packages'];
    foreach (['http', 'console', 'scheduler'] as $name) {
        check(\Composer\InstalledVersions::isInstalled("acme/$name"), "not installed:$name");
        $class = 'Acme\\' . ucfirst($name) . '\\Provider';
        $path = $loader->findFile($class);
        check(is_string($path) && is_file($path), "not autoloadable:$class");
    }
    echo "Mode: Composer-installed metadata and autoloader\n";
} else {
    throw new InvalidArgumentException('Usage: php checks.php [--source-fixture]');
}

$modules = moduleIndex($packages);
check(array_keys($modules) === ['console', 'http', 'scheduler'], 'module inventory');

// The same inventory is supplied to each target, without mutation.
$web = plan($modules, ['http']);
check(array_keys($web) === ['http'], 'web plan');
check(registerProviders($web) === ['http.handler'], 'web services');
check(!class_exists('Acme\\Console\\Provider', false), 'inactive console loaded');
check(!class_exists('Acme\\Scheduler\\Provider', false), 'inactive scheduler loaded');
echo "web: http.handler; inactive providers not loaded\n";

$cli = plan($modules, ['console']);
check(array_keys($cli) === ['console'], 'cli plan');
check(registerProviders($cli) === ['console.command'], 'cli services');
echo "cli: console.command\n";

$scheduler = plan($modules, ['scheduler']);
check(array_keys($scheduler) === ['console', 'scheduler'], 'scheduler plan');
check(registerProviders($scheduler) === ['console.command', 'scheduler.job'], 'scheduler services');
echo "scheduler: console.command, scheduler.job\n";

// Contrast with the intentionally naive "enable every discovered module" policy.
$all = plan($modules, array_keys($modules));
check(registerProviders($all) === ['console.command', 'http.handler', 'scheduler.job'], 'all services');
echo "all-discovered: console.command, http.handler, scheduler.job\n";

function expectFailure(string $expected, callable $operation): void
{
    try {
        $operation();
    } catch (LogicException $exception) {
        check($exception->getMessage() === $expected, 'wrong failure: ' . $exception->getMessage());
        echo "rejected: $expected\n";
        return;
    }
    throw new RuntimeException("Expected failure: $expected");
}

expectFailure('missing:missing', fn () => plan($modules, ['missing']));
expectFailure('excluded:console', fn () => plan($modules, ['scheduler'], ['console']));
$withoutConsole = $modules;
unset($withoutConsole['console']);
expectFailure('missing:console', fn () => plan($withoutConsole, ['scheduler']));
$cycle = $modules;
$cycle['console']['requires'] = ['scheduler'];
expectFailure('cycle:scheduler', fn () => plan($cycle, ['scheduler']));

$reversed = moduleIndex(array_reverse($packages));
check(plan($modules, ['scheduler', 'http']) === plan($reversed, ['http', 'scheduler']), 'determinism');
echo "deterministic: reversed inventory and roots\n";
echo "Matrix PASS\n";
Enter fullscreen mode Exit fullscreen mode

After saving all nine files, open a terminal in the composition-demo project root and execute the following commands individually:

php --version
composer --version
composer validate --strict
composer update --no-interaction --no-plugins --no-scripts
composer run matrix
Enter fullscreen mode Exit fullscreen mode

Strict Composer validation may report warnings and return a nonzero exit status because the local package versions are pinned intentionally to 1.0.0. These warnings are expected in this controlled fixture and do not indicate an invalid manifest. A successful installation and matrix execution produce the Composer-backed output shown in section 4, ending with Matrix PASS. The verification script fails with a nonzero status when an assertion or an unexpected graph failure occurs. You can repeat the verification with composer run matrix or php checks.php without reinstalling packages.

To test the graph and registration independently of Composer, run:

php checks.php --source-fixture
Enter fullscreen mode Exit fullscreen mode

The source-only test is useful when Composer is unavailable, but it cannot replace the installed-package verification. In particular, it does not test Composer's path repository installation or generated autoloader.

References

Disclosure: AI was used to help draft this article and prepare the example.

Top comments (0)