【问题标题】:What is the correct interface for Slim's container?Slim 容器的正确接口是什么?
【发布时间】:2018-05-19 14:39:05
【问题描述】:

我正在尝试实现https://www.slimframework.com/docs/v3/objects/router.html 描述的Allow Slim to instantiate the controller 部分。这样做时,我收到以下错误:

传递给 Michael\Test\HomeController::__construct() 的参数 1 必须 是 Slim\ContainerInterface 的实例,Slim\Container 的实例 给定的,调用的 /var/www/slimtest/vendor/slim/slim/Slim/CallableResolver.php 上线 93

认为它可能与命名空间有关,我也在 \ 命名空间中进行了尝试,但得到了同样的错误。

https://www.slimframework.com/docs/v3/objects/router.html 上的文档是否不正确,HomeController 的构造函数参数声明类型应该是 Slim\Container,还是我做错了什么,Slim\ContainerInterface 是正确的?

<?php
namespace Michael\Test;

error_reporting(E_ALL);
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);

require '../vendor/autoload.php';

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app = new \Slim\App();
$container = $app->getContainer();
//$container['view'] = function ($c) {};

//Question.  Do I need to use the fully qualified class name???
$app->get('/', \Michael\Test\HomeController::class . ':home');
//$app->get('/', '\Michael\Test\HomeController:home');

$app->run();

家庭控制器

namespace Michael\Test;
class HomeController
{
    protected $container;

    // constructor receives container instance
    public function __construct(\Slim\ContainerInterface $container) {
        $this->container = $container;
    }

    public function home($request, $response, $args) {
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }

    public function contact($request, $response, $args) {
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }
}

【问题讨论】:

    标签: php interface slim


    【解决方案1】:

    \Slim\ContainerInterface 不存在(请参阅here)。查看\Slim\Container的实现,您需要使用的接口是Interop\Container\ContainerInterface,或者您可以使用Slim实现\Slim\Container作为类型参数。

    【讨论】:

    • 谢谢。您同意文档不正确吗?
    • 我不会说文档不正确,只是不清楚,您可以更改this file(router.md) 以使其更清晰,并创建一个对瘦网站的拉取请求。
    • Interop\Container\ContainerInterface其实只是Psr\Container\ContainerInterface的别名,所以你也可以使用Psr的ContainerInterface
    猜你喜欢
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 2010-10-17
    • 1970-01-01
    相关资源
    最近更新 更多