如何将实现数组注入PHP的构造函数中

问题描述 投票:1回答:1

如何通过构造函数将实现数组注入类。我正在共享c#链接。我想在php中实现相同的效果。

如何在php中实现相同。

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

提前感谢。

php laravel inversion-of-control lumen laravel-ioc
1个回答
0
投票

您可能需要使用Tagging。例如,也许您正在构建一个报表聚合器,该聚合器接收到一系列许多不同的Report接口实现。注册后报告实施,您可以使用标签为其分配标签方法:

$this->app->bind('SpeedReport', function () {
    //
});

$this->app->bind('MemoryReport', function () {
    //
});

$this->app->tag(['SpeedReport', 'MemoryReport'], 'reports');

一旦标记了服务,您就可以轻松解决所有问题通过标记的方法:

$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;
    }
    //...
}
© www.soinside.com 2019 - 2024. All rights reserved.