jblaak/php-modules

该软件包的最新版本(1.2.1)没有提供许可证信息。

1.2.1 2023-12-21 08:38 UTC

This package is auto-updated.

Last update: 2024-09-21 10:10:48 UTC


README

通过定义哪些模块可以访问应用程序的其他部分,在你的应用程序中明确声明清晰的依赖关系。

安装

此软件包将很快在Packagist上发布,但仍在开发中。

特性

使用test命令在您的代码库上运行模块检查

./vendor/bin/modules test

生成依赖关系图,为此请确保已安装GraphViz

./vendor/bin/modules graph

定义模块

您的项目根目录中的modules.php文件将存储您的配置。此文件应返回PhpModules\Lib\Modules的实例。

假设我们有一个位于App\Http命名空间中的模块,它依赖于App\Persistence,我们可以按以下方式定义它

<?php

$persistence = PhpModules\Lib\Module::create('App\Persistence');
$http = PhpModules\Lib\Module::create('App\Http', [$persistence]);

return Modules::builder('./src')->register([$persistence, $http])

设计上不允许创建循环依赖,因为我们试图通过此设计模式避免这种情况。

严格模块

显式定义从您的模块中导出的类。大多数模块将有一个显式的公共API,其中可能包含许多辅助类和其他逻辑。例如,一个App\Persistence模块可能有公共API为App\Persistence\PersistedUserApp\Persistence\UserRepository,但可能希望隐藏App\Persistence\Drivers\MySQLDriver以防止其他模块干涉数据库配置。

使用Module::strict定义严格模块

<?php

$persistence = PhpModules\Lib\Module::strict('App\Persistence');
$http = PhpModules\Lib\Module::strict('App\Http', [$persistence]);

return Modules::builder('./src')->register([$persistence, $http])

使用PHPDoc标记类为公共

/**
 * @public
 */
class PersistedUser {}

与外部依赖项或遗留代码库一起工作

虽然鼓励尽可能明确地定义依赖项,但外部依赖项(如框架)或遗留代码库需要大量配置才能开始。

为了允许从尚未定义为模块的应用程序部分或外部库中导入,我们可以在Modules配置中添加->allowUndefinedModules()

例如,您的App\Persistence层可能依赖于Laravel的Eloquent(如果您喜欢这样的东西),而无需显式声明。

<?php

$persistence = PhpModules\Lib\Module::create('App\Persistence');
$http = PhpModules\Lib\Module::create('App\Http', [$persistence]);

return Modules::builder('./src') 
    ->allowUndefinedModules()
    ->register([$persistence, $http])