Please note: I am not looking for the "use framework" answers. I am trying to structurally improve the way coding websites and accessing databases from PHP.
I am creating a web service from scratch, without any frameworks. I am using the LAMP stack and trying to learn a bit of PHP OO functionality while I am in it. Earlier, I used OO to create mobile applications.
I’ve been doing this for several months (as planned, do not worry). Along the way, I ran into several structural problems, making me wonder what the best way would be to make an object code object.
To a large extent, all problems are related to the database in some way. Say we have a class DBand a class User. In most cases, I only need to get one information from the database. I thought that a good way to handle this was to have a global variable $_dband have an object Userquery such a database (simplified):
class User {
function __construct($id) {
global $_db;
$q = $_db->query("SELECT name, mail FROM user WHERE id = ?", $id);
$this->loadProperties($q);
}
}
Now let's say that we have a page that shows a list of users. I still want to make objects Userfor each of them, but I do not want to query the database for each individual user.
So, I am extending the class Userto take an object as an argument:
class User {
function __construct($id) {
if(is_object($id))
$q = $id;
else {
global $_db;
$q = $_db->query("SELECT name, mail FROM user WHERE id = ?", $id);
}
$this->loadProperties($q);
}
}
Now I can create a list, for example, of the 100 most recently created and active accounts:
$user_list = [];
$q = $_db->query("SELECT name, mail FROM user WHERE banned = 0 ORDER BY date_created DESC LIMIT 100");
while($a = $_db->fetch($q))
$user_list[] = new User($a);
, : User , . , .
, , DB User, :
class DB {
public function getUsers($where) {
$q = $this->query("SELECT name, mail FROM user WHERE ".$where);
$users = [];
while($a = $this->fetch($q))
$users[] = new User($a);
}
}
:
$user_list = $_db->getUsers("banned = 0 ORDER BY date_created DESC LIMIT 100");
getUsers() , SQL-, . , getUsers() SQL- . , .
, , OO PHP. , PHP , . , User::getName():
class User {
public function getName() {
return $this->name;
}
}
, . , . . , , .
, . , OO, , , , , , .
, ( , ), , new User. , Registration ( , ):
class Registration {
function createUser() {
$form = $this->getSubmittedForm();
global $_db;
$_db->query("INSERT INTO user (name, mail) VALUES (?, ?)", $form->name, $form->mail);
if($_db->hasError)
return FALSE;
return $_db->insertedID;
}
}
, , , . , , .
, , . , . , . , SQL-?
.
, global $_db. , , , , . DB, .