简体   繁体   中英

Slim3 - Argument 1 passed to constructor must be instance of Slim\Views\Twig

I'm using Slim3, but I'm having an issue registering a dependency. According to the error the constructor I created expects the type of argument 1 to be Slim\\Views\\Twig .

The problem is I am passing an instance of Slim\\Views\\Twig - at least I think I am. I've not used Slim in a few months so I might be missing something obvious. Never the less I can't find the issue.

The error I'm getting is:

Catchable fatal error:  Argument 1 passed to App\Controllers\RegistrationController::__construct() must be an instance of Slim\Views\Twig, instance of Slim\Container given

controllers/RegistrationController.php

<?php

namespace App\Controllers;

class RegistrationController {
  protected $view;

  public function __construct(\Slim\Views\Twig $view) {
    $this->view = $view;
  }

  public function register($request, $response, $args) {
    // Does some stuff ...
  }
}

dependencies.php

<?php

use \App\Controllers\RegistrationController;

$container = $app->getContainer();

// Twig View
$container['view'] = function ($c) {
    $settings = $c->get('settings')['renderer'];
    $view = new \Slim\Views\Twig($settings['template_path']);
    $basePath = rtrim(str_ireplace('index.php', '', $c['request']->getUri()->getBasePath()), '/');
    $view->addExtension(new Slim\Views\TwigExtension($c['router'], $basePath));
    return $view;
};

// monolog
$container['logger'] = function ($c) {
    $settings = $c->get('settings')['logger'];
    $logger = new Monolog\Logger($settings['name']);
    $logger->pushProcessor(new Monolog\Processor\UidProcessor());
    $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
    return $logger;
};

// sqlite3
$container['db'] = function ($c) {
    return new SQLite3(__DIR__ . '/../db/prod.db');
};

// Registration Controller
$container['RegistrationController'] = function($c) {
  return new RegistrationController($c->get('view'));
};

route

$app->post('/signup', '\App\Controllers\RegistrationController:register');

Also tried the following:

$app->post('/signup', \App\Controllers\RegistrationController::class . ':register');

Any ideas?

The problem was I was defining the route incorrectly and I completely missed the section on Container Resolution

Here's how it should look:

$app->post('/signup', 'RegistrationController:register');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM