我的老板给了我建造一个比我们现在更好的成型物体的任务。该公司过去几年一直在使用意大利面条锅,我已经被带去清理它。
我正在尝试获取PHP类用户,以便在实例化时它看起来像这样:
<?php
$user = new User();
$user->firstname;
$user->lastname;
$user->haircolor;
$user->eyecolor;
$user->homephone;
依此类推。现在,如果它们都在一个表上,但为了获得所有这些数据,我将不得不查询几个表。当然,很好。但是,如果我定义一个类来获取所有用户信息,则必须在构造函数中调用多个查询或大量连接。对?
有更好的方法吗?目标是以最佳加载时间更好地组织代码。老板特别希望拥有变量而不是函数。我不确定背后的原因是什么,他只是让我这样做。
所以,我的具体问题是,通过调用多个查询和/或使用巨大的JOIN,有更简单,更快捷的方法吗?
答案 0 :(得分:0)
class User {
public $id;
public $firstname;
public $lastname;
public $email;
public $creationdate;
public $user_image;
public static function find_all(){
return self::find_by_sql("SELECT * FROM users");
}
public static function find_by_id($id=0){
$result_array = self::find_by_sql("SELECT * FROM users WHERE id={$id} LIMIT 1");
//$found=$database->fetch_array($result_set);
return !empty($result_array)?array_shift($result_array):FALSE;
}
public static function find_by_sql($sql=""){
global $database;
$result_set=$database->query($sql);
//return $result_set;
$object_array=array();
while($row=$database->fetch_array($result_set)){
$object_array[]=self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record){
//long form
$object=new self;
//dynamic
foreach ($record as $attribute=>$value){
if($object->has_attribute($attribute)){
$object->$attribute =$value;
}
}
return $object;
}
private function has_attribute($attribute){
//get_object_vars returns an associative array with all attributes
$object_vars=get_object_vars($this);
//we will return true or false
return array_key_exists($attribute, $object_vars);
}
//dynamically add the public class variable and it will automatically assign the value
//if you are joining the queries than it will also work
//and your code will work here
//$user = new User();
//$user->firstname;
//$user->lastname;
//$user->haircolor;
//$user->eyecolor;
//$user->homephone;
}
?>
答案 1 :(得分:0)
除了我的评论之外,您还可以为数据库信息实现一种延迟加载。例如,假设您有一个用户,并且用户可以作为朋友连接到其他用户。但是,如果每次创建User对象时都不需要朋友(这也允许您在对象上多次使用getFriends(),但只从数据库中获取一次数据):
class User {
private $id;
private $name;
private $friends;
public function __construct($id) {
// If you have a caching solution, you can check the cache first
// Load user from database, fetch and set id and name.
}
public function getFriends() {
if ($this->friends != null) {
return $this->friends;
}
// If you have a caching solution, you can check the cache first
// Fetch friends from databse, set instance variable and return it
}
public function save() {
// Save information to database and possibly cache
}
}