如何在Slim 3路由中注入全局变量?

djt*_*oms 2 php dependency-injection slim

你如何在Slim 3中注入全局变量?我发现了这个如何在slim框架中定义全局变量,但它引用了Slim 2.

我有一个配置Google API的单身人士:

class Google_Config {

    private static $CLIENT_ID = "...";
    private static $CLIENT_SECRET = "...";
    private static $REDIRECT_URI = "...";

    private static $instance = null;

    private $client = null;

    private $scopes = [...];

    private function __construct() {
        $this->client = new Google_Client();
        $this->client->setClientId(self::$CLIENT_ID);
        $this->client->setClientSecret(self::$CLIENT_SECRET);
        $this->client->setRedirectUri(self::$REDIRECT_URI);
        $this->client->setScopes($this->scopes);
    }

    public static function get() {
        if(self::$instance == null) {
            self::$instance = new Google_Config();
        }

        return self::$instance;
    }

}
Run Code Online (Sandbox Code Playgroud)

我正在定义全局变量index.php如下:

 $config = Google_Config::get();
Run Code Online (Sandbox Code Playgroud)

我尝试了上面引用的文章中的一些旧方法:

$app->config = Google_Config::get(); // index.php

// route.php 
$app->get('/login', function($request, $response, $args) {
    $google = $this->get("AS_Google_Config");
    var_dump($google); // for testing
    return $this->renderer->render($response, 'login.phtml');
});
Run Code Online (Sandbox Code Playgroud)

但我得到:

 Identifier "Google_Config" is not defined.
Run Code Online (Sandbox Code Playgroud)

我应该如何使用这个单例,但能够将它作为依赖项注入,以便它可以在所有路由中使用?根据我在文档中看到的内容(http://www.slimframework.com/docs/objects/router.html#container-resolution),似乎我需要将构造函数设为public.

geg*_*eto 6

我就是编写该部分文档的人.

您需要做的是在容器中定义它.

$container['google_client'] = function ($c) { 
    return Google_Config::get(); 
};
Run Code Online (Sandbox Code Playgroud)

然后...

$app->get('/login', function($request, $response, $args) {
    $google = $this->get("google_client"); // <--
    var_dump($google); // for testing
    return $this->renderer->render($response, 'login.phtml');
});
Run Code Online (Sandbox Code Playgroud)