Answer the question
In order to leave comments, you need to log in
How to get one object in different requests?
Hello! I'm quite confused about this OOP.
I need to create a list of objects like user . Each object will contain fields (there are many of them. First name, last name, address, photo, login, number of posts, subscribers, etc.).
Getting such a list of objects from the database is simple... We make a request:
We will get a list of users objects. It seems to be a profit, BUT ...
If in another request we need to display users who "liked" the post. Run the query again:SELECT * FROM `users`
SELECT u.*
FROM `likes` lk
INNER JOIN `users` u ON u.`id` = lk.`user_id`
WHERE lk.`post_id` = 1775
Answer the question
In order to leave comments, you need to log in
Let's start with the fact that the database is not about OOP. The database is something that has grown out of primitive files on the hard drive, where all sorts of different information that was born while working with the program is spit out.
The database aims to work very fast with gigantic amounts of data. The database has its own feature of the beauty of its own device, called normalization.
If you stick to everything you see, OOP, you will very soon notice that the development time will simply run into infinity.
And now for your example: you have a class called user. Data gets into it after requesting all users - and it works with them. And then the data gets into it after a request from users who put likes - it works with them too.
All. This is a ceiling, a masterpiece, OOP has done its job here. You can continue to code in peace.
Until we found out that the user model can change depending on the situation, and somewhere you will need a user model with an avatar model inside, and somewhere with an avatar model and also a token model ...
So far, everything is fine.
What you are talking about is called the Identity Map pattern and is implemented in some ORM systems such as Doctrine.
> Here is the question, how to make it so that you can use a single method to get user objects?
When getting data from the database, check whether there is an entity with the same identifier in the cache.
> Or is it still correct to create a new object in each request
Correctly, IMHO, that there would be only one object with one identifier, and if you need a different behavior - say it separately.
I'll add my two cents to Decadal
's answer
. I advise you to read the Laravel doc, or at least lumen (microframework, Laravel's brother), in particular the section about Eloquent. A lot has to fall into place.
Those. we have a user model:
$user = User::find(1); //пользователь с id = 1
$users = User:all(); //все пользователи
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question