Blog tutorial (Part 1)
- Posted by dlib on March 26th, 2008 filed in Blog tutorial, Formation, Medium, Tutorials
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.
March 27th, 2008 at 2:43 am
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.
March 27th, 2008 at 5:28 pm
Good work, really good example and explanation.
Waiting for the next part
March 27th, 2008 at 8:18 pm
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
March 28th, 2008 at 2:57 pm
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)
April 5th, 2008 at 3:23 pm
[...] 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, [...]
April 13th, 2008 at 5:47 pm
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?
April 22nd, 2008 at 4:17 pm
whereis “Formation” class??
i cant find how to extend it.
April 22nd, 2008 at 6:02 pm
I’ve included a link at the top.
May 24th, 2008 at 8:54 am
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
May 24th, 2008 at 10:32 am
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
June 17th, 2008 at 2:26 am
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?
June 17th, 2008 at 7:24 am
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.
July 12th, 2008 at 2:46 pm
If you aren’t using 2.2 then the forge render line should read
$form->html();instead of$form->render()August 16th, 2008 at 10:07 pm
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!
August 30th, 2008 at 11:24 am
@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.
August 31st, 2008 at 12:57 pm
Where on earth can I find the Forge module, it didn’t come bundled with Kohana & I’d prefer not to use Formation.
August 31st, 2008 at 1:41 pm
It’s somewhere on Google Code. It’s not actively maintained by Kohana devs though.
September 21st, 2008 at 1:45 am
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
September 25th, 2008 at 11:54 pm
Where is “ndorin’s post on google formation page” I looked and could not find anything.
September 26th, 2008 at 12:26 am
Never mind. I found it at the end of http://code.google.com/p/kohana-mptt/wiki/Formation_Documentation
October 13th, 2008 at 7:54 am
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..
October 13th, 2008 at 11:11 am
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