Using Jamie Rumbelow's My_Model

Building forms in your app? Be sure to consider these common security mistakes: 
Web form security - avoiding common mistakes
Like PDO? Check out how to use it with Codeigniter
Codeigniter with PDO Thanks!

One thing I've noticed while answering questions one the CodeIgniter forums is how few "noobies" seem to use a MY_Model library. The concept of a MY_Controller is mentioned all the time, and more and more people are using templates libraries for their views, but MY_Model often seems to slip by.

Joost van Veen (codeigniter.tv) just released a great 4-part tutorial on building your own MY_Model (check it out here: Extending the Codeigniter core: MY_Model ), but I thought a lot of people might be scared off by how much work it takes to write their own. So, why not encourage them to learn from Joost, but in the meantime, grab a top-notch code library and start using it? After all, isn't that the point of a library?

Jamie Rumbelow's MY_Model (http://github.com/jamierumbelow/codeigniter-base-model) is probably the best-known out there. It has been contributed to by Phil Sturgeon, Dan Horrigan and Adam Jackett, and is the basis of the model used in PyroCMS, so you can count on it being well-designed. However, it is not well documented and a bit intimidating to the uninitiated.

Therefore, instead of my writing a new tutorial or library which wouldn't be as good as what these guys have already contributed, I thought I would just introduce you to Jamie's and give you lots of examples on how to get going.

So...let's get going

Setup:

1) download the library from the link above and put it in your /core directory

2) create a table with this:

CREATE TABLE IF NOT EXISTS `articles` (
 `body` text,
 `title` varchar(250) DEFAULT NULL,
 `id` int(11) NOT NULL AUTO_INCREMENT,
 PRIMARY KEY (`id`),
 FULLTEXT KEY `body` (`body`,`title`)
) ENGINE=MyISAM  


--
-- Dumping data for table `articles`
--

 INSERT INTO `articles` (`body`, `title`, `id`) VALUES
 ('bears are fuzzy and cute - but don''t try to pet them!', 'Something about bears', 1),
 ('Fuzzy Wuzzy was a bear; Fuzzy Wuzzy had no hair. Fuzzy Wuzzy wasn''t very fuzzy, was he?', 'Fuzzy Wuzzy', 2),
 ('This is dumb and boring', 'Dumb and boring post', 3),
 ('This is dumb and boring, too.', 'Dumb and boring post', 4);

 

3) create a model called article_model.php (no "s")

class Article_model extends MY_Model
{

}

4) last, make a test controller to run all your queries from. Here is a fairly complete list of all of the functions available to you, each one given by an example with the output you should expect (if you run them one at a time in order), as well as the actual sql generated. My thought is this will be all you need to get going. All of this code should go in your controller. Don't forget to start with:

$this->load->model('article_model');

 

$row = $this->article_model->get(2);		
//stdClass Object ( [body] => Fuzzy Wuzzy was a bear; Fuzzy Wuzzy had no hair. Fuzzy Wuzzy wasn't very fuzzy, was he? [title] => Fuzzy Wuzzy [id] => 2 ) 
//SELECT * FROM (`articles`) WHERE `id` = 2

$row = $this->article_model->get_by('title', 'Fuzzy Wuzzy');
//stdClass Object ( [body] => Fuzzy Wuzzy was a bear; Fuzzy Wuzzy had no hair. Fuzzy Wuzzy wasn't very fuzzy, was he? [title] => Fuzzy Wuzzy [id] => 2 ) 
//SELECT * FROM (`articles`) WHERE `title` = 'Fuzzy Wuzzy'
// NOTE: if more than 1, returns first

$result = $this->article_model->get_many(array(1,3,4));
//Array ( [0] => stdClass Object ( [body] => bears are fuzzy and cute - but don't try to pet them! [title] => Something about bears [id] => 1 ) [1] => stdClass Object ( [body] => This is dumb and boring [title] => Dumb and boring post [id] => 3 ) [2] => stdClass Object ( [body] => This is dumb and boring, too. [title] => Dumb and boring post [id] => 4 ) ) 
//SELECT * FROM (`articles`) WHERE `id` IN (1, 3, 4)  

$result = $this->article_model->get_many_by('title', 'Dumb and boring post');
//Array ( [0] => stdClass Object ( [body] => This is dumb and boring [title] => Dumb and boring post [id] => 3 ) [1] => stdClass Object ( [body] => This is dumb and boring, too. [title] => Dumb and boring post [id] => 4 ) ) 
//SELECT * FROM (`articles`) WHERE `title` = 'Dumb and boring post'

