Restler中的构造函数注入

zon*_*eil 2 php rest restler

为了构造函数注入,是否可以将参数传递给API类?例如,在index.php中我有以下内容:

$r->addAPIClass('Contacts', '');
Run Code Online (Sandbox Code Playgroud)

而Contacts.php看起来像这样:

class Contacts
{
    private $v;

    public function __construct(Validation v)
    {
        $this->v = v;
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何使用Restler做到这一点?

Aru*_*ran 6

Restler 3 RC5有一个依赖注入容器Scope,它负责从它们的名字创建任何类的新实例,它为此目的派上用场.

一旦使用register方法注册Contacts类及其依赖项,在被要求时它将被惰性实例化

<?php
include '../vendor/autoload.php';

use Luracast\Restler\Scope;
use Luracast\Restler\Restler;

Scope::register('Contacts', function () {
    return new Contacts(Scope::get('Validation'));
});

$r = new Restler();
$r->addAPIClass('Contacts', '');
$r->handle();
Run Code Online (Sandbox Code Playgroud)

通过使用Scope::get('Validation')我们也可以注册,Validation如果它有任何依赖