PHP MVC:模型之间的关系(人物:联系人、星座等)
我现在正在学习PHP、MVC和“PHP的简单MVC框架” 我有一个模型叫Person:PHP MVC:模型之间的关系(人物:联系人、星座等),php,model-view-controller,frameworks,Php,Model View Controller,Frameworks,我现在正在学习PHP、MVC和“PHP的简单MVC框架” 我有一个模型叫Person: <?php namespace Models; use Core\Model; use Helpers\Database; use Core\Error; class Person extends Model { protected $db; protected $tname = 'person'; function __construct() { par
<?php
namespace Models;
use Core\Model;
use Helpers\Database;
use Core\Error;
class Person extends Model {
protected $db;
protected $tname = 'person';
function __construct() {
parent::__construct ();
$this->db = Database::get ();
}
public function getPersons() {
return $this->db->select ( "SELECT firstname, lastname FROM " . PREFIX . $this->tname );
}
public function insertPerson($data) {
if (is_array ( $data )) {
$this->db->insert ( PREFIX . $this->tname, $data );
return $this->db->lastInsertId ( 'personID' );
} else {
// Error::display ( '$data is not an array.' ); // TODO: not in model
}
}
}
这是一个非常开放的问题,因为有很多方法可以做到这一点。我的方法是让getter在需要时负责初始化模型
例如,类Person可以有contact()、living()等方法。这些方法看起来像这样:
public function contact()
{
if($this->_contact_model == null) {
$this->_contact_model == new Contact();
// ...
}
return $this->_contact_model;
}
然后,从$person对象访问联系人方法应该非常简单:
$person->contact()->getSomeContactProperty();
$person->contact()->getSomeContactProperty();