问题
I'm trying to figure out how to count all registered users from the Firebase. I've only implemented the Firebase authentication and have not mannualy created a database.
I can't find a way to count or even get them from Firebase.
$serviceAccount = ServiceAccount::fromJsonFile(config_path('path-to-file.json'));
$firebase = (new Factory())
->withServiceAccount($serviceAccount)
->create();
$database = $firebase->getDatabase();
I've got a connection with the code above.
Also I tried to use the auth helper like:
$auth = $firebase->getAuth();
$users = $auth->listUsers($defaultMaxResults = 1000, $defaultBatchSize = 1000);
But the thing I only managed with this was getting the current user.
Anyone knows how to count all users / get them?
回答1:
👋 Hi, maintainer of the SDK you're using here :).
There is currently (as of 2019-08-29 and as far as I know) no way to directly get the number of registered users in a Firebase project except through iterating through all of them and counting them manually.
The fastest way to do this would be by using
$users = $auth->listUsers();
$userCount = iterator_count($users);
We have to use iterator_count
here because Auth::listUsers() returns a Generator that behaves differently than the "usual" array: instead of fetching all the users at once, it will fetch the next batch only when we "need" it.
There are methods to convert an iterator to an array (iterator_to_array()) and to count all items of an iterator (iterator_count()), but under the hood, they will load all users into memory, which can become really expensive if you have thousands or hundreds of thousands of users.
For that reason, I would recommend not using iterator_to_array()
but foreach
when you want to work with the user records directly:
foreach ($users as $user) {
/** @var \Kreait\Firebase\Auth\UserRecord $user */
echo $user->uid;
}
as well as using iterator_count()
only sparingly and cache the result when you have it.
PS: Did you know that there's now a Laravel Package for this SDK as well? 😅
来源:https://stackoverflow.com/questions/57698602/how-to-count-users-from-firebase-with-php-laravel-5-8