I need to create a new user in google, and I`m using Slim 3 to make a REST API.
My code:
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
I want to access to Google_Client
as I do with UserModel
, but I cannot figure it out how.
If I use it in routes.php, it works.
$app->get('/g', function ($request, $response, $args) {
$client = new Google_Client(); // THIS WORKS!!
var_dump($client);
});
The Google_Client
class is defined in \vendor\google\apiclient\src\Google\client.php
Google_Client
exists in the root namespace.
When you attempt to do:
$client = new Google_Client()
It's looking for the class in the namespace for the file the statement is in.
It works in routes.php because there are is no namespace declared in that file. But since your controller does reside in a namespace, you get the error you are seeing.
To avoid it, just do this:
$client = new \Google_Client();
To explicitely say that Google_Client
resides in the root namespace.