我从 CodeIgniter 开始,在 Google 中潜入几个小时后,我有点困惑。
让我们尝试用一个简单的例子来解释我的问题:我有一个表“car”,其中包含字段“name”和“color”。因此我想要一个 php 类 Car,这样我的代码最终看起来像这样:
$car = new Car('BMW', 'red'); //new $car Object
$car->save(); //this will make an SQL insert to the table 'car'
//Lets query all cars
$cars = Car::get_all();
//cars will be an array of Car objects, (not a set of rows!)
因此,我正在寻找与 RubyOnRails 或 Django (Python) 中的内容非常相似的东西。我需要处理各种关系,并且能够以真正的 OOP+MVC 方式编写代码。
这些是我失败的方法:
使用外部 ORM(DataMapper、Doctrine、AcidCrud...)
他们要么需要太多的设置,要么处理人际关系的方式很糟糕。
使用 CodeIgniter 类(扩展 CodeIgniter 的 Model 类)
class Car extends Model{
public function Car($name='',$color='')
{
$this->name = $name;
$this->color = $color;
parent::Model();
}
public function save()
{
$data = array(
'name' => $this->name ,
'color' => $this->color
);
$this->db->insert('cars' $data);
}
依此类推...这种方法的问题是,如果对 $car 对象执行 var_dump(),我会发现它包含来自 CodeIgniter 的很多内容,例如对象 CI_Config、CI_Input、CI_Benchmark 等。因此我认为这不是一个好的解决方案,因为我的Car类的每个对象,它都会包含很多重复的数据,(它的性能会很差!),不是吗?
不使用 CodeIgniter 的模型
我可以制作模型,而无需从 CodeIgniter 的 Model 类扩展它们,然后使用常规 PHP5 构造函数(__construct() 而不是函数 Car()),但本例中的问题是:我如何访问 $db 对象来进行查询使用 CodeIgniter 的 ActiveRecord?以及如何在控制器中加载模型(其类)?