<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Inside DealTakermodels » Inside DealTaker</title>
	<atom:link href="http://www.dealtaker.com/our-blog/tag/models/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dealtaker.com/our-blog</link>
	<description>Just another DealTaker.com site</description>
	<lastBuildDate>Fri, 10 Feb 2012 14:56:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Kohana PHP 3.0 (KO3) Tutorial Part 4</title>
		<link>http://www.dealtaker.com/our-blog/2010/02/01/kohana-php-3-0-ko3-tutorial-part-4/</link>
		<comments>http://www.dealtaker.com/our-blog/2010/02/01/kohana-php-3-0-ko3-tutorial-part-4/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 13:20:40 +0000</pubDate>
		<dc:creator>ellisgl</dc:creator>
				<category><![CDATA[DealTaker.com Updates]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[KO3]]></category>
		<category><![CDATA[kohana]]></category>
		<category><![CDATA[models]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.dealtaker.com/blog/?p=1921</guid>
		<description><![CDATA[Welcome to the fourth part in this series on how to develop with Kohana PHP V3 (KO3). If you haven&#8217;t read any of previous parts yet, I would search for and read them before going on. In this tutorial we will be going over how work with models. So you might be asking your self, [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to the fourth part in this series on how to develop with Kohana PHP V3 (KO3). If you haven&#8217;t read any of previous parts yet, I would search for and read them before going on. In this tutorial we will be going over how work with models.<br />
<span id="more-1921"></span><br />
So you might be asking your self, what is a model. From <a href="http://docs.kohanaphp.com/">Kohana&#8217;s 2.x documents</a>:</p>
<blockquote cite="http://docs.kohanaphp.com/general/models"><p>Models are classes designed to work with information given by or asked for by the controller. For example, you have a guestbook, the controller will ask the model to retrieve the last ten entries, the model returns those entries to the controller who passes them on to a view. The controller might also send new entries to the model, update existing ones or even delete some.</p></blockquote>
<p>Simply a model is a data handler and manipulator.</p>
<p>The first thing we want to do is identify where and what the data is. Is it an XML feed, CSV, JSON, DB or something else? Well I&#8217;m going to make it easy. We are going to deal with our friend MySQL for this. The next step is to setup a MySQL DB connection.</p>
<p>Lets open up your bootstrap file (&#8220;application/bootstrap.php&#8221;) and find the like that reads &#8220;// &#8216;database&#8217;   =&gt; MODPATH.&#8217;database&#8217;,   // Database access&#8221; and uncomment it. The whole block of code should look like the following:<br />
[php]Kohana::modules(array(<br />
// &#8216;auth&#8217;       =&gt; MODPATH.&#8217;auth&#8217;,       // Basic authentication<br />
// &#8216;codebench&#8217;  =&gt; MODPATH.&#8217;codebench&#8217;,  // Benchmarking tool<br />
&#8216;database&#8217;   =&gt; MODPATH.&#8217;database&#8217;,   // Database access<br />
// &#8216;image&#8217;      =&gt; MODPATH.&#8217;image&#8217;,      // Image manipulation<br />
// &#8216;orm&#8217;        =&gt; MODPATH.&#8217;orm&#8217;,        // Object Relationship Mapping<br />
// &#8216;pagination&#8217; =&gt; MODPATH.&#8217;pagination&#8217;, // Paging of results<br />
// &#8216;userguide&#8217;  =&gt; MODPATH.&#8217;userguide&#8217;,  // User guide and API documentation<br />
));[/php]<br />
Now save this. We&#8217;ve basically told the bootstrap to load the database module, but we need to configure it. Copy the &#8220;database.php&#8221; from &#8220;modules/database/config/&#8221; to &#8220;application/config/&#8221;. Open up the &#8220;application/config/database.php&#8221; file and edit accordingly to your settings. Mine looks like this:<br />
[php]&lt;?php defined(&#8216;SYSPATH&#8217;) OR die(&#8216;No direct access allowed.&#8217;);</p>
<p>return array<br />
(<br />
&#8216;default&#8217; =&gt; array<br />
(<br />
&#8216;type&#8217;       =&gt; &#8216;mysql&#8217;,<br />
&#8216;connection&#8217; =&gt; array(<br />
/**<br />
* The following options are available for MySQL:<br />
*<br />
* string   hostname<br />
* integer  port<br />
* string   socket<br />
* string   username<br />
* string   password<br />
* boolean  persistent<br />
* string   database<br />
*/<br />
&#8216;hostname&#8217;   =&gt; &#8216;localhost&#8217;,<br />
&#8216;username&#8217;   =&gt; &#8216;root&#8217;,<br />
&#8216;password&#8217;   =&gt; FALSE,<br />
&#8216;persistent&#8217; =&gt; FALSE,<br />
&#8216;database&#8217;   =&gt; &#8216;mykohana3&#8242;,<br />
),<br />
&#8216;table_prefix&#8217; =&gt; &#8221;,<br />
&#8216;charset&#8217;      =&gt; &#8216;utf8&#8242;,<br />
&#8216;caching&#8217;      =&gt; FALSE,<br />
&#8216;profiling&#8217;    =&gt; TRUE,<br />
),<br />
&#8216;alternate&#8217; =&gt; array(<br />
&#8216;type&#8217;       =&gt; &#8216;pdo&#8217;,<br />
&#8216;connection&#8217; =&gt; array(<br />
/**<br />
* The following options are available for PDO:<br />
*<br />
* string   dsn<br />
* string   username<br />
* string   password<br />
* boolean  persistent<br />
* string   identifier<br />
*/<br />
&#8216;dsn&#8217;        =&gt; &#8216;mysql:host=localhost;dbname=mykohana3&#8242;,<br />
&#8216;username&#8217;   =&gt; &#8216;root&#8217;,<br />
&#8216;password&#8217;   =&gt; FALSE,<br />
&#8216;persistent&#8217; =&gt; FALSE,<br />
),<br />
&#8216;table_prefix&#8217; =&gt; &#8221;,<br />
&#8216;charset&#8217;      =&gt; &#8216;utf8&#8242;,<br />
&#8216;caching&#8217;      =&gt; FALSE,<br />
&#8216;profiling&#8217;    =&gt; TRUE,<br />
),<br />
);[/php]<br />
Save this. You&#8217;ll notice I have a database setup just this tutorial series named &#8220;mykohana3&#8243;, you might want to do the same if you can. Now that we have saved, let get a table set up. Here&#8217;s the SQL:<br />
[php]CREATE TABLE `posts` (<br />
`id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT,<br />
`title` VARCHAR(255) DEFAULT NULL,<br />
`post` TEXT,<br />
PRIMARY KEY  (`id`)<br />
) ENGINE=INNODB DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;[/php]<br />
Go run that in your favorite MySQL client, I personally like <a href="http://code.google.com/p/sqlyog/">SQLYog</a>. You might have noticed the &#8220;charset&#8221; is set to &#8220;utf8&#8243; in both the config and create table statement. This will allow us to deal with i18n (Internationalization) stuff later on.</p>
<p>So let create a new folder under &#8220;application/classes&#8221; named &#8220;model&#8221;. Now lets create a new file and make it look like this:<br />
[php]&lt;?php<br />
defined(&#8216;SYSPATH&#8217;) or die(&#8216;No direct script access.&#8217;);</p>
<p>class Model_Post extends Kohana_Model<br />
{<br />
/**<br />
* Get the last 10 posts<br />
* @return ARRAY<br />
*/<br />
public function getLastTenPosts()<br />
{<br />
$sql = &#8216;SELECT *&#8217;.&#8221;n&#8221;.<br />
&#8216;FROM   `posts`&#8217;.&#8221;n&#8221;.<br />
&#8216;ORDER BY `id` DESC&#8217;.&#8221;n&#8221;.<br />
&#8216;LIMIT  0, 10&#8242;;</p>
<p>return $this-&gt;_db-&gt;query(Database::SELECT, $sql, FALSE)<br />
-&gt;as_array();<br />
}<br />
}[/php]<br />
Save this as &#8220;post.php&#8221; under &#8220;application/classes/model/&#8221;. Here&#8217;s an line by line explaination of the code.<br />
[php]        $sql = &#8216;SELECT *&#8217;.&#8221;n&#8221;.<br />
&#8216;FROM   `posts`&#8217;.&#8221;n&#8221;.<br />
&#8216;ORDER BY `id` DESC&#8217;.&#8221;n&#8221;.<br />
&#8216;LIMIT  0, 10&#8242;;[/php]<br />
This is a basic MySQL statement that selects up to ten rows from the DB which are sorted by the &#8216;id&#8217; in a descending direction.<br />
[php]        return $this-&gt;_db-&gt;query(Database::SELECT, $sql, FALSE)<br />
-&gt;as_array();[/php]<br />
This return array of the result from a query. The &#8220;query&#8221; method in this example take 3 parameters. 1st being what type of query, our being select, we use the constant &#8220;Database::SELECT&#8221;. There are 3 others,  &#8220;Database::INSERT&#8221;,  &#8220;Database::UPDATE&#8221; and &#8220;Database::DELETE&#8221;. The &#8220;as_array()&#8221; will return an array of the results, no having to do &#8220;while($row = mysql_fetch_array())&#8221;.</p>
<p>Now that we have a model method, I&#8217;m sure we would want to put it use. Open up &#8220;ko3.php&#8221; in &#8220;/application/classes/controller&#8221; and lets add this into the class:<br />
[php]    public function action_posts()<br />
{<br />
$posts                            = new Model_Post();<br />
$ko3                              = array();<br />
$this-&gt;template-&gt;title            = &#8216;Kohana 3.0 Model Test&#8217;;<br />
$this-&gt;template-&gt;meta_keywords    = &#8216;PHP, Kohana, KO3, Framework, Model&#8217;;<br />
$this-&gt;template-&gt;meta_description = &#8216;A test of of the KO3 framework Model&#8217;;<br />
$this-&gt;template-&gt;styles           = array();<br />
$this-&gt;template-&gt;scripts          = array();</p>
<p>// Get the last 10 posts<br />
$ko3['posts']                     = $posts-&gt;getLastTenPosts();<br />
$this-&gt;template-&gt;content          = View::factory(&#8216;pages/posts&#8217;, $ko3);</p>
<p>}[/php]<br />
Basically we&#8217;ve called our model&#8217;s &#8220;getLastTenPosts()&#8221; method and assigned it to an array which we pass to our view. Talking about views, open up a new file and put the following into it:<br />
[php]&lt;?php foreach($posts as $post):?&gt;<br />
&lt;h1&gt;&lt;?php echo $post['title'];?&gt;&lt;/h1&gt;<br />
&lt;?php echo $post['post'];?&gt;<br />
&lt;hr /&gt;<br />
&lt;?php endforeach;?&gt;[/php]<br />
Save to as &#8220;posts.php&#8221; under &#8220;application/views/pages/&#8221;. This view loops through the array we pass to it from the the controller and displays our posts from the DB. Wait, what? There&#8217;s no posts in our DB! Here&#8217;s some SQL you can run to populate your table:<br />
[php]insert  into `posts`(`id`,`title`,`post`) values (1,&#8217;Test Post&#8217;,'This is some sample text.&#8217;);<br />
insert  into `posts`(`id`,`title`,`post`) values (2,&#8217;Another post&#8217;,'Some more text&#8217;);[/php]<br />
Now if you point your browser to &#8220;http://yourserver/mykohana3/ko3/posts&#8221; you should see the two entries on the screen.</p>
<p>Now lets add something to put data into our DB. Open the the post model (&#8220;application/classes/model/post.php&#8221;) and add this to the class:<br />
[php]    public function addPost($title, $post)<br />
{<br />
$sql = sprintf(&#8216;INSERT INTO `posts`&#8217;.&#8221;n&#8221;.<br />
&#8216;SET         `title` = %s,&#8217;.&#8221;n&#8221;.<br />
&#8216;            `post`  = %s&#8217;,<br />
$this-&gt;_db-&gt;escape($title),<br />
$this-&gt;_db-&gt;escape($post));</p>
<p>$this-&gt;_db-&gt;query(Database::INSERT, $sql, FALSE);<br />
}[/php]<br />
The above is a pretty simple insert, but you may notice we are using &#8220;$this-&gt;_db&gt;escape()&#8221;. This will wrap your strings in quotes and escape it content for you. Save it and now go back to the &#8220;posts.php&#8221; from &#8220;application/views/pages&#8221; and replace the contents with:<br />
[php]&lt;?php if(!empty($msg)):?&gt;<br />
&lt;?php echo $msg.&#8217;&lt;br /&gt;&#8217;;?&gt;<br />
&lt;?php endif;?&gt;<br />
&lt;?php foreach($posts as $post):?&gt;<br />
&lt;h1&gt;&lt;?php echo $post['title'];?&gt;&lt;/h1&gt;<br />
&lt;?php echo $post['post'];?&gt;<br />
&lt;hr /&gt;<br />
&lt;?php endforeach;?&gt;<br />
&lt;form method=&#8221;POST&#8221; action=&#8221;&lt;?php echo url::base();?&gt;ko3/posts/&#8221;&gt;<br />
&lt;table&gt;<br />
&lt;tr&gt;<br />
&lt;td&gt;<br />
Title<br />
&lt;/td&gt;<br />
&lt;td&gt;<br />
&lt;input type=&#8221;text&#8221; name=&#8221;title&#8221; style=&#8221;border: 1px solid #000000;&#8221;/&gt;<br />
&lt;/td&gt;<br />
&lt;/tr&gt;<br />
&lt;tr&gt;<br />
&lt;td&gt;<br />
Post<br />
&lt;/td&gt;<br />
&lt;td&gt;<br />
&lt;textarea cols=&#8221;20&#8243; rows=&#8221;5&#8243; name=&#8221;post&#8221;&gt;&lt;/textarea&gt;<br />
&lt;input type=&#8221;submit&#8221; name=&#8221;submit&#8221; value=&#8221;Submit&#8221;/&gt;<br />
&lt;/td&gt;<br />
&lt;/table&gt;<br />
&lt;/form&gt;[/php]<br />
Save that and open the ko3 controller back up (&#8220;application/classes/controller/ko3.php&#8221;) and lets add a new method to it.<br />
[php]    private function _addPost($title, $post_content)<br />
{<br />
// Load model<br />
$post = new Model_Post();</p>
<p>// Check required fields<br />
if(empty($title))<br />
{<br />
return(array(&#8216;error&#8217; =&gt; &#8216;Please enter a title.&#8217;));<br />
}<br />
elseif(empty($post_content))<br />
{<br />
return(array(&#8216;error&#8217; =&gt; &#8216;Please enter a post.&#8217;));<br />
}</p>
<p>// Add to DB<br />
$post-&gt;addPost($title, $post_content);<br />
return TRUE;<br />
}[/php]<br />
The above code is pretty much a middle man between the &#8220;action_posts&#8221; and the model that saves the post it self. Lets go back to the &#8220;action_posts&#8221; method and make it look like this:<br />
[php]   public function action_posts()<br />
{<br />
// Load model<br />
$posts                            = new Model_Post();</p>
<p>// Setup view stuff<br />
$ko3                              = array();<br />
$this-&gt;template-&gt;title            = &#8216;Kohana 3.0 Model Test&#8217;;<br />
$this-&gt;template-&gt;meta_keywords    = &#8216;PHP, Kohana, KO3, Framework, Model&#8217;;<br />
$this-&gt;template-&gt;meta_description = &#8216;A test of of the KO3 framework Model&#8217;;<br />
$this-&gt;template-&gt;styles           = array();<br />
$this-&gt;template-&gt;scripts          = array();<br />
$ko3['msg']                       = &#8220;&#8221;;</p>
<p>// Handle POST<br />
if($_POST)<br />
{<br />
$ret = $this-&gt;_addPost((isset($_POST['title']) ? $_POST['title'] : &#8220;&#8221;),<br />
(isset($_POST['post']) ? $_POST['post']  : &#8220;&#8221;));</p>
<p>if(isset($ret['error']))<br />
{<br />
$ko3['msg'] = $ret['error'];<br />
}<br />
else<br />
{<br />
$ko3['msg'] = &#8216;Saved.&#8217;;<br />
}<br />
}</p>
<p>// Get the last 10 posts<br />
$ko3['posts']                     = $posts-&gt;getLastTenPosts();</p>
<p>// Display it.<br />
$this-&gt;template-&gt;content          = View::factory(&#8216;pages/posts&#8217;, $ko3);<br />
}[/php]<br />
Save this and reload your browser. Now you should see a pretty ugly form at bottom. Enter some stuff in and click the &#8220;submit&#8221; button. Your post should appear at the top along with the word &#8220;Saved&#8221;, this is if you entered stuff in both fields, if not you should see an error.</p>
<p>Before I end this tutorial, I want to go back to our little model for saving our posts. There are several ways to do queries in KO3, but want to quickly show you how you can use the query builder to do the same thing.<br />
[php]    public function addPost($title, $post)<br />
{<br />
DB::insert(&#8216;posts&#8217;, array(&#8216;title&#8217;,'post&#8217;))<br />
-&gt;values(array($title, $post))<br />
-&gt;execute();<br />
}[/php]<br />
That&#8217;s pretty simple! It does the same thing as the previous one, with less &#8220;hassle&#8221; There are advantages using the query builder method, like being able to convert between different DB types (MySQL to Oracle to what ever).</p>
<p>While I might not have gone over doing updates with your model, I thought I would give you a homework assignment to see if you can come up with you own update model for this. Until next time when we go over &#8220;H&#8221; in &#8220;HMVC&#8221;, happy coding.</p>
<p>Sources used: <a href="http://kerkness.ca/wiki/doku.php" target="_blank">Unofficial Kohana 3 Wiki</a>, <a href="http://docs.kohanaphp.com/" target="_blank">Kohana PHP 2.x Docs</a>, <a href="http://v3.kohanaphp.com/guide/api" target="_blank">KO3 API Guide</a></p>
<p>&lt;&lt;<a href="http://www.dealtaker.com/our-blog/2009/12/30/kohana-php-3-0-ko3-tutorial-part-3/">Part 3</a> | <a href="http://www.dealtaker.com/our-blog/2010/02/25/kohana-php-3-0-ko3-tutorial-part-5/">Part 5</a>&gt;&gt;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dealtaker.com/our-blog/2010/02/01/kohana-php-3-0-ko3-tutorial-part-4/feed/</wfw:commentRss>
		<slash:comments>57</slash:comments>
		</item>
		<item>
		<title>Kohana PHP Tuturial &#8211; Part III</title>
		<link>http://www.dealtaker.com/our-blog/2009/06/19/kohana-php-tuturial-part-iii/</link>
		<comments>http://www.dealtaker.com/our-blog/2009/06/19/kohana-php-tuturial-part-iii/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 08:26:09 +0000</pubDate>
		<dc:creator>ellisgl</dc:creator>
				<category><![CDATA[DealTaker.com Updates]]></category>
		<category><![CDATA[db]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[kohana]]></category>
		<category><![CDATA[models]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.dealtaker.com/blog/?p=1013</guid>
		<description><![CDATA[It&#8217;s been a couple weeks now, so lets get back on track with this series of tutorials. This tutorial will get into models and how to play with data. The first thing I have to is tell you is that Kohana PHP has been updated since the last tutorial. So I have gone ahead and [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a couple weeks now, so lets get back on track with this series of tutorials. This tutorial will get into models and how to play with data.<br />
<span id="more-1013"></span></p>
<p>The first thing I have to is tell you is that Kohana PHP has been updated since the last tutorial. So I have gone ahead and took the last tutorial and updated the core and made sure it worked with Kohana 2.3.4. <a href="http://images.dealtaker.com/dealtaker/blog/kohana/dealtaker-kohana-2-2.3.4.zip">You can grab that here</a>. Now onward to the glory!</p>
<p>The first thing we want to do is identify where and what the data is. Is it an XML feed, CSV, JSON, DB or something else? Well I&#8217;m going to make it easy. We are going to deal with our friend MySQL for this. The next step is to setup a MySQL DB connection.</p>
<p>Go into your system/config folder and copy the database.php file to your application/config folder. Edit the application/config/database.php to reflect your server settings. Mine looks like this:</p>
<pre>$config['default'] = array
(
	'benchmark'     =&gt; TRUE,
	'persistent'    =&gt; FALSE,
	'connection'    =&gt; array
	(
		'type'     =&gt; 'mysql',
		'user'     =&gt; 'root',
		'pass'     =&gt; 'root',
		'host'     =&gt; 'localhost',
		'port'     =&gt; FALSE,
		'socket'   =&gt; FALSE,
		'database' =&gt; 'myfirstkohana'
	),
	'character_set' =&gt; 'utf8',
	'table_prefix'  =&gt; '',
	'object'        =&gt; TRUE,
	'cache'         =&gt; FALSE,
	'escape'        =&gt; TRUE
);</pre>
<p>Now that we have a configuration a connection for our database, we should probably set up a database and a table. Here&#8217;s the SQL:</p>
<pre>/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`myfirstkohana` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `myfirstkohana`;

/*Table structure for table `posts` */
DROP TABLE IF EXISTS `posts`;

CREATE TABLE `posts` (
  `id` mediumint(8) unsigned NOT NULL auto_increment,
  `title` varchar(255) default NULL,
  `post` text,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;

/*Data for the table `posts` */
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;</pre>
<p>This is a pretty straight forward &#8220;Create a DB and one table&#8221; setup. You might notice that we have everything set for UTF8. This will match the DB configuration setting and also will allow us to deal with i18n (Internationalization) stuff later on.</p>
<p>Onward to creating an actual model. There are a couple things to keep in mind with naming conventions, well really one. From the docs &#8220;The model class name is capitalized, does have _Model appended to it and should be the singular form of the name.&#8221;. There are so other rules when you are dealing with ORM, but we won&#8217;t be dealing with ORM in this tutorial.</p>
<p>Create a file named post.php in the &#8216;application/models/&#8217; folder and make it look like the following:</p>
<pre>&lt;?php
defined('SYSPATH') or die('No direct script access.');

class Post_Model extends Model
 {
    public function __construct()
    	{
		      parent::__construct();
    	}

 }</pre>
<p>As you can tell the above really doesn&#8217;t do much, so let&#8217;s give it some functionality:</p>
<pre>&lt;?php
defined('SYSPATH') or die('No direct script access.');

class Post_Model extends Model
 {
    public function __construct()
    	{
		      parent::__construct();
    	}

    public function getPosts()
     {
        $sql = 'SELECT *
                FROM   `posts`
                LIMIT  0, 10';

        return $this-&gt;db-&gt;query($sql);
     }
 }</pre>
<p>So we have a model method that pulls 10 posts from the table with a pretty simple query. We use &#8220;$this-&gt;query()&#8221; to run queries, which will return object and we return that to the calling entity. Check the query method <a href="http://docs.kohanaphp.com/libraries/database/query" target="_blank">docs here</a> for more information.</p>
<p>Let&#8217;s update our &#8216;Hello&#8217; controller to use this the model.</p>
<p>In your application/controllers/hello.php update your index() method to look like this:</p>
<pre>    public function index()
     {
        // Load the models
        $post  = new Post_Model;
        $posts = $post-&gt;getPosts();
        $rpsts = "";

        // Loop thru the posts
        foreach($posts-&gt;result_array(FALSE) as $row)
         {
          // Simple output of
          $rpsts .= '
    &lt;h1&gt;'.$row['title'].'&lt;/h1&gt;
    '.$row['post'].'&lt;hr /&gt;';
         }

        // Put something useful in our variables.
        $this-&gt;template-&gt;header-&gt;pageTitle .= ' ::: I am on the top';
        $this-&gt;template-&gt;content-&gt;content   = $rpsts;
     }</pre>
<p>When we run the hello controller, we won&#8217;t get much but &#8216;This is my second view&#8217;. We need to put stuff in the table. Use your favorite method of accessing your DB and insert some rows. Now when you run it you will see stuff!</p>
<p>If you notice there is a &#8220;$post-&gt;result_array()&#8221; inside a foreach loop. This allows us to loop though the results of the query easily from within the controller.</p>
<p>You might have notice something of bad practice. I pretty much created HTML inside the controller. As we all know, we shouldn&#8217;t do this. Let&#8217;s fix this!</p>
<p>Create a new view named main_posts.php and make it look like:</p>
<pre>&lt;?php foreach($posts as $post): ?&gt;
&lt;h1&gt;&lt;?php echo $post['title'];?&gt;&lt;h1&gt;
&lt;?php echo $post['post'];?&gt;&lt;hr /&gt;
&lt;?php endforeach; ?&gt;</pre>
<p>This view does a foreach on our query results and fills in our little view.</p>
<p>In the the index method of our controller we will need to change up the controller to use our new view.</p>
<pre>   public function index()
     {
        // Load the models
        $post  = new Post_Model;
        $posts = $post-&gt;getPosts();

        // Put something useful in our variables.
        $this-&gt;template-&gt;header-&gt;pageTitle .= ' ::: I am on the top';

        // Posts view
        $this-&gt;template-&gt;content-&gt;content        = new View('main_posts');
        $this-&gt;template-&gt;content-&gt;content-&gt;posts = $posts-&gt;result_array(FALSE);
     }</pre>
<p>As you can tell, it&#8217;s pretty simple and it&#8217;s clean! Here&#8217;s a quick sample on how to do an insert. We are going to add a method to the post model called addPost.</p>
<pre>  public function addPost($title, $post)
    {
       $sql = sprintf('INSERT INTO `posts`
                       SET         `title` = %s,
                                   `post`  = %s',
                       $this-&gt;db-&gt;escape($title),
                       $this-&gt;db-&gt;escape($post));
      $this-&gt;db-&gt;query($sql);
    }</pre>
<p>We need to add a method to handle adding of posts to our hello controller:</p>
<pre>   public function addpost()
     {
        // Load the models
        $post  = new Post_Model;
        $post-&gt;addPost($_POST['title'], $_POST['post']);
        url::redirect('hello');
     }</pre>
<p>And lets add a form to the end of the main_post.php in the views:</p>
<pre>&lt;form method="POST" action="&lt;?php echo url::base();?&gt;hello/addpost/"&gt;
  &lt;table&gt;
    &lt;tr&gt;
     &lt;th&gt;
       Title
     &lt;/th&gt;
     &lt;th&gt;
       Post
     &lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
     &lt;td&gt;
      &lt;input type="text" name="title" /&gt;
     &lt;/td&gt;
     &lt;td&gt;
      &lt;textarea cols="20" rows="5" name="post"&gt;&lt;/textarea&gt;
      &lt;input type="submit" name="submit" value="Submit"/&gt;
     &lt;/td&gt;
  &lt;/table&gt;
&lt;/form&gt;</pre>
<p>Once again, pretty simple right? I could go on and give you how to edit entries, but I&#8217;m leaving that to you for your home work. Free free to post your results! Until next time when will go over libraries and helpers, keep on coding till your fingers bleed!</p>
<p>If you enjoyed this tutorial, please check out our <a href="http://www.dealtaker.com/tech-deals.html" target="_blank">tech deals</a> and <a href="http://www.dealtaker.com/Computer-store-coupons-10.html" target="_blank">Computer related coupons</a>.</p>
<p><a href="http://images.dealtaker.com/dealtaker/blog/kohana/dealtaker-kohana-3.zip">Get the file for this tutorial here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dealtaker.com/our-blog/2009/06/19/kohana-php-tuturial-part-iii/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
	</channel>
</rss>

