What are the best practices for adapting a PHP class and function to retrieve permissions from a database instead of predefined constants?
When adapting a PHP class and function to retrieve permissions from a database instead of predefined constants, it is best practice to create a table in the database to store the permissions and their corresponding values. Then, modify the class and function to query the database for the permissions based on the user's role or ID.
// Assuming we have a database connection established
class Permissions {
public function getPermissions($userId) {
$query = "SELECT permission FROM user_permissions WHERE user_id = :userId";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':userId', $userId);
$stmt->execute();
$permissions = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$permissions[] = $row['permission'];
}
return $permissions;
}
}
// Example of how to use the Permissions class
$permissions = new Permissions();
$userPermissions = $permissions->getPermissions($userId);
// Check if a specific permission exists
if (in_array('admin', $userPermissions)) {
echo 'User has admin permission';
}