Вопрос

Is it possible to do pass along arguments to an API class for the sake of constructor injection? For example, in index.php I have the following:

$r->addAPIClass('Contacts', '');

And Contacts.php looks something like this:

class Contacts
{
    private $v;

    public function __construct(Validation v)
    {
        $this->v = v;
    }
}

How would I do this with 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.

Once you register the Contacts class with its dependency using the register method, it will be lazy instantiated when asked for

<?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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top