在php中有一个ActiveRecord样式类,将模型传递给包含外键/与其他模型的关系的模型的视图的正确方法是什么?我的控制器应该实例化相关类(user_id、category_id)然后将所有信息传递给视图,还是应该在模型和控制器之间生成一个新层来结合两者?本质上,我想我是在问 sql“join”查询应该去哪里?
在我的数据库中,我有一个名为 Article 的表,它看起来像,
+------------------+------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+------------+------+-----+-------------------+-----------------------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | NO | MUL | NULL | |
| title | char(30) | NO | | NULL | |
| subtitle | char(60) | YES | | NULL | |
| time | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| visible | tinyint(1) | NO | | 1 | |
| body | mediumtext | YES | | NULL | |
| category_id | int(10) | NO | MUL | NULL | |
| featured_mediaid | int(10) | YES | | NULL | |
+------------------+------------+------+-----+-------------------+-----------------------------+
我在我的文章类中实现了这个表:
Class Article extends DatabaseTable{
public $id = null;
public $title = null;
public $subtitle = null;
public $body = null;
public $time = null;
public $visible = null;
public $category_id = null;
public $user_id = null;
public $featured_mediaid = null;
/*.....methods for Article*/
}
和相关表格:
+-------------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | char(50) | NO | UNI | NULL | |
| description | char(50) | NO | | | |
| visible | tinyint(1) | NO | | 1 | |
+-------------+------------+------+-----+---------+----------------+
和一个类别:
Class Category extends DatabaseTable {
public $id = null;
public $name = null;
public $description = null;
public $visible = null;
/*... Some methods here */
}
我所有的类都继承自具有 getById 方法的 DatabaseTable:
Class DatabaseTable {
// ...
public static function getById($id){
try {
$connection = new PDO(Database::DB_DSN, Database::DB_USERNAME, Database::DB_PASSWORD);
$sql = "SELECT * FROM " . strtolower(self::get_called()) . " WHERE id = :id";
$statement = $connection->prepare($sql);
$statement->bindValue(":id", (int) $id, PDO::PARAM_INT);
$statement->execute();
$row = $statement->fetch(PDO::FETCH_ASSOC);
$connection = null;
}
/*catch(PDOException $exception) {
}*/
catch(Exception $exception) {
echo "An Unknown Exception Occured";
echo "Calling Class [" . self::get_called() . "] " . "Method [" . __FUNCTION__ . "]" ;
$connection = null;
echo $exception->getMessage();
}
$class = self::get_called();
return new $class($row);
}
public static function get_called(){
return get_called_class() ;
}
//...
}