Blog tutorial (Part 1)

Difficulty: Medium

This blog tutorial will do what most blog tutorials do, teach you how to code your own blog. It will have posts and comments but in part 1 I’ll only deal with the posts. Part 2 will deal with comments and the relationship between comments and posts.

We’ll work with models, views and controllers and the libraries utilized will be ORM Formation. Forge can be used as well even though it might work a little different. It is assumed you installed Kohana properly, with a database and without url rewriting to mask index.php in the url.

Step 1: the models
The models stand between the data and the controller and function as an abstraction layer. I use ORM for ease in this example but you can write the queries yourself as well.

//models/post.php
class Post_Model extends ORM{
	protected $has_many=array('comments');
}
//model/comment.php
class Comment_Model extends ORM{
	protected $belongs_to=array('post');
}

You see how the relationship is declared. I’ll go into this in part 2.

Step 2: the tables
You need tables in the database, execute this SQL

CREATE TABLE IF NOT EXISTS `comments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) collate utf8_unicode_ci NOT NULL,
  `email` varchar(255) collate utf8_unicode_ci NOT NULL,
  `text` text collate utf8_unicode_ci NOT NULL,
  `post_id` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
 
 
CREATE TABLE IF NOT EXISTS `posts` (
  `id` mediumint(9) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) collate utf8_unicode_ci NOT NULL,
  `text` text collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

Step 3: the controllers
We want the blog available under http://localhost/blog so we create a Blog_Controller

//controllers/blog.php
class Blog_Controller extends Controller {}

The basis is laid, we first want to add posts before anything else so we add an add_post() method to our controller

class Blog_Controller extends Controller {
	public function add_post()
	{
		$form=new Post_Form;
 
		if($form->validate())
		{
			$post=new Post_Model;
			$post->load_values($form->as_array());//load values of form into model
//see http://learn.kohanaphp.com/2008/02/21/loading-values-into-kohanas-orm/ for more on this method
/* alternatively you can do this
			$post->title= (string) $form['title'];
			$post->text= (string) $form['text'];
*/
			$post->save();//Save post 
 
			url::redirect('blog');
		}
		else
		{
			$view=new View('add_post');
			$view->form=$form->render();
			$view->render(true);
		}
 
	}
}

Now there’s some explaining to be done ;) What happens in the ‘new Post_Form’ statement is that I load a library which is a Formation form. It’s explained in an earlier post on this blog. This library looks like this:

//libraries/Post_Form.php
class Post_Form_Core extends Formation{
	public function __construct()
	{
	  parent::__construct();
      $this->legend='Add post';
      $this->add_element('input','title')->add_rule('required')->add_pre_filter('ucfirst');
      $this->add_element('textarea','text')->add_rule('required');
      $this->add_element('submit','Submit');
	}
}
//or if you use Forge, not the load_values method in the above example is not available
class Post_Form_Core extends Forge{
	public function __construct()
	{
	  parent::__construct();
       $this->input('title')->rules('required');
      $this->textarea('text')->rules('required');
 
      $this->submit('submit');
 
	}
}

It’s simple, one form field for every database field and both fields are required. The first field is capitalized.

Back to the controller, after I instantiate the form I ask for it to be validated. If it doesn’t validate (e.g. no post request or invalid field values) I output the form, else I save the form to the database and redirect to a page listing all posts.

One more thing, I load a viewfile ‘add_post’. It’s found in ‘views/add_post.php’

<h1>Add post</h1>
<?php
echo $form;
?>

That’s what it looks like, you can see that the variables match to the properties of the view object in the controller. Now you can go to localhost/blog/add_post and add posts to your blog.

Now, on to the listing of the posts.
We add another controller method:

class Blog_Controller extends Controller{
//..... add_post() etc. //
public function index()
{
		$view=new View('blog');
		$view->posts=ORM::factory('post')->orderby('id','desc')->find_all();
		$view->render(true);	
}
}

I load all posts with the ORM factory and add the results to the view.
The view (views/blog.php) will look like:

foreach($posts as $post)
{
	echo '<h1>'.$post->title.'</h1>';
	echo '<p>'.$post->text.'</p>';
}

That’s it, you can freely add posts to your blog and they will all show up when you enter localhost/blog

In part 2 of this tutorial I’ll deal with comments and relationships.

Note: I made an error with the sql for the tables. It’s fixed now.


22 Responses to “Blog tutorial (Part 1)”

  1. neovive Says:

    Great tutorial! With all of these good ORM examples in the past few posts, I may have give ORM a try for some of my models.

  2. Alex Sancho Says:

    Good work, really good example and explanation.

    Waiting for the next part ;)

  3. Matt Says:

    Awesome tutorial Just one question, within ORM all tables are plural, so obviously $has_many=array(’comments’);, so is it definitely correct that $belongs_to=array(’post’); post is singular?

    This also reminds me that I definitely need to check out your Formation module!

    Cheers

    /Matt

  4. dlib Says:

    Part 2 is out which should explain it in part. Basically you read the line as a sentence. Post_Model has many comments (plural), Comment_Model belongs to (one) post (singular)

  5. sam.clark.name » Kohana PHP Object Relational Mapping Guide supporting files Says:

    [...] Attribution-Non-Commercial-Share Alike 2.0 UK: England & Wales License.Based on a work at learn.kohanaphp.com. April 5th, 2008 / 0 Comments / Tags: kohana php, orm, guide, supporting files, [...]

  6. Leo Says:

    Is it smart to base all of these posts on Formation? Is it officially part of Kohana? Will new users understand what Formation is (and how to enable it) without disclaiming it at the beginning of the article?

  7. vandai Says:

    whereis “Formation” class??
    i cant find how to extend it.

  8. dlib Says:

    I’ve included a link at the top.

  9. Patryk Says:

    Hello i have problem with add_post
    Fatal error: Class ‘required’ not found in C:\wamp\www\kohana\modules\formation\libraries\Field.php on line 307

  10. dlib Says:

    Sorry, I updated the code in the svn not in any the release. Instead of ‘required’ do ‘Rule_Required’
    See http://code.google.com/p/kohana-mptt/source/detail?r=70

  11. Peter Weil Says:

    When I run http://localhost/blog/, I’m still getting the default welcome in my browser page, and I’m not sure why. What should the welcome controller look like? What else should I be looking/checking for?

  12. dlib Says:

    I’m not sure what you mean. If you want to change the default route (when no controller is given in the url) go to the config/routes.php file and change _default.

    If no method is set in the url the index method is called.

  13. Caius Says:

    If you aren’t using 2.2 then the forge render line should read

    $form->html(); instead of $form->render()

  14. Gonzalo Says:

    Hello, I am totally new to kohana, I have just decided to use it and installed it… after some investigation seems to be the best for the project I am starting.

    I would like to know how to configure the database connection and its properties… can anyone help me with this?

    Thanks in advance!

    BTW: Great tutorial and great blog! Added to favourites!

  15. Dmitry Seredinov Says:

    @Gonzalo

    Simplest solution to your question is just copy file Database.php from your system/config dir to your application/config dir.
    Then change a values in this file to actual (related to your DB).
    Note: for flexibility of your app, you will not change appropriated values in system/config dir files. It will looks like hard-coding method :)
    But, in any case, you can do that.

  16. Andrew Says:

    Where on earth can I find the Forge module, it didn’t come bundled with Kohana & I’d prefer not to use Formation.

  17. dlib Says:

    It’s somewhere on Google Code. It’s not actively maintained by Kohana devs though.

  18. Karsten Says:

    For those going through this tutorial using kohana 2.2 and are newish to mvc, formation and ORM:

    1) download formation (link above)
    2) modify formation to work with 2.2! (see ndorin’s post on google formation page)
    2) enable it in your application config
    3) delete the MY_ORM.php in the formation library
    4) make sure your application config paths are correct
    5) dont use orm load_values

  19. toulon Says:

    Where is “ndorin’s post on google formation page” I looked and could not find anything.

  20. toulon Says:

    Never mind. I found it at the end of http://code.google.com/p/kohana-mptt/wiki/Formation_Documentation

  21. robnardo Says:

    I would love to see a tutorial on how to create a blog without Forge or Formation, instead calling a hand-coded form with validation from somewhere like ‘/application/views/forms/my_form.php’. It would help us noobs understand the Validation library, Form Helper, and Templates..

  22. DeluxZ Says:

    I agree with robnardo. Im coming from CodeIgniter and want to try this. But im already stuck with this tutorial. Only with the Formation/Forge library. Maybe you could explain how to integrate the FOrmation/Forge library into Kohana

Leave a Comment