Answer the question
In order to leave comments, you need to log in
How to implement access to the database in the user class?
I want to create a user class, but how can I access the database in it?
Would it be ok to do it like this?
class User{
private static $db = '';
public static function setup($type, $user, $pass, $opt)
{
self::$db = new PDO($type, $user, $pass, $opt);
}
}
User::setup($type, $user, $pass, $opt);
Answer the question
In order to leave comments, you need to log in
Would it be ok to do it like this?
How to implement access to the database in the user class?
public static function setup($pdo)
{
self::$db = $pdo;
}
There, in the next thread, FanatPHP correctly wrote that in order to understand why it is not necessary to do this, experience is needed.
But if you try very briefly and without introducing "extra classes", then, nevertheless, I think this whole thing can be improved a little:
1) The user repository should be responsible for the user repository
2) The user should be responsible for the user
3) For the connection to the database - connection to the database
Your captain is obvious)
Does it seem clear here? Then let's do:
// Соединение к БД
$connection = new PDO(...);
// Хранилище с одним "findById"
class UsersDatabaseRepository
{
public function __construct(PDO $connection) { ... }
public function findById(int $id): ?User
{
$stmt = $this->prepare('SELECT * FROM `users` WHERE id = ? LIMIT 1');
$stmt->execute([$id]);
return new User($stmt->fetch(PDO::FETCH_ASSOC)) ?: null;
}
public function save(User $user): void
{
// ...
}
}
// Юзер с одним полем "id"
class User
{
public int $id;
public function __construct(array $attributes)
{
$this->id = $attributes['id'] ?? 0;
}
}
// В качестве бонуса: Теперь у нас один и тот же юзер может храниться где угодно!
// А сам User мы вообще не трогали - просто добавили новый класс, который хранит всё в файликах
class UsersFilesystemRepository
{
public function findById(int $id): ?User { /* какой-то код */ }
}
// В качестве бонуса N2: А ещё мы точно так же можем получать этого
// юзера через API с какого-нибудь GitHub
class UsersGithubRepository { ... }
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question