4
4
4sadly2020-04-17 14:54:24
PHP
4sadly, 2020-04-17 14:54:24

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

3 answer(s)
F
FanatPHP, 2020-04-17
@FanatPHP

Would it be ok to do it like this?

Of course it's okay.
There will be, for example, in the application 10 different classes - and there will be 10 connections to the database. 100 classes - 100 connections. So what?
How to implement access to the database in the user class?

In a good way, in the User class there should not be any access to the database. But you still have five years to understand this.
Therefore, you can simply connect from the database and pass a ready-made connection to the class
public static function setup($pdo)
    {
        self::$db = $pdo;
    }

But considering that you have no OOP, but a golem proceduralism, you can simply write global $ pdo in the "methods" of your "class" and not take a steam bath

V
Vitaliy K, 2020-04-17
@revenger

Not perfect, but you can try something like this

K
Kirill Nesmeyanov, 2020-04-18
@SerafimArts

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 { ... }

In the "big world" everything is a little more complicated. For example:
1) Passing an array to the User constructor is not very good.
2) findById is overcomplicated, and it can be completely simplified by moving similar "similar" code to a higher level in AbstractDatabaseRespotory
3) Working with a turnip (storage) is through an interface (more precisely, through a set of them), and not through an implementation.
Well, and so on...
In any case, at least such a division will allow you to organize your code more easily.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question