在 Slim v3 中如何访问路由中的 $container 属性?

In Slim v3 how to access $container properties in routes?

我的设置是这样的:

我从这个文件请求我的设置并将它们存储在设置变量中。

$settings = require __DIR__ . '/settings.php';

接下来像这样创建一个新的 Slim 实例:

$app = new \Slim\App($settings);

$container = $app->getContainer();

$container['logger'] = function($c) {
    $settings = $c->get('settings')['logger'];
    $logger = new \Monolog\Logger($settings['name']);
    $file_handler = new \Monolog\Handler\StreamHandler($settings['path']);
    $logger->pushHandler($file_handler);
    return $logger;
};

那我打电话给我的路线:

$this->get('/testlogger, __testReq::class . ':test);

上面的路由调用了我的 class 中的 "test" 方法。哪个通过自动加载加载。在我的 class(控制器)下面,我正在尝试访问容器,就像 Slim 网站上解释的那样。

class __testReq {
   function test($request, $response){
       //According to Documentation i am supposed to be able to call logger like so:
       $this->logger->addInfo("YEY! I am logging...");

    }
}

为什么它不起作用?

来自 Slim documentation(文档以 HomeController class 为例):

Slim first looks for an entry of HomeController in the container, if it’s found it will use that instance otherwise it will call it’s constructor with the container as the first argument.

所以在你的class __testReq构造函数中,你需要设置对象:

class __testReq {

    // logger instance
    protected $logger;

    // Use container to set up our newly created instance of __testReq
    function __construct($container) {
        $this->logger= $container->get('logger');
    }

    function test($request, $response){
        // Now we can use $this->logger that we set up in constructor
        $this->logger->addInfo("YEY! I am logging...");

    }
}