CodeIgniter,模型和ORM,如何处理?

jäv*_*ävi 37 php orm codeigniter

我从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!)
Run Code Online (Sandbox Code Playgroud)

因此,我正在寻找与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);
}
Run Code Online (Sandbox Code Playgroud)

等等......这种方法的问题在于,如果做一个$ car对象的var_dump(),我发现它包含很多来自CodeIgniter的东西,比如对象CI_Config,CI_Input,CI_Benchmark等.所以我认为这不是一个好的解决方案,因为我班的每个对象都会包含很多重复数据,(它会有很差的表现!),不是吗?

不使用CodeIgniter的模型

我可以创建我的模型而不是从CodeIgniter的Model类扩展它们,然后使用常规的PHP5构造函数(__construct()而不是函数Car()),但在这种情况下的问题是:我如何访问$ db对象来进行查询使用CodeIgniter的ActiveRecord?以及如何在控制器中加载模型(其类)?

Til*_*tra 14

你可能想要这样的东西:

   class Cars {

    //List all neccessary vars here

    function __construct() {
        //get instance of Codeigniter Object and load database library
        $this->obj =& get_instance();
        $this->obj->load->database();
    }

//You can now list methods like so:
function selectCar($name, $color) {

        $this->obj->db->select('color')->from('car')->where('color', $color);
        $query = $this->obj->db->get();

        switch ($query->num_rows()) {
        case 0:
            return false;
            break;
        default:
            return $query->result();
            break;
        }
    }
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!

  • 这根本不是ORM.这基本上只是访问对象内的数据库抽象库. (11认同)
  • 他从未明确声明过ORM解决方案,我从未说过这是ORM.对你选择的答案来说似乎有点屈尊俯就,你不觉得吗? (4认同)

Dan*_*eti 9

尝试使用Doctrine,是一个很棒的ORM,可以很容易地集成到CodeIgniter中.