This is a design issue that I encounter regularly, and I would like to find a general idea of the subject. The code given here is just an example.
At the design stage, it is easy to decide that you need an object:
User
==========
Unique ID
Login name
Password
Full name
And it's easy to convert it to a database object:
CREATE TABLE user (
user_id INT NOT NULL PRIMARY KEY,
username VARCHAR(15) NOT NULL UNIQUE,
password_hash CHAR(32) NOT NULL,
full_name VARCHAR(50)
);
My doubts start at the PHP level. Obvious conversion:
<?php
class User{
public $user_id, $username, $full_name;
}
?>
However, how should I fill in the actual values?
I can save the DB-agnostic class:
<?php
class User{
public $user_id, $username, $full_name;
public function __construct($user_id, $username, $full_name){
$this->user_id = $user_id;
$this->username = $username;
$this->full_name = $full_name;
}
}
?>
But then I need to run the request somewhere else ...
I can encapsulate it inside the class constructor:
<?php
class User{
public $user_id, $username, $full_name;
public function __construct($user_id){
$sql = 'SELECT username, full_name FROM user WHERE user_id=?';
$parameters = array($user_id);
$res = get_row_from_db($sql, $parameters);
$this->user_id = $user_id;
$this->username = $res['username'];
$this->full_name = $res['username'];
}
}
?>
It looks elegant, but it stops me from doing a lot of things with the class:
- Confirm the user by username and password ($ user_id is not yet known)
- ( 100 , 100 )
, , , . ? ? ? , , .
:
==== ====
, . , , " " PHP :
, , . , .