38

I'm starting with CodeIgniter and after several hours diving in Google I'm a bit confused.

Let's try to explain my question with a easy example: I have a table 'car' with the fields 'name' and 'color'. Therefore I want to have a php class Car, so that my code could look finally like this:

$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!)

Therefore, I am looking for something pretty similar to what you have in RubyOnRails or Django (Python). I need to handle all kind of relationships, and to be able of write code in a true OOP+MVC way.

These are my failed approaches to get it:

Using an external ORM (DataMapper, Doctrine, AcidCrud...)

They either requires too many settings, or they handle relationships in a poor way.

Using CodeIgniter classes (to extend the CodeIgniter's Model class)

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);
}

And so on... Problem with this approach is that if a do a var_dump() of a $car object, I see that it contains a lot of stuff from the CodeIgniter, such as the objects CI_Config, CI_Input, CI_Benchmark, etc. Therefore I think this is not a good solution, because each object of my class Car, it will contain a lot of repeated data, (it will have a poor performance!), isn't it?

Not using the CodeIgniter's models

I could make my models without extending them from CodeIgniter's Model class, and then using the regular PHP5 constructor (__construct() instead of function Car()), but problem in this case is: how I access to the $db object to make querys using the CodeIgniter's ActiveRecord? and, how I load the models (its classes) within the controllers?

3
  • 3
    Good question, the codeigniter models require a lot of effort when manipulating hierarchical data. I would really like to define and validate forms in models. Perhaps some mashup of Doctrine and the form library will suffice.
    – Benbob
    Aug 9, 2010 at 7:38
  • 1
    Why do you want to use PHP if you have experience with Rails and Django? Apr 21, 2011 at 5:00
  • RedBean is a great extremely easy to use ORM May 10, 2011 at 10:22

10 Answers 10

14

You probably want something like this:

   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;
        }
    }

Hope that helps!

4
  • Note that this class is outside of the Codeigniter Model - You should probably place it in /system/application/libraries and then load it using $this->load->library('cars');
    – Tilo Mitra
    Jan 26, 2010 at 19:44
  • 12
    This isn't ORM at all. This is basically just accessing the database abstraction library inside an object. Apr 22, 2011 at 3:55
  • 4
    He never explicitly stated for an ORM solution, and I never said this was ORM. Also it seems a little condescending to downvote the chosen answer, don't you think?
    – Tilo Mitra
    Apr 22, 2011 at 17:06
  • In my haste I had basically locked on the actual title of the post, which mentions ORM. CI's DB abstraction, which is referred to as an implementation of ActiveRecord, is IMHO not the correct MVC way to do things since it does not have a class properties to column mapping, see: en.wikipedia.org/wiki/Active_record_pattern. Personally having worked before with Kohana I missed this feature, especially since it allows you to ignore the need to explicitly escape data most of the time. Apr 24, 2011 at 9:07
9

Try with Doctrine, is a great ORM and can be easily integrated in CodeIgniter.

2
4

take a look the the codeigniter wiki page for ORM

http://codeigniter.com/wiki/ORM/

1
3

For future Googlers, here is a tutorial I wrote up about how to integrate CodeIgniter 2 with Doctrine 2.

Let me know if you have any issues.

2

I had good luck with using Propel with codeigniter.

1
  • please share the link for reference Nov 9, 2016 at 5:41
2

check out GAS ORM it sounds pretty good, handy and easy to use. some features of this ORM implementation for CodeIgniter:

  • Supported databases : cubrid, mssql, mysql, oci8, odbc, postgre, sqlite, sqlsrv. (including PDO, if you keep sync with CI repo)
  • Support multiple database connections.
  • Support multiple relationships.
  • Support composite keys (for key that define relationships).
  • Auto-create models from database tables and vice versa.
  • Auto-synchronize models-tables by creating migrations file.
  • Per-request caching.
  • Self-referential and adjacency column/data (hierarchical data).
  • Eager Loading to maximize your relationship queries (for performance manner).
  • Various finder methods (can chained with most of CI AR) and aggregates.
  • Validation and auto-mapping input collection with minimal setup.
  • Hooks points to control over your model.
  • Extensions to share your common function/library across your model.
  • Transactions and other CI AR goodness.
  • Included phpunit test suite to ensure most of API consistency.

there is one form with spark support -> so it's easy to install

1

What you want to do is create a library that extends the ActiveRecord class. Some people are ahead of you:

http://codeigniter.com/wiki/ActiveRecord_Class/

good mods in the thread, here:

http://codeigniter.com/forums/viewthread/101987/

If you're looking for ORM methods that are general to your app, just extend the ActiveRecord class. For my application, knowing the structure of a table allows me to scaffold (auto-generate) forms, and do other mapping. I do API-to-API mapping, so I include a GetStructure() method in MyActiveRecord and build other things from there.

(RoR snickering can bugger off now)

Edit: while I am a fan of the scope and power of Doctrine, I think it's demand for command-line usage places it beyond the spirit of CI. What's right for you is what's right for you, but if I'm going to use Doctrine, I might as well use Symfony, right? Or RoR, for that matter, right?? See where I'm gong with this? Right tool for the right time.

1
  • I disagree that Doctrine is too 'heavy' for CodeIgniter. The "command-line usage" (it doesn't have to be through a command-line - you can easily place the model generation inside a CI controller and call it from the web) is simply to generate model definitions that massively reduce the amount of work you need to do inside CodeIgniter to handle models. In my mind the spirit of CI is all about rapid development speed, and Doctrine helps massively with that.
    – Alex Dean
    Feb 15, 2011 at 11:20
1

I used CodeIgniter with Propel and they really mixed well. I've used like that for a while and got a few webapps working that way. Since I found a few awful ways to do it ( some included modifiying Apache's configuration!!). I decided to publish a blog post on how to do it. You can read it here.

Hope I can help!

1
  • Hi @David Conde I read your post, can you precise to me what you mean by "the best way to start is copying Propel’s runtime into that folder" ? Do you mean the whole folder of propel ? Or a specific folder ?
    – pollux1er
    Mar 7, 2016 at 12:51
0

I think php-activerecord is a very good drop-in ORM. I've used it with the Slim Framework a few times and I think it would be a great alternative to using CI's native model class. Here is some sample code and the link:

$post = new Post();
$post->title = 'My first blog post!!';
$post->author_id = 5;
$post->save();

PHP ActiveRecord

-1

i know this is quite old, but for those who are just using codeigniter now and wannt to use an orm with it can use this tutorial to integrate propel with codeigniter

http://llanalewis.blogspot.com/2013/06/installing-propel-in-codeigniter.html

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.