$result = $this->article_model->get_all();
//Array ( [0] => stdClass Object ( [body] => bears are fuzzy and cute - but don't try to pet them! [title] => Something about bears [id] => 1 ) [1] => stdClass Object ( [body] => Fuzzy Wuzzy was a bear; Fuzzy Wuzzy had no hair. Fuzzy Wuzzy wasn't very fuzzy, was he? [title] => Fuzzy Wuzzy [id] => 2 ) [2] => stdClass Object ( [body] => This is dumb and boring [title] => Dumb and boring post [id] => 3 ) [3] => stdClass Object ( [body] => This is dumb and boring, too. [title] => Dumb and boring post [id] => 4 ) [4] => stdClass Object ( [body] => Ain't no sunshine [title] => When she's gone [id] => 13 ) [5] => stdClass Object ( [body] => Woot! [title] => My thoughts [id] => 11 ) [6] => stdClass Object ( [body] => Hello [title] => I must be going [id] => 12 ) ) 
//SELECT * FROM (`articles`)

$count = $this->article_model->count_by('title', 'Dumb and boring post');
//2
//SELECT COUNT(*) AS `numrows` FROM (`articles`) WHERE `title` = 'Dumb and boring post'

$count = $this->article_model->count_all();
//4
//SELECT COUNT(*) AS `numrows` FROM `articles`

$insert_id = $this->article_model->insert(array('body'=>'Woot!', 'title'=>'My thoughts'), FALSE);
//5
//INSERT INTO `articles` (`body`, `title`) VALUES ('Woot!', 'My thoughts')


$insert_array = array(
		array('body'=>'Hello', 'title'=>'I must be going'),
		array('body'=>"When she's gone", 'title'=>"Ain't no sunshine" ),
	);
$insert_ids = $this->article_model->insert_many($insert_array, FALSE);	
//Array ( [0] => 16 [1] => 17 ) //1
//INSERT INTO `articles` (`body`, `title`) VALUES ('When she\'s gone', 'Ain\'t no sunshine')


$update_id = $this->article_model->update(4, array('body'=>'This is dumber and more boring', 'title'=>'Dumber and boringer'));
//1
//UPDATE `articles` SET `body` = 'This is dumber and more boring', `title` = 'Dumber and boringer' WHERE `id` = 4

$update_id = $this->article_model->update_by(array('title'=>'My thoughts'), array('body'=>'Having deeper thoughts'));
//1
//UPDATE `articles` SET `body` = 'Having deeper thoughts' WHERE `title` = 'My thoughts'	

$update_id = $this->article_model->update_many(array(3,4,5), array('body'=>"Oh! I've been updated...and I feel MARVELOUS!"));
//1
//UPDATE `articles` SET `body` = 'Oh! I\'ve been updated...and I feel MARVELOUS!' WHERE `id` IN (3, 4, 5) 	

$update_id = $this->article_model->update_all( array('title'=>"Another dumb title"));
//1
//UPDATE `articles` SET `title` = 'Another dumb title' 	

$delete_id = $this->article_model->delete( 7);
//1
//DELETE FROM `articles` WHERE `id` = 7 

$delete_id = $this->article_model->delete_by( array('body'=>'Hello'));
//1
//DELETE FROM `articles` WHERE `body` = 'Hello' 

$delete_id = $this->article_model->delete_many( array(3,4,5));
//1
//DELETE FROM `articles` WHERE `id` IN (3, 4, 5) 

//// Utilities ////

// dropdown - automatically picks the primary key if only one value passed
$dropdown_array = $this->article_model->dropdown( 'title');
//Array ( [1] => Another dumb title [2] => Another dumb title ) 
//SELECT `id`, `title` FROM (`articles`)


// otherwise, give it a key, value pair to build on (my data is bad for example at this point)
$dropdown_array = $this->article_model->dropdown( 'title', 'body');
//Array ( [Another dumb title] => Fuzzy Wuzzy was a bear; Fuzzy Wuzzy had no hair. Fuzzy Wuzzy wasn't very fuzzy, was he? ) 
//SELECT `title`, `body` FROM (`articles`)

 

Finally, a couple of common tasks you might be after (this code goes in article_model.php ):

#1 - I only want certain fields

Create a new function to make your select function call, but then stick to the parent get()

function select($fields)
{ 
        $this->db->select($fields); 
        return $row = $this->get(2); 
}

//SELECT `title` FROM (`articles`) WHERE `id` = 2

#2 - I want to validate my insert

Create all the validation rules you might need for anything on this table at the top of your class. NOTICE it is an array of arrays (check the user guide http://codeigniter.com/user_guide/libraries/form_validation.html#rulereference for rules)

protected $validate = array(array('title'=>'required'));

That should get you started down the road to happy MY_Model usage :-)  Come to the Codeigniter forums and ask if you run into trouble.



Contact me