ray/ray-di-for-laravel

Ray.Di for Laravel

0.4.0 2024-03-01 10:15 UTC

This package is auto-updated.

Last update: 2024-08-26 09:29:06 UTC


README

DI+AOP,正确的方式

英文 | 日语

安装

composer require ray/ray-di-for-laravel

使用

复制描述绑定、上下文和生成文件存储目录的模块。

cp -r vendor/ray/ray-di-for-laravel/RayDi app
cp -r vendor/ray/ray-di-for-laravel/storage/ storage

更改 bootstrap/app.php 中的以下行。

+ $basePath = $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__);
+ $context = getenv('APP_ENV') ?: 'local';
- $app = new Illuminate\Foundation\Application(
-     $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
- );
+ $app = new Ray\RayDiForLaravel\Application(
+     $basePath,
+     App\RayDi\Context\ContextProvider::get($basePath, $context)
+ );

Ray\RayDiForLaravel\Attribute\Injectable 属性添加到您希望通过 Ray.Di 解析的类或接口。

此类将通过 Ray.Di 解析。

<?php

namespace App\Http\Controllers;

use Ray\RayDiForLaravel\Attribute\Injectable;

#[Injectable]
class HelloController extends Controller
{

}

此类将通过现有的 Laravel 服务容器解析。

<?php

namespace App\Http\Controllers;

// no attributes
class MyController extends Controller
{

}

上下文

RayDi/Context/ContextProvider 为应用程序运行时上下文生成上下文类。

在上下文类中指定模块和缓存,并将选择上下文特定的注入器。

Ray.Di for Laravel 提供以下内置上下文。

  • RayDi/Context/ProductionContext
  • RayDi/Context/LocalContext
  • RayDi/Context/TestingContext.php

缓存

RayDi/Context/ProductionContext 中,如果启用了 apcu 扩展,注入器将被缓存。

自定义上下文

您可能需要自己的上下文。根据内置上下文实现自定义上下文,并在 RayDi/Context/ContextProvider 中使用它。

覆盖模块

当运行测试时,您可能希望根据测试用例更改绑定。

在测试类中使用 Ray\RayDiForLaravel\Testing\OverrideModule,并按如下所示调用 $this->overrideModule

use Tests\TestCase;

final class HelloTest extends TestCase
{
    use Ray\RayDiForLaravel\Testing\OverrideModule;

    public function testStatusOk(): void
    {
        $this->overrideModule(new MyModule());
    
        $res = $this->get('/hello');

        $res->assertOk();
        $res->assertSeeText('Hello 1 * 2 = 2.');
    }
}

性能

通过安装 DiCompileModule,使用优化的注入器,并在编译时而不是运行时报告依赖错误。

对于对应于 RayDi/Context/ProductionContextRayDi/ProductionModuleDiCompileModule 已经安装。

示例

查看 hello-ray-di-for-laravel 示例代码。