我想从数据库(使用PDO)加载数据并将其推送到类中。但这将是通用的,因此我正在使用一个抽象类,它将执行所有基本操作。每个子类(每个数据库表一个)应尽可能减少。
同时,我想控制公共属性和功能。
abstract class myTable {
protected static $table
protected static $classname
public function __construct($id) {
$pdo = new MyMagicPdoClass();
$sql = "SELCT * FROM ".self::$table." WHERE id = {$id}";
$stmt = pdo->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_CLASS, self::$classname);
// Here is my OBJECT in the CLASS-TYPE i want (POINT 1)
// Show evidence for testing:
echo "<pre>",print_r($result),"</pre>";
}
}
class User extends myTable {
// for each accessable field: property-name = column-name --> as PRIVATE
private $id;
private $FirstName;
private $LastName;
private $Email;
// avoid automated property creation (by PDO::FETCH_CLASS), the
// use of "__set()"-method helps to filter all properties out.
// Only properties (declared in this class) that match with the name of the column
// will be initiated. If not doing this, ALL columns would be
// automatically created as an PUBLIC property of the class.
// So no control via Gettes and Setters.
public function __set($name, $value) {}
public function __construct($id = null) {
self::$classname = __CLASS__; // will be used in abstract class
self::$table = "tblUser"; // will be used in abstract class
// call onstructer of parent-class
parent::__construct($id);
/**
* I GUESS, HERE SHOULD BE THE MAGIC (POINT 2)
*/
}
// SETTERS
public function setFirstName($value) {
$this->FirstName = $value;
}
[...]
// GETTERS
public function getFirstName() {
return $this->FirstName;
}
[...]
// SOME METHODS
public function doWhatOnlyThisClassShallDo() {...}
}
用法示例
$id = 234;
$user = new User($id);
echo $user->FirstName; // shall be forbidden
echo $user->getFirstName(); // shall be used instead
echo $user->doWhatOnlyThisClassShallDo(); // shall be possible
在父构造函数中,我具有要在$result
中寻找的对象。现在,我想把它作为子类的构造函数的结果(请参见第2点)。
可以肯定的是,我现在可以通过抽象类的结果手动加载构造函数中的每个属性,但是如上所述,我希望每个子类都尽可能简单。最重要的是,使用FETCH_CLASS所做的所有工作都是无用的,因为我只是将值分配给子类的构造函数中的属性。
有什么建议吗?还是我使用了错误的方法?
答案 0 :(得分:0)
因此,您想从数据库中获取行并将每个列值填充到匹配属性中?另外,我确定您要执行safe and secure database queries。我想这就是您要寻找的东西:
2L.LongPow(p) : 0L