[英]Constructor Injection in Restler
Is it possible to do pass along arguments to an API class for the sake of constructor injection? 为了构造函数注入,是否可以将参数传递给API类? For example, in index.php I have the following:
例如,在index.php中,我具有以下内容:
$r->addAPIClass('Contacts', '');
And Contacts.php looks something like this: 和Contacts.php看起来像这样:
class Contacts
{
private $v;
public function __construct(Validation v)
{
$this->v = v;
}
}
How would I do this with Restler? 我将如何与Restler做到这一点?
Restler 3 RC5 has a dependency injection container called Scope
which is responsible for creating new instances of any class from their name, it comes in handy for this purpose. Restler 3 RC5有一个名为
Scope
的依赖项注入容器,该容器负责根据名称创建任何类的新实例,为此它非常有用。
Once you register the Contacts class with its dependency using the register method, it will be lazy instantiated when asked for 一旦使用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();
By using Scope::get('Validation')
we can register Validation
too if it has any dependencies 通过使用
Scope::get('Validation')
如果它具有任何依赖关系,我们也可以注册Validation
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.