2016-06-23 25 views
1

Slim 3にグローバル変数を挿入するにはどうすればよいですか?私はこのHow can i define global variables in slim frameworkを見つけたが、それは、私は、GoogleのAPIを設定シングルトンを持っている2.Slim 3ルートにグローバル変数を挿入する方法は?

スリムを参照:

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. 

は、どのように私はこのシングルトンを使用したが、それはすべてルートで使用できるように依存関係としてそれを注入することができることについては行くべき?私がドキュメント(http://www.slimframework.com/docs/objects/router.html#container-resolution)で見たことに基づいて、コンストラクタをpublicにする必要があるようです。

答えて

6

私はドキュメントのそのセクションを書いた人です。

あなたがする必要があることは、コンテナに定義することです。それだ

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

!どうもありがとう。 – djthoms

関連する問題