Reputation: 33
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 -
Upvotes: 3
Views: 1298
Reputation: 12866
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 );
Upvotes: 2
Reputation: 1888
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.
Upvotes: 2