Comming from Java I feel more comfortable using Objects and Classes rather than plain functions. The question is:
I currently have a ‘User’ class, which offers me methods such as getting access level, changing profile, erasing notifications, etc. Each method uses a query to my db to pull out the info needed or update it. But in the constructor I get the basic info: id, email, name and lastname (which are the fields I use the most on every method).
Which design would you use:
(Current)
class User{
private $id;
private $email;
...
function __construct($id){
//Connect to database
...
$this->id=$id;
$thid->name=$row['name'];
...
}
function getEmail(){
return $this->email;
}
...
}
Or:
class User{
private $id;
function __construct($id){
$this->id=$id;
}
function getEmail(){
//Connect to database using id
return $row['email'];
}
...
}
I feel that being just a couple of text fields the performance would not be improved by the second one, but I’m a begginer so I don’t know.
Thanks in advance
Do version 1 and cache the results of your db query into fields in your object. You don’t want to go to the db every time over the lifespan of the object and in a web app an object’s lifetime is only the single page request, so there is little chance of non-atomic data operation pollution.
Further, don’t connect to the database in your constructor. Take the time to build a class factory to generate your classes. Honestly you can even write a very simple code generator to generate both the model class that stores all your data fields and the mapper class that goes to the db and builds your object from a table in under 100 lines of code.
If you have the extra time, learn and use a framework like zend or for just data, doctrine…
(FWIW, I think learning simple zend table stuff would net you a time savings)