2

如何通过构造函数将实现数组注入类。我正在分享 C# 的链接。我想在 php 中实现相同的目标。

如何在 php.ini 中实现相同的功能。

public interface IFoo { }
public class FooA : IFoo {}
public class FooB : IFoo {}

public class Bar
{
    //array injected will contain [ FooA, FooB ] 
    public Bar(IFoo[] foos) { }
}

public class MyModule : NinjectModule
{
    public override void Load()
    {
        Bind<IFoo>().To<FooA>();
        Bind<IFoo>().To<FooB>();
        //etc..
    }
}

https://stackoverflow.com/a/13383476/1844634

提前致谢。

4

2 回答 2

1

PHP 不支持泛型导致运行时性能困难。因此,无法通过承包商的定义来解释您期望所有接口。所以你必须手动配置 DI 容器。明确地告诉你的类需要所有支持某种接口的类。

Laravel 配置使用ServiceProvider进行各种配置:在类\App\Providers\AppServiceProvider中,您可以配置类的创建。


    public function register(): void
    {
        // to configure implementation for an interface or abstract class
        // you can only configure one implementation for interface
        $this->app->bind(\App\IFoo::class, \App\FooA::class);

        // or 'tag' several implementation for one string tag.
        $this->app->tag([\App\FooA::class, \App\FooB::class], \App\IFoo::class);

        $this->app->bind(\App\Bar::class, function(\Illuminate\Contracts\Foundation\Application $container){
            // get all tagged implementations
            $foos = $container->tagged(\App\IFoo::class);

            return new \App\Bar($foos);
        });
    }

于 2020-02-03T14:25:23.663 回答
0

您可能需要使用标记。例如,也许您正在构建一个报表聚合器,它接收许多不同的报表接口实现的数组。注册 Report 实现后,您可以使用 tag 方法为它们分配标签:

$this->app->bind('App\Reports\MemoryReportInterface', 'App\Reports\MemoryReportImplementation');       
$this->app->bind('App\Reports\SpeedReportInterface', 'App\Reports\SpeedReportImplementation');  

$this->app->tag(['App\Reports\MemoryReportInterface', 'App\Reports\MemoryReportInterface'], 'reports'); 

标记服务后,您可以通过 tagged 方法轻松解决它们:

$this->app->bind('ReportAggregator', function ($app) {
    return new ReportAggregator($app->tagged('reports'));
});

用法

<?php 

namespace ...;

/**
 * 
 */
class ReportAggregator
{
    private $reports;

    function __construct($reports)
    {
        $this->reports = $reports;
    }

    public function getReports() {
        return $this->reports;
    }
    //...
}
于 2020-02-03T14:16:32.960 回答