我正在使用 CodeIgniter 构建一个 php Web 应用程序,并且我正在尝试使用良好的 OO 实践——其中似乎有很多思想流派。我特别有一个类 biography_model 来与 MySQL 表交互。这个数据模型有一些类属性表示表中的列,但它也有一些表中没有的属性,例如$image_url
. 类构造函数接受一个可选的记录 ID 参数,然后从表中获取该记录并通过调用该get_biography()
方法设置所有对象属性,包括$image_url
不在表中的属性。这样我就可以在控制器中实例化一个新的 biography_model 对象,并准备好所有有用的属性:$bio = new biography_model($id);
但是,当我们从表中返回记录的多行结果集时,最好的方法是什么?对于每条记录,我还需要设置$image_url
. 我可以在控制器中执行此操作,方法是查询表中的记录列表,然后将每个 id 传递给新的 biography_model($id) 对象。但是后来我会遇到控制器绕过模型直接查询数据库的情况。
相反,我选择从 biography_model 中返回一个 biography_model 对象数组。
例子:
class Biography_model extends Model
{
/**
* This model manages biography information in the 'biography_content' table.
* If a biography ID is passed in when instantiating a new object,
* then all class properties are set.
*/
protected $id;
protected $person_name;
protected $title;
protected $image_file_name;
protected $image_url;
protected $biography_text;
protected $active;
/**
* Constructor
*
* If an id is supplied when instantiating a new object, then
* all class variables are set for the record.
*/
public function __construct($person_id = NULL)
{
parent::Model();
if(isset($person_id))
{
$this->set_property('id',$person_id);
$this->get_biography();
}
}
/**
* Sets supplied property with supplied value.
*/
public function set_property($property, $value)
{
// Set image path if $value is the file name
if($property == 'image_file_name')
{
$this->set_property('image_url',$this->get_bio_img_url($value));
}
$this->$property = $value;
}
/**
* Gets requested property value.
*/
public function get_property($property)
{
return $this->$property;
}
/**
* Returns the biography thumbnail image URL
*/
public function get_bio_img_url($image_name)
{
return $this->config->item('parent_url').'assets/img/biography/'.$image_name;
}
/**
* Get one or more biography entries
*/
public function get_biography()
{
// If the ID is set then set model properties.
if($this->get_property('id'))
{
$this->db->where('id',$this->get_property('id'));
$query = $this->db->get('biography_content');
if($query->num_rows() == 1)
{
foreach($query->row() as $key => $value)
{
$this->set_property($key, $value);
}
}
}
// Otherwise return result set of all biographies
else
{
// Get the list of record ID's
$this->db->select('id');
$query = $this->db->get('biography_content');
if ($query->num_rows() > 0)
{
// New array to return result set
$biography_list = array();
// For each record, return a new biography_model object
foreach($query->result() as $value)
{
$biography_list[] = new biography_model($value->id);
}
}
return $biography_list;
}
}
}
// End of Biography_model Class
有用。但这是一个合理的方法吗?还有其他更受欢迎的方法吗?我敏锐地意识到我正在查询数据库两次,但我不确定有更好的方法来处理这个问题。欢迎所有建议!
谢谢,狼