{"id":13560254,"url":"https://github.com/jamierumbelow/codeigniter-base-model","last_synced_at":"2025-05-15T07:05:55.813Z","repository":{"id":46916471,"uuid":"1383038","full_name":"jamierumbelow/codeigniter-base-model","owner":"jamierumbelow","description":"⛔️DEPRECATED CodeIgniter base CRUD model to remove repetition and increase productivity","archived":false,"fork":false,"pushed_at":"2018-04-04T15:10:18.000Z","size":172,"stargazers_count":1045,"open_issues_count":100,"forks_count":478,"subscribers_count":137,"default_branch":"master","last_synced_at":"2025-04-14T12:58:41.816Z","etag":null,"topics":["archived","deprecated","obsolete"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jamierumbelow.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2011-02-18T16:14:59.000Z","updated_at":"2025-03-30T20:27:24.000Z","dependencies_parsed_at":"2022-08-25T09:21:11.594Z","dependency_job_id":null,"html_url":"https://github.com/jamierumbelow/codeigniter-base-model","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jamierumbelow%2Fcodeigniter-base-model","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jamierumbelow%2Fcodeigniter-base-model/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jamierumbelow%2Fcodeigniter-base-model/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jamierumbelow%2Fcodeigniter-base-model/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jamierumbelow","download_url":"https://codeload.github.com/jamierumbelow/codeigniter-base-model/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254292042,"owners_count":22046426,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["archived","deprecated","obsolete"],"created_at":"2024-08-01T13:00:40.360Z","updated_at":"2025-05-15T07:05:50.806Z","avatar_url":"https://github.com/jamierumbelow.png","language":"PHP","readme":"DEPRECATED: codeigniter-base-model\n=====================================\n\n**Deprecated since I no longer use CodeIgniter. If anybody would like to take over maintainence of this repo, please get in touch.**\n\n[![No Maintenance Intended](http://unmaintained.tech/badge.svg)](http://unmaintained.tech/) [![Build Status](https://secure.travis-ci.org/jamierumbelow/codeigniter-base-model.png?branch=master)](http://travis-ci.org/jamierumbelow/codeigniter-base-model)\n\nMy CodeIgniter Base Model is an extended CI_Model class to use in your CodeIgniter applications. It provides a full CRUD base to make developing database interactions easier and quicker, as well as an event-based observer system, in-model data validation, intelligent table name guessing and soft delete.\n\nSynopsis\n--------\n\n```php\nclass Post_model extends MY_Model { }\n\n$this-\u003eload-\u003emodel('post_model', 'post');\n\n$this-\u003epost-\u003eget_all();\n\n$this-\u003epost-\u003eget(1);\n$this-\u003epost-\u003eget_by('title', 'Pigs CAN Fly!');\n$this-\u003epost-\u003eget_many_by('status', 'open');\n\n$this-\u003epost-\u003einsert(array(\n    'status' =\u003e 'open',\n    'title' =\u003e \"I'm too sexy for my shirt\"\n));\n\n$this-\u003epost-\u003eupdate(1, array( 'status' =\u003e 'closed' ));\n\n$this-\u003epost-\u003edelete(1);\n```\n\nInstallation/Usage\n------------------\n\nDownload and drag the MY\\_Model.php file into your _application/core_ folder. CodeIgniter will load and initialise this class automatically for you.\n\nExtend your model classes from `MY_Model` and all the functionality will be baked in automatically.\n\nNaming Conventions\n------------------\n\nThis class will try to guess the name of the table to use, by finding the plural of the class name. \n\nFor instance:\n\n    class Post_model extends MY_Model { }\n\n...will guess a table name of `posts`. It also works with `_m`:\n\n    class Book_m extends MY_Model { }\n\n...will guess `books`.\n\nIf you need to set it to something else, you can declare the _$\\_table_ instance variable and set it to the table name:\n\n    class Post_model extends MY_Model\n    {\n        public $_table = 'blogposts';\n    }\n\nSome 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:\n\n    class Post_model extends MY_Model\n    {\n        public $primary_key = 'post_id';\n    }\n\nCallbacks/Observers\n-------------------\n\nThere are many times when you'll need to alter your model data before it's inserted or returned. This could be adding timestamps, pulling in relationships or deleting dependent rows. The MVC pattern states that these sorts of operations need to go in the model. In order to facilitate this, **MY_Model** contains a series of callbacks/observers -- methods that will be called at certain points.\n\nThe full list of observers are as follows:\n\n* $before_create\n* $after_create\n* $before_update\n* $after_update\n* $before_get\n* $after_get\n* $before_delete\n* $after_delete\n\nThese are instance variables usually defined at the class level. They are arrays of methods on this class to be called at certain points. An example:\n\n```php\nclass Book_model extends MY_Model\n{\n    public $before_create = array( 'timestamps' );\n    \n    protected function timestamps($book)\n    {\n        $book['created_at'] = $book['updated_at'] = date('Y-m-d H:i:s');\n        return $book;\n    }\n}\n```\n\n**Remember to always always always return the `$row` object you're passed. Each observer overwrites its predecessor's data, sequentially, in the order the observers are defined.**\n\nObservers can also take parameters in their name, much like CodeIgniter's Form Validation library. Parameters are then accessed in `$this-\u003ecallback_parameters`:\n\n    public $before_create = array( 'data_process(name)' );\n    public $before_update = array( 'data_process(date)' );\n\n    protected function data_process($row)\n    {\n        $row[$this-\u003ecallback_parameters[0]] = $this-\u003e_process($row[$this-\u003ecallback_parameters[0]]);\n\n        return $row;\n    }\n\nValidation\n----------\n\nMY_Model uses CodeIgniter's built in form validation to validate data on insert.\n\nYou can enable validation by setting the `$validate` instance to the usual form validation library rules array:\n\n    class User_model extends MY_Model\n    {\n        public $validate = array(\n            array( 'field' =\u003e 'email', \n                   'label' =\u003e 'email',\n                   'rules' =\u003e 'required|valid_email|is_unique[users.email]' ),\n            array( 'field' =\u003e 'password',\n                   'label' =\u003e 'password',\n                   'rules' =\u003e 'required' ),\n            array( 'field' =\u003e 'password_confirmation',\n                   'label' =\u003e 'confirm password',\n                   'rules' =\u003e 'required|matches[password]' ),\n        );\n    }\n\nAnything valid in the form validation library can be used here. To find out more about the rules array, please [view the library's documentation](http://codeigniter.com/user_guide/libraries/form_validation.html#validationrulesasarray).\n\nWith this array set, each call to `insert()` or `update()` will validate the data before allowing  the query to be run. **Unlike the CodeIgniter validation library, this won't validate the POST data, rather, it validates the data passed directly through.**\n\nYou can skip the validation with `skip_validation()`:\n\n    $this-\u003euser_model-\u003eskip_validation();\n    $this-\u003euser_model-\u003einsert(array( 'email' =\u003e 'blah' ));\n\nAlternatively, pass through a `TRUE` to `insert()`:\n\n    $this-\u003euser_model-\u003einsert(array( 'email' =\u003e 'blah' ), TRUE);\n\nUnder the hood, this calls `validate()`.\n\nProtected Attributes\n--------------------\n\nIf you're lazy like me, you'll be grabbing the data from the form and throwing it straight into the model. While some of the pitfalls of this can be avoided with validation, it's a very dangerous way of entering data; any attribute on the model (any column in the table) could be modified, including the ID.\n\nTo prevent this from happening, MY_Model supports protected attributes. These are columns of data that cannot be modified.\n\nYou can set protected attributes with the `$protected_attributes` array:\n\n    class Post_model extends MY_Model\n    {\n        public $protected_attributes = array( 'id', 'hash' );\n    }\n\nNow, when `insert` or `update` is called, the attributes will automatically be removed from the array, and, thus, protected:\n\n    $this-\u003epost_model-\u003einsert(array(\n        'id' =\u003e 2,\n        'hash' =\u003e 'aqe3fwrga23fw243fWE',\n        'title' =\u003e 'A new post'\n    ));\n\n    // SQL: INSERT INTO posts (title) VALUES ('A new post')\n\nRelationships\n-------------\n\n**MY\\_Model** now has support for basic _belongs\\_to_ and has\\_many relationships. These relationships are easy to define:\n\n    class Post_model extends MY_Model\n    {\n        public $belongs_to = array( 'author' );\n        public $has_many = array( 'comments' );\n    }\n\nIt will assume that a MY_Model API-compatible model with the singular relationship's name has been defined. By default, this will be `relationship_model`. The above example, for instance, would require two other models:\n\n    class Author_model extends MY_Model { }\n    class Comment_model extends MY_Model { }\n\nIf you'd like to customise this, you can pass through the model name as a parameter:\n\n    class Post_model extends MY_Model\n    {\n        public $belongs_to = array( 'author' =\u003e array( 'model' =\u003e 'author_m' ) );\n        public $has_many = array( 'comments' =\u003e array( 'model' =\u003e 'model_comments' ) );\n    }\n\nYou can then access your related data using the `with()` method:\n\n    $post = $this-\u003epost_model-\u003ewith('author')\n                             -\u003ewith('comments')\n                             -\u003eget(1);\n\nThe related data will be embedded in the returned value from `get`:\n\n    echo $post-\u003eauthor-\u003ename;\n\n    foreach ($post-\u003ecomments as $comment)\n    {\n        echo $message;\n    }\n\nSeparate queries will be run to select the data, so where performance is important, a separate JOIN and SELECT call is recommended.\n\nThe primary key can also be configured. For _belongs\\_to_ calls, the related key is on the current object, not the foreign one. Pseudocode:\n\n    SELECT * FROM authors WHERE id = $post-\u003eauthor_id\n\n...and for a _has\\_many_ call:\n\n    SELECT * FROM comments WHERE post_id = $post-\u003eid\n\nTo change this, use the `primary_key` value when configuring:\n\n    class Post_model extends MY_Model\n    {\n        public $belongs_to = array( 'author' =\u003e array( 'primary_key' =\u003e 'post_author_id' ) );\n        public $has_many = array( 'comments' =\u003e array( 'primary_key' =\u003e 'parent_post_id' ) );\n    }\n\nArrays vs Objects\n-----------------\n\nBy default, MY_Model is setup to return objects using CodeIgniter's QB's `row()` and `result()` methods. If you'd like to use their array counterparts, there are a couple of ways of customising the model.\n\nIf you'd like all your calls to use the array methods, you can set the `$return_type` variable to `array`.\n\n    class Book_model extends MY_Model\n    {\n        protected $return_type = 'array';\n    }\n\nIf you'd like just your _next_ call to return a specific type, there are two scoping methods you can use:\n\n    $this-\u003ebook_model-\u003eas_array()\n                     -\u003eget(1);\n    $this-\u003ebook_model-\u003eas_object()\n                     -\u003eget_by('column', 'value');\n\nSoft Delete\n-----------\n\nBy default, the delete mechanism works with an SQL `DELETE` statement. However, you might not want to destroy the data, you might instead want to perform a 'soft delete'.\n\nIf you enable soft deleting, the deleted row will be marked as `deleted` rather than actually being removed from the database.\n\nTake, for example, a `Book_model`:\n\n    class Book_model extends MY_Model { }\n\nWe can enable soft delete by setting the `$this-\u003esoft_delete` key:\n\n    class Book_model extends MY_Model\n    { \n        protected $soft_delete = TRUE;\n    }\n\nBy default, MY_Model expects a `TINYINT` or `INT` column named `deleted`. If you'd like to customise this, you can set `$soft_delete_key`:\n\n    class Book_model extends MY_Model\n    { \n        protected $soft_delete = TRUE;\n        protected $soft_delete_key = 'book_deleted_status';\n    }\n\nNow, when you make a call to any of the `get_` methods, a constraint will be added to not withdraw deleted columns:\n\n    =\u003e $this-\u003ebook_model-\u003eget_by('user_id', 1);\n    -\u003e SELECT * FROM books WHERE user_id = 1 AND deleted = 0\n\nIf you'd like to include deleted columns, you can use the `with_deleted()` scope:\n\n    =\u003e $this-\u003ebook_model-\u003ewith_deleted()-\u003eget_by('user_id', 1);\n    -\u003e SELECT * FROM books WHERE user_id = 1\n    \nIf you'd like to include only the columns that have been deleted, you can use the `only_deleted()` scope:\n\n    =\u003e $this-\u003ebook_model-\u003eonly_deleted()-\u003eget_by('user_id', 1);\n    -\u003e SELECT * FROM books WHERE user_id = 1 AND deleted = 1\n\nBuilt-in Observers\n-------------------\n\n**MY_Model** contains a few built-in observers for things I've found I've added to most of my models.\n\nThe timestamps (MySQL compatible) `created_at` and `updated_at` are now available as built-in observers:\n\n    class Post_model extends MY_Model\n    {\n        public $before_create = array( 'created_at', 'updated_at' );\n        public $before_update = array( 'updated_at' );\n    }\n\n**MY_Model** also contains serialisation observers for serialising and unserialising native PHP objects. This allows you to pass complex structures like arrays and objects into rows and have it be serialised automatically in the background. Call the `serialize` and `unserialize` observers with the column name(s) as a parameter:\n\n    class Event_model extends MY_Model\n    {\n        public $before_create = array( 'serialize(seat_types)' );\n        public $before_update = array( 'serialize(seat_types)' );\n        public $after_get = array( 'unserialize(seat_types)' );\n    }\n\nDatabase Connection\n-------------------\n\nThe class will automatically use the default database connection, and even load it for you if you haven't yet.\n\nYou can specify a database connection on a per-model basis by declaring the _$\\_db\\_group_ instance variable. This is equivalent to calling `$this-\u003edb-\u003edatabase($this-\u003e_db_group, TRUE)`.\n\nSee [\"Connecting to your Database\"](http://ellislab.com/codeigniter/user-guide/database/connecting.html) for more information.\n\n```php\nclass Post_model extends MY_Model\n{\n    public $_db_group = 'group_name';\n}\n```\n\nUnit Tests\n----------\n\nMY_Model contains a robust set of unit tests to ensure that the system works as planned.\n\nInstall the testing framework (PHPUnit) with Composer:\n\n    $ curl -s https://getcomposer.org/installer | php\n    $ php composer.phar install\n\nYou can then run the tests using the `vendor/bin/phpunit` binary and specify the tests file:\n\n    $ vendor/bin/phpunit\n\n\nContributing to MY_Model\n------------------------\n\nIf you find a bug or want to add a feature to MY_Model, great! In order to make it easier and quicker for me to verify and merge changes in, it would be amazing if you could follow these few basic steps:\n\n1. Fork the project.\n2. **Branch out into a new branch. `git checkout -b name_of_new_feature_or_bug`**\n3. Make your feature addition or bug fix.\n4. **Add tests for it. This is important so I don’t break it in a future version unintentionally.**\n5. Commit.\n6. Send me a pull request!\n\n\nOther Documentation\n-------------------\n\n* My book, The CodeIgniter Handbook, talks about the techniques used in MY_Model and lots of other interesting useful stuff. [Get a copy now.](https://efendibooks.com/books/codeigniter-handbook/vol-1)\n* Jeff Madsen has written an excellent tutorial about the basics (and triggered me updating the documentation here). [Read it now, you lovely people.](http://www.codebyjeff.com/blog/2012/01/using-jamie-rumbelows-my_model)\n* Rob Allport wrote a post about MY_Model and his experiences with it. [Check it out!](http://www.web-design-talk.co.uk/493/codeigniter-base-models-rock/)\n* I've written a write up of the new 2.0.0 features [over at my blog, Jamie On Software.](http://jamieonsoftware.com/journal/2012/9/11/my_model-200-at-a-glance.html)\n\nChangelog\n---------\n\n**Version 2.0.0**\n* Added support for soft deletes\n* Removed Composer support. Great system, CI makes it difficult to use for MY_ classes\n* Fixed up all problems with callbacks and consolidated into single `trigger` method\n* Added support for relationships\n* Added built-in timestamp observers\n* The DB connection can now be manually set with `$this-\u003e_db`, rather than relying on the `$active_group`\n* Callbacks can also now take parameters when setting in callback array\n* Added support for column serialisation\n* Added support for protected attributes\n* Added a `truncate()` method\n\n**Version 1.3.0**\n* Added support for array return types using `$return_type` variable and `as_array()` and `as_object()` methods\n* Added PHP5.3 support for the test suite\n* Removed the deprecated `MY_Model()` constructor\n* Fixed an issue with after_create callbacks (thanks [zbrox](https://github.com/zbrox)!)\n* Composer package will now autoload the file\n* Fixed the callback example by returning the given/modified data (thanks [druu](https://github.com/druu)!)\n* Change order of operations in `_fetch_table()` (thanks [JustinBusschau](https://github.com/JustinBusschau)!)\n\n**Version 1.2.0**\n* Bugfix to `update_many()`\n* Added getters for table name and skip validation\n* Fix to callback functionality (thanks [titosemi](https://github.com/titosemi)!)\n* Vastly improved documentation\n* Added a `get_next_id()` method (thanks [gbaldera](https://github.com/gbaldera)!)\n* Added a set of unit tests\n* Added support for [Composer](http://getcomposer.org/)\n\n**Version 1.0.0 - 1.1.0**\n* Initial Releases\n","funding_links":[],"categories":["CRUD","Model","PHP"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjamierumbelow%2Fcodeigniter-base-model","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjamierumbelow%2Fcodeigniter-base-model","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjamierumbelow%2Fcodeigniter-base-model/lists"}