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.
free viagra
buy viagra online
generic viagra
how does viagra work
cheap viagra
buy viagra
buy viagra online inurl
viagra 6 free samples
viagra online
viagra for women
viagra side effects
female viagra
natural viagra
online viagra
cheapest viagra prices
herbal viagra
alternative to viagra
buy generic viagra
purchase viagra online
free viagra without prescription
viagra attorneys
free viagra samples before buying
buy generic viagra cheap
viagra uk
generic viagra online
try viagra for free
generic viagra from india
fda approves viagra
free viagra sample
what is better viagra or levitra
discount generic viagra online
viagra cialis levitra
viagra dosage
viagra cheap
viagra on line
best price for viagra
free sample pack of viagra
viagra generic
viagra without prescription
discount viagra
gay viagra
mail order viagra
viagra inurl
generic viagra online paypal
generic viagra overnight
generic viagra online pharmacy
generic viagra uk
buy cheap viagra online uk
suppliers of viagra
how long does viagra last
viagra sex
generic viagra soft tabs
generic viagra 100mg
buy viagra onli
generic viagra online without prescription
viagra energy drink
cheapest uk supplier viagra
viagra cialis
generic viagra safe
viagra professional
viagra sales
viagra free trial pack
viagra lawyers
over the counter viagra
best price for generic viagra
viagra jokes
buying viagra
viagra samples
viagra sample
cialis
generic cialis
cheapest cialis
buy cialis online
buying generic cialis
cialis for order
what are the side effects of cialis
buy generic cialis
what is the generic name for cialis
cheap cialis
cialis online
buy cialis
cialis side effects
how long does cialis last
cialis forum
cialis lawyer ohio
cialis attorneys
cialis attorney columbus
cialis injury lawyer ohio
cialis injury attorney ohio
cialis injury lawyer columbus
prices cialis
cialis lawyers
viagra cialis levitra
cialis lawyer columbus
online generic cialis
daily cialis
cialis injury attorney columbus
cialis attorney ohio
cialis cost
cialis professional
cialis super active
how does cialis work
what does cialis look like
cialis drug
viagra cialis
cialis to buy new zealand
cialis without prescription
free cialis
cialis soft tabs
discount cialis
cialis generic
generic cialis from india
cheap cialis sale online
cialis daily
cialis reviews
cialis generico
how can i take cialis
cheap cialis si
cialis vs viagra
levitra
generic levitra
levitra attorneys
what is better viagra or levitra
viagra cialis levitra
levitra side effects
buy levitra
levitra online
levitra dangers
how does levitra work
levitra lawyers
what is the difference between levitra and viagra
levitra versus viagra
which works better viagra or levitra
buy levitra and overnight shipping
levitra vs viagra
canidan pharmacies levitra
how long does levitra last
viagra cialis levitra
levitra acheter
comprare levitra
levitra ohne rezept
levitra 20mg
levitra senza ricetta
cheapest generic levitra
levitra compra
cheap levitra
levitra overnight
levitra generika
levitra kaufen
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
November 25th, 2008 at 6:48 pm
Too difficult to try with newbie
December 10th, 2008 at 4:48 pm
Hi!
I followed the tutorial and it went well, until I was gonna try to read the add_post that you told us to in the tutorial.
First, it said that it couldn’t find /kohana/blog/add_post
Then I realized that I hadn’t turned on the htaccess, so I got the .htaccess now(as given from the download - example).
However, now it gives me an error:
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, admin@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
Any idea why? I would really love to get kohana working, cause it seems great!
Thanks for tutorial, but still a little too.. advanced xD
Thanks in advance
December 10th, 2008 at 5:31 pm
Okey. Disregard my other post, I got it working(stupid me!).
Anyways, a new problem has occured:
Fatal error: Class ‘Log’ not found in C:\wamp\www\kohana\modules\formation\libraries\Formation.php on line 34
Where would I find that class? And where should it be put?
Thanks!
December 12th, 2008 at 5:35 pm
I got the same problem.
You need to go to: http://code.google.com/p/kohana-mptt/wiki/Formation_Documentation
and look for this post:
Comment by ndorin, Sep 17, 2008
I’m also new to Kohana and this tutorial did not help.
Maybe someone could write a better tutorial that just uses the framework. So newbies do not have to install modules or anything.
December 22nd, 2008 at 4:51 pm
Bearing in mind this is the tutorial recommended as the starting place for new Kohana users, requiring an optional module seems to make things unnecessarily hard. Why not have a tutorial that uses the normal tools available?
Off to find a better tutorial. I may look for another framework if this is the standard of the rest of the documentation (plus a number of the general pages have dead links etc.).
December 22nd, 2008 at 5:02 pm
It gets better. The installation instructions for the required formation package state:
“Before installation you should know how to work with Kohana else this might become difficult.”
The recommended starting tutorial, requires a module, and that module cannot be installed without knowing how to work with Kohana. This is somewhat circular….
January 7th, 2009 at 1:10 pm
> Before installation you should know how to work with Kohana else this might become difficult.
How is one intended to know how to work with Kohana if he had not ever heard of it before today and there is no sane intro available?
I’ve clean-installed kohana and followed this tutorial, and still was getting a welcome page at http://localhost/blog/. Then I’ve concluded that I have to override default route by copying a routes.php from to system\config to blog\config and replacing ‘welcome’ by ‘blog’ there to get my blog working, but that lead to a big nasty exception instead.
January 7th, 2009 at 2:05 pm
> and there is no sane intro available?
Excuse me, I’ve finally found kohana101.pdf - looks sane
Should be linked from some very visible place, imho.
For those seeking for an intro: http://forum.kohanaphp.com/comments.php?DiscussionID=1144&page=1#Item_0
January 10th, 2009 at 3:27 am
hi
65m4z178nftcostk
good luck
February 15th, 2009 at 9:54 pm
got an error on line 2 of /library/Post_Form.php which looks like this:
class Post_Form_Core extends Formation{what should it look like??
March 2nd, 2009 at 12:45 pm
it seems that kohana can call any other controllers/models just from any controller/model, right?
I still confused..
Sorry for my bad english..
March 9th, 2009 at 8:21 pm
Hello,
I try to follow this Kohana blog tutorial, but I get this error:
atal error: Class ‘Posts_Model’ not found in /XXX/www/kohana/system/libraries/ORM.php on line 82
I have tried to copy/paste the code above, am I missing something ?
March 12th, 2009 at 1:09 pm
It would be nice to have all the tutorial Not using external libraries, aka, Formation
March 15th, 2009 at 4:22 pm
[...] Este artículo es la traducción libre de la primera parte de uno de sus tutoriales, ya que no he encontrado mucha documentación sobre Kohana en castellano. El artículo original, puede encontrarse aquí. [...]
April 6th, 2009 at 9:05 pm
Is this tutorial still applicable to version 2.3.2? I’m getting an error in the MY_ORM.php file in Formation and am unsure if it is a problem on my end or if this tutorial needs to be updated.
April 6th, 2009 at 9:11 pm
Sorry, meant to include the error with my post:
system/libraries/ORM.php [363]:
The table property does not exist in the Post_Model class.
Stack Trace
* modules/formation/libraries/MY_ORM.php [36]:
ORM_Core->__get( table )
I added this line to my Post_Model class: var $table=’posts’;, but that just resulted in another error in MY_ORM.php:
Fatal error: Access to undeclared static property: ORM::$fields in /var/www/kohana/modules/formation/libraries/MY_ORM.php on line 36
Any ideas?
April 9th, 2009 at 5:28 am
I think I figured it out.
April 12th, 2009 at 5:49 am
@Red John: How can u figure out? I had a similar problem. It seems there is a conflict between MY_ORM.php of the Formation 0.98 and ORM.php of v2.3.2
April 15th, 2009 at 8:15 pm
[...] de la primera parte del tutorial: Kohana BLog Tutorial (Part 1) [...]
April 20th, 2009 at 5:15 pm
This is a really frustrating experience for anyone trying to get a quick introduction to kohana…
I think that from the start it is a bad idea to use Formation, since it is not being maintained, or at least provide a snippet with the needed fixes to have Formation working with the last version of the framework.
Also, it is an aggravating comparison with CE’s blog-in-twenty-minutes 101 tutorial…
April 25th, 2009 at 7:21 am
hohoho
June 25th, 2009 at 6:20 pm
I’ve arrived to CI but noted their commercial features and then I’ve found Kohana… jeje… It seems very pro at first sight…! But not so easy to use…
Will keep trying…
Greeting to he community!