The other day, while developing my PHP project and implementing the User
class, i started to wonder how this class should interact with the MySQL database the project is using.
Let me start with an example: let's say I have a getName()
method, inside the User
class, that returns the user's real name. What's the more fitting way to implement that method?
I came up with 2 solutions:
I put the DB query inside the
getName()
and only get what I need like this:public function getName() { // MySQL query code here }
I create a
load()
method inside theUser
class that load all the user data inside the class structure and then thegetName()
is something like this:private $name; // Load all user data inside the class' structure public function load() { $this->name = // MySQL query here } public function getName() { return $this->name; }
I thought, not sure if mistakenly or not, that the first way is more efficient because i only get the data I need, while the second way is more OOP but less efficient.
So, here's the question: what is the better way? Why? Are there better ways?