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

#1
[eluser]papagno[/eluser]
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
Code:
$this->load->model('example');
I get an instance of the model class.

Thank you,
Francesco

#2
[eluser]LuckyFella73[/eluser]
Hello Francesco and welcome around this forums!

About your post:

did you read the user guide section about models in codeigniter?
http://ellislab.com/codeigniter/user-gui...odels.html

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.

#3
[eluser]Unknown[/eluser]
here some best tuts

http://net.tutsplus.com/articles/news/co...tch-day-1/

#4
[eluser]papagno[/eluser]
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.

#5
[eluser]papagno[/eluser]
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:
Code:
class Post extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }
    
    function get_posts()
    {
        $query = $this->db->get('posts');
        return $query->result();
    }

Now in the posts controller I can use:
Code:
$this->load->model('post');
$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

#6
[eluser]LuckyFella73[/eluser]
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?
http://datamapper.wanwizard.eu/

#7
[eluser]papagno[/eluser]
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:
Code:
$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.