The Users class allows loading and manipulating user objects. The Users class also inherits all the methods and properties of Module.
Create user
When creating new users, the name
, password
and password_confirmation
parameters are required.
use Scriptor\Core\User;
$user = new User();
$user->set('name', 'content-admin')
->set('password', 'My-secret-pass')
->set('password_confirmation', 'My-secret-pass')
->save();
Retrieve one or more users
Retrieve one or more users using the Users::getUser()
and Users::getUsers()
methods.
By the way, the mentioned methods are used almost the same as the methods of
Pages
class: Pages::getPage or Pages::getPages.
Since the username is unique, you can search for a specific user by name:
use Scriptor\Core\Scriptor;
$users = Scriptor::getSite()->users();
$contentAdmin = $users->getUser('name=content-admin');
If you are looking for multiple users, use the Users::getUsers()
method. For example, if you are looking for all users with the siteadmin role:
$admins = ($users->getUsers('role=siteadmin')) ?? [];
foreach ($admins as $admin) {
echo "Admin user: $admin->name\n";
}
If you want to change a user's password, you can do it as follows:
use Scriptor\Core\Scriptor;
$users = Scriptor::getSite()->users();
$user = $users->getUser('name=content-admin');
$user->set('password', 'OIU=)(87dsds>.$y7y');
$user->set('password_confirmation', 'OIU=)(87dsds>.$y7y');
$user->save();
If you want to catch the exceptions when setting the field values, proceed like this:
try {
$user->set('password', 'OIU=)(87dsds>.$y7s')
->set('password_confirmation', 'OIU=)(87dsds>.$y7q')
->save();
} catch (Exception $e) {
die('Exception: ' . $e->getMessage());
}
Assign the content-admin role to a user with ID 9.
$users = Scriptor::getSite()->users();
$user = $users->getUser(9);
if ($user) $user->set('role', 'content-admin')->save();
Set active
attribute of the user with ID 9 to true (one-liner only if the user with ID 9 exists definitely):
Scriptor::getSite()->users()->getUser(9)->set('active', true)->save();
Delete user
Delete user with the name content-admin
permanently.
use Scriptor\Core\Scriptor;
$users = Scriptor::getSite()->users();
$user = $users->getUser('name=content-admin');
// Permament delete user
$users->deleteUser($user);