User Management
Creating Users
Using addUser() Method
The simplest way to add a user:
<?php
$user = $users->addUser(
'John Doe', // Full name
'johndoe', // Username
'[email protected]', // Email
'SecurePass123' // Password
);
Using UserModel
For more control, create a UserModel instance:
<?php
use ByJG\Authenticate\Model\UserModel;
$userModel = new UserModel();
$userModel->setName('John Doe');
$userModel->setUsername('johndoe');
$userModel->setEmail('[email protected]');
$userModel->setPassword('SecurePass123');
$userModel->setRole('user');
$savedUser = $users->save($userModel);
Creating Entities via UsersService
When you need a new UserModel that already respects the mapper configuration (including any PasswordDefinition passed to the UsersService constructor), call getUsersEntity():
<?php
$user = $users->getUsersEntity([
'name' => 'Jane Smith',
'email' => '[email protected]',
'username' => 'janesmith',
]);
$user->setPassword('Str0ngPass!');
$users->save($user);
The returned model is identical to instantiating UserModel manually, but it is pre-configured with the service-level password rules and field mappings.
Retrieving Users
The UsersService provides several methods to retrieve users:
Get User by ID
<?php
$user = $users->getById($userId);
Get User by Email
<?php
$user = $users->getByEmail('[email protected]');
Get User by Username
<?php
$user = $users->getByUsername('johndoe');
Get User by Login Field
The login field is determined by the UsersService constructor (either email or username):
<?php
$user = $users->getByLogin('johndoe');
Using Custom Queries
For advanced queries, use the repository directly:
<?php
use ByJG\MicroOrm\Query;
// Get users repository
$usersRepo = $users->getUsersRepository();
// Build custom query
$query = Query::getInstance()
->table('users')
->where('email = :email', ['email' => '[email protected]'])
->where('admin = :admin', ['admin' => 'yes']);
$results = $usersRepo->getRepository()->getByQuery($query);
Updating Users
<?php
// Get the user
$user = $users->getById($userId);
// Update fields
$user->setName('Jane Doe');
$user->setEmail('[email protected]');
// Save changes
$users->save($user);
Deleting Users
Delete by ID
<?php
$users->removeById($userId);
Delete by Login
<?php
$users->removeByLogin('johndoe');
Checking User Roles
Users can have assigned roles stored in the role field. Use $user->hasRole() to check if a user has a specific role:
<?php
/** @var $user \ByJG\Authenticate\Model\UserModel */
if ($user->hasRole('admin')) {
echo "User is an administrator";
}
if ($user->hasRole('moderator')) {
echo "User is a moderator";
}
// Set a role
$user->setRole('admin');
$users->save($user);
// Get current role
$role = $user->getRole();
The hasRole() method performs case-insensitive comparison, so hasRole('admin') and hasRole('ADMIN') are equivalent.
UserModel Properties
The UserModel class provides the following properties:
| Property | Type | Description |
|---|---|---|
userid | string|int|Literal|null | Primary key. Generated by the database unless you override it. |
name | string|null | User's display name. |
email | string|null | User's email address. |
username | string|null | Unique username (used when LoginField::Username is selected). |
password | string|null | Hashed password. Uses PasswordSha1Mapper by default. |
role | string|null | Optional application role. |
createdAt | string|null | Automatically set when the record is inserted. |
updatedAt | string|null | Automatically updated whenever the record is saved. |
deletedAt | string|null | Nullable soft-delete timestamp (requires manual handling). |
properties | UserPropertiesModel[] (array) | Loaded via getProperties() or manipulated through helpers. |
Next Steps
- Authentication - Validate user credentials
- User Properties - Store custom user data
- Password Validation - Enforce password policies