ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

MY_Model Base CRUD Model

November 08, 2009 9:02am

Subscribe [19]
  • #1 / Nov 08, 2009 9:02am

    Jamie Rumbelow

    546 posts

    I’ve recently released an extended Model class to use in CodeIgniter applications that provides a base CRUD pattern for your models. It gives you the core CRUD functionality, as well as support for before_create and after_create callbacks and some clever table name guessing.

    Usage
    Drag the MY_Model.php file into your application/libraries folder. CodeIgniter will load and initialise this class automatically for you. Then all you have to do is make sure all your models extend from MY_Model and all the functionality will be baked into your models automatically!

    Tutorial
    I’ve written a tutorial that takes a reasonable look at the functionality provided by the entire class, as well as my MY_Controller Controller System on my delightful blog. Check it out and feel free to leave a comment.

    Download
    You can get the source directly from GitHub, where I’ll be updating the library. You can also fork it and customise it yourself! Alternatively, you can download it as a .zip or a .tar.

    Naming Conventions
    This class will try to guess the name of the table to use, by guessing the plural of the class name. If the table name isn’t the plural and you need to set it to something else, just declare the $table instance variable and set it to the table name. Some of the CRUD functions also assume that your primary key ID column is called _’id’_. You can overwrite this functionality by setting the _$primary\_key_ instance variable.

    Upcoming Features
    * Support for validations
    * Function reference
    * Before and after update callbacks
    * Better table name guessing
    * Better support for associations and JOINs

    Version History
    * 1.1.0 Two new methods, count_by() and count_all(), made use of some ActiveRecord methods and optimisations
    * 1.0.5 Added support for custom primary keys
    * 1.0.0 First release

  • #2 / Nov 08, 2009 9:43am

    hugle

    289 posts

    Thanks,

    nice pack of functions!

  • #3 / Nov 08, 2009 12:58pm

    imn.codeartist

    145 posts

    Naming Conventions
    This class will try to guess the name of the table to use, by guessing the plural of the class name. If the table name isn’t the plural and you need to set it to something else, just declare the $table instance variable and set it to the table name. Some of the CRUD functions also assume that your primary key ID column is called ‘id’.

    Well there are also lot more people who don’t prefer calling primary key id as “Id”.. so in that case your library is not useful right ??

  • #4 / Nov 08, 2009 1:01pm

    Jamie Rumbelow

    546 posts

    Naming Conventions
    This class will try to guess the name of the table to use, by guessing the plural of the class name. If the table name isn’t the plural and you need to set it to something else, just declare the $table instance variable and set it to the table name. Some of the CRUD functions also assume that your primary key ID column is called ‘id’.

    Well there are also lot more people who don’t prefer calling primary key id as “Id”.. so in that case your library is not useful right ??

    Not at all. That’s just the way I do things. If you’ve got an issue with that just change it.

  • #5 / Nov 08, 2009 7:06pm

    Jamie Rumbelow

    546 posts

    I just updated the class to allow for custom primary key names - by default it will assume your primary key is “id” but you can now change that by setting the $primary_key instance variable to the primary key of your table.

    Jamie

  • #6 / Nov 09, 2009 11:05am

    Boris Strahija

    129 posts

    I think it would be really great if there would be a save() method, so something like this would be possible:

    $post = new Post();
    $post->title = 'Lorem ipsum';
    $post->body = 'Test…';
    $post->save();

    I was working on somethig very similar but lately I don’t have so much time 😉

    Oh, and please use tabs instead of spaces for code indenting 😊

  • #7 / Nov 09, 2009 2:15pm

    Jamie Rumbelow

    546 posts

    Boris,

    You’re looking for an ORM! My MY_Model is merely a CRUD base and won’t ever be that advanced to support ORM and relationships etc. It’s just a quick and easy way of reusing replicated functionality across your models.

    Jamie

  • #8 / Nov 09, 2009 2:28pm

    Boris Strahija

    129 posts

    I wasn’t talking about an ORM, just the part for saving objects seems to be a nice addon.
    Relationships are of course an overkill for a simple class like that.
    My extended Model class has something like this:

    function MY_Model()
    {
        ...
        
        parent::Model();
                
        // Get the DB table name
        $this->_get_table_name();
                
        // Load all fields if table exists
        $this->_get_table_fields();
        
        ...
    } //end __contruct()

    Getting the fields:

    private function _get_table_fields()
    {
        if ($this->db->table_exists($this->table)) :
            $this->fields = $this->db->list_fields($this->table);
        else :
            echo "The table '", $this->table, "' does not exist.";
            exit();
        endif;
        
    } //end _get_table_fields()

    And the save method:

    function save($id = NULL)
    {
        foreach ($this->fields as $key=>$field) :
            if (isset($this->$field)) $data[$field] = $this->$field;
        endforeach;
                
        // if ID is set update a record
        if ($id || isset($this->id)) :
            if ($id) $this->update($id, $data);
            else $this->update($this->id, $data);
        else :
            return $this->insert($data);
        endif;
        
    } //end save()

    That’s it, nothing fancy 😉

  • #9 / Dec 02, 2009 5:09am

    Jamie Rumbelow

    546 posts

    I wasn’t talking about an ORM, just the part for saving objects seems to be a nice addon. Relationships are of course an overkill for a simple class like that.

    That sounds lovely, but sorry, it’s a bit too much of an ORM for my liking 😉 The idea behind this is to provide a simple CRUD interface with a few niceties, nothing more. Otherwise you get into the realms of developing an ORM and that’s a totally different project.

    Jamie

  • #10 / Dec 02, 2009 5:22am

    Jamie Rumbelow

    546 posts

    Update 1.1.0
    Tidied up a bit, added two new methods count_by() and count_all(), moved some stuff over to some ActiveRecord methods I’d overlooked changed the syntax a bit etc. Had a lot of help with Phil Sturgeon on this one, so many thanks to him. I’ve also updated the first post with a link to a tutorial found on my blog.

    Cheers!

  • #11 / Dec 17, 2009 7:02pm

    happydude

    45 posts

    I want to make a suggestion for MY_Model.
    Please, add $limit and $offset to the functions that get many rows (get_many_by and get_all) as most times I have to write custom models to limit the amount of data and from where it gets fetched. I also need offset for pagination purposes.

    Thanks in advance.

  • #12 / Dec 18, 2009 9:19am

    Jamie Rumbelow

    546 posts

    Update 1.1.1
    A limit() method. Call it before any methods to add a LIMIT clause to your query. Takes two parameters - the limit integer and an optional offset.

  • #13 / Dec 18, 2009 9:48am

    happydude

    45 posts

    errrm, sorry. Thank you so much for your fast response and fast action.

    This one just popped into my head one hour after I made my last post and I am just checking this thread now. An order_by method will be handy too. It should handle strings or multiple array containing fields with which the result set will be ordered and the order_by value (asc, desc, random).

    e.g. $this->product->order_by(‘sort = asc, date = desc’)->get($id); //string
    and $this->product->order_by(array(‘sort’ => ‘asc’, ‘date’ => ‘desc’)->get($id); //array

    Following your limit() method in the latest release, I’ve got something working on my end. Just thought I should let you know.

    It’ll be my last request though for this library though. 😉

    Thanks for the simple but great libraries. They are lifesavers. 😊

  • #14 / Jan 04, 2010 3:28pm

    megabyte

    179 posts

    Tutorial
    I’ve written a tutorial that takes a reasonable look at the functionality provided by the entire class, as well as my MY_Controller Controller System on my delightful blog. Check it out and feel free to leave a comment.

    Your website has changed. Can you give an update on where your tutorial is for your MY_Model please.

    I’m trying to learn more about it. Specifically:

    /**
         * Runs the before create actions.
         *
         * @param array $data The array of actions
         * @return void
         * @author Jamie Rumbelow
         */
        private function _run_before_create($data) {
            foreach ($this->before_create as $method) {
                $data = call_user_func_array(array($this, $method), array($data));
            }
            
            return $data;
        }
        
        /**
         * Runs the after create actions.
         *
         * @param array $data The array of actions
         * @return void
         * @author Jamie Rumbelow
         */
        private function _run_after_create($data, $id) {
            foreach ($this->after_create as $method) {
                call_user_func_array(array($this, $method), array($data, $id));
            }
        }


    Thanks.

  • #15 / Jan 04, 2010 6:36pm

    Jamie Rumbelow

    546 posts

    Sorry about that, the first post is updated.

    Jamie

.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases