简体   繁体   中英

PHP OOP: retrieve data from database

I'm pretty new to OOP (and also in PHP programming), and I have some troubles using objects and interfacing them with db data (MySql in my case, but this is irrelevant).

I have on the DB a table USERS . I declared a class User in the PHP code, with the various properties and methods I need. The problem is interfacing this thing to db.
I put code to retrieve data from the db in the constructor, so when I need to work on a specific user, I simply write $user = new User($user_id); and start working with the object. When I've done I call a method on the object to save data on db, and this works pretty well.

The problem arise when I need data about many users in a single page , as in showing the complete list of users. With this approach, when I need the list of users, I have to instantiate all the objects, and this causes the code to make too many queries of the type SELECT * FROM users WHERE user_id = ... , instead than a single query such as SELECT Only_needed_fields FROM users WHERE 1 LIMIT 20 as I would've done in procedural code.

Which is the correct OOP approach to such a problem? Which is the good-practise alternative to retrieving data in the constructor?

Notice Please, don't suggest using frameworks of any kind - I'd like learn pure OOP PHP before using abstraction layers -

Your problem is that you are not seperating the layers of your application. What you should do is have a factory class instantiating your users that handles the database calls and let the user class only handle the business logic. This will also contribute to the testability of your code.

Your factory class could have two methods. One for loading a single user and instantiating it and another for loading a set of users.

A factory method is always plausible, then you can implement an optimised common query:

list($one, $two) = User::GetMultiple (array( 1, 2 ));

Translating into

SELECT * FROM users WHERE user_id IN ( 1, 2 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM