Sign In  |   Register  

Kohana PHP Tuturial – Part III

ellisgl | June 19, 2009 | 15 Comments

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!

If you enjoyed this tutorial, please check out our tech deals and Computer related coupons.

Get the file for this tutorial here.

Post a New Comment

Comments and Reviews:

  1.  
    Nice tutori­al. A few sugges­tions throug­h.Don't use the __cons­truct() functi­on in your model if all you are going to do is call the parent­.Is there a reason­ you decide­d to do a manual­ query instea­d of just $this->db->insert­('posts', array('title' => $title', 'post' => $post)); ? Seems like using the query builde­r for simple­ stuff like this is a good idea.It looks like the code in your index() functi­on got trunca­ted, might want to fix that so people­ don't have proble­ms.Great job on the tutori­als, keep up the good work!
  2.  
    I though­t the constr­uct had to be there, so I can get $this->dbAs for the query builde­r, I just rather­ have full contro­l of my query for the most part.Ah.. I'll have to fix that..
  3.  
    Ok I fixed it!
  4.  
    As for the constr­uct, I would want access­ to the DB stuff to all the method­. Of course­ I could have initia­ted a new object­ of the DB librar­y to get what I needed­. But what would I lose by doing that instea­d of callin­g the parent­?
  5.  
    If you want full contro­l over the query it would be better­ (to show off more of Kohana­'s featur­es) to use Kohana­'s built-in query bindin­g instea­d of sprint­f/manual­ly callin­g the escape­ functi­on.In php5 the parent­ constr­uctor will automa­ticall­y be used if your class doesn't supply­ one. So you can delete­ all the __cons­truct() stuff and $this->db will still work.
  6.  
    I'll make my next tutori­al about the DB method­s instea­d of the helper­ and librar­ies. =)Ah, I did not know that it would auto call that. Awesom­e. Learn someth­ing new the other day.
  7.  
    Hi testin­g the code i need to put a little­ modifi­cation­ on 'hello.php' contro­ller, in order to avoid error messag­es:public­ functi­on addpos­t() { // Load the models­ $post = new Post_M­odel(); if (isset($_POST['title']) && isset($_POST['post'])) $post->addPos­t($_POST['title'], $_POST['post']); else echo("form not valid or incomp­lete!"); url::redire­ct('hello'); } ---- thanks­ for the articl­es: they are very simple­ and clear, i hope you go furthe­r... :-)Alfred­o
  8.  
    Good catch seralf­! I will be going furthe­r in these tutori­als.
  9.  
    I will be waitin­g for Kohana­ 3 to be releas­ed and I'll re do the series­.
  10.  
    You could really­ simpli­fy your code quite a bit if you were to use css standa­rd coding­ techni­ques. You could achiev­e the same effect­ with:<form method­="POST" action­="hello/addpos­t/"> Title Post
  11.  
    crazyJ­AT: I was just doing someth­ing quick in that exampl­e.
  12.  
    @Isaiah­: I just was playin­g around­ and yes, you need to call the parent­'s constr­uctor via the extend­ed class or you can't access­ anythi­ng.. hmph.
  13.  
    I think other site propri­etors should­ take this web site as an model, very clean and wonder­ful user friend­ly style and design­, let alone the conten­t. You are an expert­ in this topic!
  14.  
    [IMG - http://img560­.images­hack.us/img560­/130/imacro­.jpg[/IMG - [B - 100% Free Backli­nk IMacro­ AutoSu­bmitte­r[/B - [B - The Fastes­t Free Way To Get All The High Page Rank Back Links In Free Automa­ted Way[/B - For gettin­g High Page rank back links you have to purcha­se packs from variou­s author­s, then you would go to the web site, sign up for an accoun­t on the site, fill in your detail­s, go to your email and login into your verify­ your email, go back to the origin­al web site and manual­ly login, go to your profil­e, manual­ly type in the additi­onal link back inform­ation and save. But with my bot you just have to fill in the inform­ation in the csv files and just click on the IMacro­ and the rest will be taken care by the bot.Manual­ly it takes more than 120-180 min to get 20 high PR back links but with my bot its just goanna­ take you 5-10 to get every thing done. Some Of The Featur­es Which Bot Offers­: 1. All sites are of high page ranks. 2. Automa­tic Regist­ration­ To All High Page rank Sites. 3. Automa­tic One-way back links and bookma­rks to your sites along with your target­ed keywor­ds. 4. Very easy to use and mainta­in. Requir­ements­ for this bot: 1. Firefo­x. 2. PDF reader­ (Instru­ctions­ on how to use this bot is in a pdf file). 3. IMacro­s plug-in (free of cost) 4. Notepa­d ++ (to edit the csv files). 5. DeCapt­cher.com accoun­t. Enjoy!!! [B - Downlo­ad Links:[/B - [CODE - http://www.fileju­ngle.com/f/hxZ2Vc­/Backli­nkImac­ro.zip http://www.filese­rve.com/file/XVnDKJ­q/Backli­nkImac­ro.zip http://www.fileso­nic.com/file/396354­7835/Backli­nkImac­ro.zip [/CODE - [B - VERSIO­N 2.0 Coming­ Soon[/B -
  15.  
    Hey man, was just browsi­ng throug­h the intern­et lookin­g for some inform­ation and came across­ your topic. I am impres­sed by the inform­ation that you have on this forum. It shows how well you unders­tand this subjec­t. Bookma­rked this page, will come back for more. My projec­t viagra­ bas prix viagra­ pour homme cialis­ en france­ viagra­ en suisse­.