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

How to inject global variables in Slim 3 route?

你如何在 Slim 3 中注入全局变量?我找到了这个 How can i define global variables in slim framework,但它引用了 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;
    }

}

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

 $config = Google_Config::get();

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

$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');
});

但我得到:

 Identifier "Google_Config" is not defined.

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

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

你需要做的是在容器中定义它。

$container['google_client'] = function ($c) { 
    return Google_Config::get(); 
};

然后...

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

使用 php 环境。例如,您可以使用 vlucas/phpdotenv。从 composer - packagist

获取