using Dice - Dependency Injector with Zend Diactoros and Fast Route

257 views Asked by At

I'm using Dice(a nice Dependency Injector) for a small project. I am also using the PSR7 Zend Diactoros for requests and nikic fast route.

I got Dice working for Twig, DB and all the rest of my classes using the examples from docs, but I am unable do figure out how to use it to pass a Request $request to my controllers.

I would appreciate if you could at least point me in the right direction on how to correctly use a Dependency Injector for such use cases

controller code:

use Psr\Http\Message\{ServerRequestInterface,ResponseInterface};

class BaseController
{
    public function index(ServerRequestInterface $request)
    {
        dump($request);
        return view('homepage/index.html');
    }
}

app init code:

$dependency_injector = new Dice();

$rule_request = ['substitutions' => [
    'Psr\\Http\\Message\\ServerRequestInterface' => ['instance'=>function(){
    return Zend\Diactoros\ServerRequestFactory::fromGlobals();
}]];


$midEngine = new MiddlewareEngine($dependency_injector);
$midEngine->add(\App\Middleware\Router::class);

$response = new Zend\Diactoros\Response();
$request = Zend\Diactoros\ServerRequestFactory::fromGlobals();

$final = $midEngine($request, $response);

$emitter = new SapiEmitter();
$emitter->emit($final);
exit;

in router code:

call_user_func_array([$this->app->di->create($handler[0]),$handler[1]],$vars)

where $this->app->di is Dice and $handler is

array(2) {
  [0]=>
  string(30) "App\Controllers\BaseController"
  [1]=>
  string(5) "index"
}

1 as my route has no param first error was that I was passing to few params, so i tried doing this in router, which calls the index method of the controller and passes $request

$class = new \ReflectionClass($handler[0]);
$method = $class->getMethod($handler[1]);
foreach ($method->getParameters() as $param) {
            dump($param->getClass()->getName());
            dump($this->app->di->getRule($param->getClass()->getName()));
            $vars[] = $this->app->di->create($param->getClass()->getName());
        }
call_user_func_array([$this->app->di->create($handler[0]),$handler[1]],$vars);

2 now I have my param passed but the error is

Uncaught Error: Cannot instantiate interface Psr\Http\Message\ServerRequestInterface

I have a feeling I'm using this all wrong, maybe the Di needs to create the $midEngine as now I create a response and request object myself.

Any advice would be great, I'm trying to wrap my head around how a mini framework should revolve around a Di.

Thanks, Alex

0

There are 0 answers