michael-rubel/laravel-enhanced-container

此包为Laravel的服务容器提供DX调整。

13.0.0 2024-08-21 17:49 UTC

README

Method binding with Service Container   Call Proxy

Laravel增强容器

Latest Version on Packagist Total Downloads Code Quality Code Coverage GitHub Tests Action Status PHPStan

此包为Laravel的服务容器提供额外功能。

#StandWithUkraine

SWUbanner

内容

安装

通过composer安装包(Laravel 11)

composer require michael-rubel/laravel-enhanced-container

如果您需要旧版本的Laravel包,请查看变更日志

使用

在构造函数外解析上下文绑定

call(ServiceInterface::class, context: static::class);

// The `call` method automatically resolves the implementation from the interface you passed.
// If you pass the context, the proxy tries to resolve contextual binding instead of global binding first.

🔝 返回内容

方法绑定

此功能使得可以通过 call 访问的方法可以重写行为。

假设这是您的服务类中的函数

class Service
{
    public function yourMethod(int $count): int
    {
        return $count;
    }
}

将服务绑定到一个接口

$this->app->bind(ServiceInterface::class, Service::class);

通过容器调用您的服务方法

call(ServiceInterface::class)->yourMethod(100);

例如在功能测试中

$this->app->bind(ApiGatewayContract::class, InternalApiGateway::class);

bind(ApiGatewayContract::class)->method('performRequest', function ($service, $app, $params) {
    // Note: you can access `$params` passed to the method call.

    return true;
});

$apiGateway = call(ApiGatewayContract::class);
$request = $apiGateway->performRequest();
$this->assertTrue($request);

注意:如果您依赖于接口,代理会自动为您解析已绑定的实现。

对包创建者的说明

如果您想在您的包中使用方法绑定,您需要确保在使用此功能之前已注册LecServiceProvider

$this->app->register(LecServiceProvider::class);

🔝 返回内容

方法转发

此功能如果您的类中不存在该方法,则会自动将其转发到转发配置中定义的第二个方法。

您可以在您的ServiceProvider中定义转发

use MichaelRubel\EnhancedContainer\Core\Forwarding;

Forwarding::enable()
    ->from(Service::class)
    ->to(Repository::class);

您还可以使用链式转发

Forwarding::enable()
    ->from(Service::class)
    ->to(Repository::class)
    ->from(Repository::class)
    ->to(Model::class);

重要提示

  • 使用转发时,请注意在 CallProxy 中您现在正在处理哪个内部实例。实例可能会在不经意间发生变化。如果您在与不同实例的相同方法/属性交互,将抛出 InstanceInteractionException
  • 如果您使用 PHPStan/Larastan,您需要为服务添加 @method 文档注释,以便进行静态分析,否则它将返回错误,表明类中不存在该方法。

🔝 返回内容

测试

composer test

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件