使用 Slim 3 从控制器中的静态方法调用 Google_Client
Call Google_Client from a static method in a controller using Slim 3
我需要在 google 中创建一个新用户,我正在使用 Slim 3 创建 REST API。
我的代码:
composer.json:
"require": {
"somethig": "somethig",
"google/apiclient": "2.0"
},
"autoload": {
"psr-4": {
"App\": "app/"
}
}
routes.php:
$app->get('/users/create', App\Controllers\UserController::class . ':create_users');
UserController.php:
use App\Models\UserModel;
class UserController{
public static function create_users( Request $request, Response $response, array $args )
{
// some code
$users = UserModel::where( 'pending', 0 )->get(); // WORKS OK
// some more code
self::get_google_client();
}
private function get_google_client()
{
$client = new Google_Client(); // ERROR: Class 'App\Controllers\Google_Client'
// a lot more code, based on quickstart.php
}
} // class end
我想像访问 UserModel
一样访问 Google_Client
,但我不知道如何访问。
如果我在 routes.php 中使用它,它会起作用。
$app->get('/g', function ($request, $response, $args) {
$client = new Google_Client(); // THIS WORKS!!
var_dump($client);
});
Google_Client
class定义在\vendor\google\apiclient\src\Google\client.php
Google_Client
存在于根命名空间中。
当您尝试这样做时:
$client = new Google_Client()
它正在查找语句所在文件的命名空间中的 class。
它在 routes.php 中有效,因为该文件中没有声明名称空间。但是由于您的控制器确实驻留在名称空间中,因此您会收到所看到的错误。
要避免它,只需这样做:
$client = new \Google_Client();
明确地说 Google_Client
驻留在根命名空间中。
我需要在 google 中创建一个新用户,我正在使用 Slim 3 创建 REST API。
我的代码:
composer.json:
"require": {
"somethig": "somethig",
"google/apiclient": "2.0"
},
"autoload": {
"psr-4": {
"App\": "app/"
}
}
routes.php:
$app->get('/users/create', App\Controllers\UserController::class . ':create_users');
UserController.php:
use App\Models\UserModel;
class UserController{
public static function create_users( Request $request, Response $response, array $args )
{
// some code
$users = UserModel::where( 'pending', 0 )->get(); // WORKS OK
// some more code
self::get_google_client();
}
private function get_google_client()
{
$client = new Google_Client(); // ERROR: Class 'App\Controllers\Google_Client'
// a lot more code, based on quickstart.php
}
} // class end
我想像访问 UserModel
一样访问 Google_Client
,但我不知道如何访问。
如果我在 routes.php 中使用它,它会起作用。
$app->get('/g', function ($request, $response, $args) {
$client = new Google_Client(); // THIS WORKS!!
var_dump($client);
});
Google_Client
class定义在\vendor\google\apiclient\src\Google\client.php
Google_Client
存在于根命名空间中。
当您尝试这样做时:
$client = new Google_Client()
它正在查找语句所在文件的命名空间中的 class。
它在 routes.php 中有效,因为该文件中没有声明名称空间。但是由于您的控制器确实驻留在名称空间中,因此您会收到所看到的错误。
要避免它,只需这样做:
$client = new \Google_Client();
明确地说 Google_Client
驻留在根命名空间中。