• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to write models

Hi, I'm a new CodeIgniter user and this is my first post to this forum.

I'm having some problems understanding how to structure model classes. With Rails we use class methods for tasks like find or create records in the database, and we use instance methods to access properties of each object. How can I implement this logic with CodeIgniter? When I do
I get an instance of the model class.

Thank you,

Hello Francesco and welcome around this forums!

About your post:

did you read the user guide section about models in codeigniter?

There you can find a good example how to set up a model and how
to call the methods of your model class.

If you get stuck somewhere post the problem here.

here some best tuts


yes, I read that guide. The problem is basically that I don't understand how to map objects (database records) in CI since models are just helpers for db operations.

I'll use an example. We have two entities: posts and comments (each post can have many comments). This could be a basic posts model:
class Post extends CI_Model
    function __construct()
    function get_posts()
        $query = $this->db->get('posts');
        return $query->result();

Now in the posts controller I can use:
$posts = $this->post->get_posts();

But $posts is not an array of objects, it's just a multidimensional array. So I don't know how (and where) to add a method to fetch comments for a post.

p.s. I'm sorry for my English Smile

I don't know rails but after reading posts about that here in the forums I think
the rails approach is a different one compared to CI.

Maybe you are looking for an ORM library?

Yes, I think that the ORM approach is what I need, but it's a library really necessary for this task?

EDIT: I'm trying DataMapper now and I think it's weird that to get (for example) all my posts I have to instantiate a Post and then call a method on the instance:
$post = new Post();
$posts = $post->get();

Do you know of any other library that use a different approach with ORM?

EDIT 2: I did a print_r of the $posts variable (2 rows with 3 attributes) and I got 1291 lines (within a pre tag)! Is that normal?

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.