我需要在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
我想像访问Google_Client
一样访问UserModel
,但是我不知道该怎么做。
如果我在routes.php中使用它,它将起作用。
$app->get('/g', function ($request, $response, $args) {
$client = new Google_Client(); // THIS WORKS!!
var_dump($client);
});
Google_Client
类在\ vendor \ google \ apiclient \ src \ Google \ client.php中定义
答案 0 :(得分:3)
Google_Client
存在于根名称空间中。
当您尝试这样做时:
$client = new Google_Client()
它正在查找该语句所在文件的名称空间中的类。
它在 routes.php 中起作用,因为该文件中没有声明名称空间。但是由于您的控制器确实位于命名空间中,所以您会看到错误。
要避免这种情况,只需执行以下操作:
$client = new \Google_Client();
要明确地说Google_Client
位于根名称空间中。