Kohana PHP Tuturial – Part III
Posted by ellisgl on June 19, 2009
It’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 took the last tutorial and updated the core and made sure it worked with Kohana 2.3.4. You can grab that here. Now onward to the glory!
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’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.
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:
$config['default'] = array ( 'benchmark' => TRUE, 'persistent' => FALSE, 'connection' => array ( 'type' => 'mysql', 'user' => 'root', 'pass' => 'root', 'host' => 'localhost', 'port' => FALSE, 'socket' => FALSE, 'database' => 'myfirstkohana' ), 'character_set' => 'utf8', 'table_prefix' => '', 'object' => TRUE, 'cache' => FALSE, 'escape' => TRUE );
Now that we have a configuration a connection for our database, we should probably set up a database and a table. Here’s the SQL:
/*!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 */;
This is a pretty straight forward “Create a DB and one table” 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.
Onward to creating an actual model. There are a couple things to keep in mind with naming conventions, well really one. From the docs “The model class name is capitalized, does have _Model appended to it and should be the singular form of the name.”. There are so other rules when you are dealing with ORM, but we won’t be dealing with ORM in this tutorial.
Create a file named post.php in the ‘application/models/’ folder and make it look like the following:
<?php
defined('SYSPATH') or die('No direct script access.');
class Post_Model extends Model
{
public function __construct()
{
parent::__construct();
}
}
As you can tell the above really doesn’t do much, so let’s give it some functionality:
<?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->db->query($sql);
}
}
So we have a model method that pulls 10 posts from the table with a pretty simple query. We use “$this->query()” to run queries, which will return object and we return that to the calling entity. Check the query method docs here for more information.
Let’s update our ‘Hello’ controller to use this the model.
In your application/controllers/hello.php update your index() method to look like this:
public function index()
{
// Load the models
$post = new Post_Model;
$posts = $post->getPosts();
$rpsts = "";
// Loop thru the posts
foreach($posts->result_array(FALSE) as $row)
{
// Simple output of
$rpsts .= '
<h1>'.$row['title'].'</h1>
'.$row['post'].'<hr />';
}
// Put something useful in our variables.
$this->template->header->pageTitle .= ' ::: I am on the top';
$this->template->content->content = $rpsts;
}
When we run the hello controller, we won’t get much but ‘This is my second view’. 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!
If you notice there is a “$post->result_array()” inside a foreach loop. This allows us to loop though the results of the query easily from within the controller.
You might have notice something of bad practice. I pretty much created HTML inside the controller. As we all know, we shouldn’t do this. Let’s fix this!
Create a new view named main_posts.php and make it look like:
<?php foreach($posts as $post): ?> <h1><?php echo $post['title'];?><h1> <?php echo $post['post'];?><hr /> <?php endforeach; ?>
This view does a foreach on our query results and fills in our little view.
In the the index method of our controller we will need to change up the controller to use our new view.
public function index()
{
// Load the models
$post = new Post_Model;
$posts = $post->getPosts();
// Put something useful in our variables.
$this->template->header->pageTitle .= ' ::: I am on the top';
// Posts view
$this->template->content->content = new View('main_posts');
$this->template->content->content->posts = $posts->result_array(FALSE);
}
As you can tell, it’s pretty simple and it’s clean! Here’s a quick sample on how to do an insert. We are going to add a method to the post model called addPost.
public function addPost($title, $post)
{
$sql = sprintf('INSERT INTO `posts`
SET `title` = %s,
`post` = %s',
$this->db->escape($title),
$this->db->escape($post));
$this->db->query($sql);
}
We need to add a method to handle adding of posts to our hello controller:
public function addpost()
{
// Load the models
$post = new Post_Model;
$post->addPost($_POST['title'], $_POST['post']);
url::redirect('hello');
}
And lets add a form to the end of the main_post.php in the views:
<form method="POST" action="<?php echo url::base();?>hello/addpost/">
<table>
<tr>
<th>
Title
</th>
<th>
Post
</th>
</tr>
<tr>
<td>
<input type="text" name="title" />
</td>
<td>
<textarea cols="20" rows="5" name="post"></textarea>
<input type="submit" name="submit" value="Submit"/>
</td>
</table>
</form>
Once again, pretty simple right? I could go on and give you how to edit entries, but I’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!
Get the file for this tutorial here.

Isaiah said,
Nice tutorial. A few suggestions through.
Don’t use the __construct() function in your model if all you are going to do is call the parent.
Is there a reason you decided to do a manual query instead of just $this->db->insert(’posts’, array(’title’ => $title’, ‘post’ => $post)); ? Seems like using the query builder for simple stuff like this is a good idea.
It looks like the code in your index() function got truncated, might want to fix that so people don’t have problems.
Great job on the tutorials, keep up the good work!
ellisgl said,
I thought the construct had to be there, so I can get $this->db
As for the query builder, I just rather have full control of my query for the most part.
Ah.. I’ll have to fix that..
ellisgl said,
Ok I fixed it!
ellisgl said,
As for the construct, I would want access to the DB stuff to all the method. Of course I could have initiated a new object of the DB library to get what I needed. But what would I lose by doing that instead of calling the parent?
Isaiah said,
If you want full control over the query it would be better (to show off more of Kohana’s features) to use Kohana’s built-in query binding instead of sprintf/manually calling the escape function.
In php5 the parent constructor will automatically be used if your class doesn’t supply one. So you can delete all the __construct() stuff and $this->db will still work.
ellisgl said,
I’ll make my next tutorial about the DB methods instead of the helper and libraries. =)
Ah, I did not know that it would auto call that. Awesome. Learn something new the other day.
seralf said,
Hi
testing the code i need to put a little modification on ‘hello.php’ controller, in order to avoid error messages:
public function addpost()
{
// Load the models
$post = new Post_Model();
if (isset($_POST['title']) && isset($_POST['post']))
$post->addPost($_POST['title'], $_POST['post']);
else
echo(”form not valid or incomplete!”);
url::redirect(’hello’);
}
—-
thanks for the articles: they are very simple and clear, i hope you go further…
Alfredo
ellisgl said,
Good catch seralf! I will be going further in these tutorials.
ellisgl said,
I will be waiting for Kohana 3 to be released and I’ll re do the series.
crazyJAT said,
You could really simplify your code quite a bit if you were to use css standard coding techniques. You could achieve the same effect with:
<form method="POST" action="hello/addpost/”>
Title
Post
ellisgl said,
crazyJAT: I was just doing something quick in that example.
ellisgl said,
@Isaiah: I just was playing around and yes, you need to call the parent’s constructor via the extended class or you can’t access anything.. hmph.
Add A Comment