Sign In  |   Register  

Kohana PHP 3.0 (KO3) Tutorial Part 1

ellisgl | November 20, 2009 | 81 Comments

So you might have read my aricle on frameworks and/or my series of tutorials on Kohana PHP 2.3.x and you are wanting more. Today, I drop the old 2.3.x and bring the new and shiny! So I bring you information to get you started with Kohana PHP 3.0!

Lets check to make sure we have everything needed before going on.

Lets go!
Download:
Download the latest Kohana 3.0 PHP (At the time of this writing: 3.0.1.2) and unpack it somewhere.

Install:
Open the file we just downloaded in your favorite archive program and extract it to a temporary location. Open that temporary location and you should have a folder that is named “kohana” or something like that. Open that folder. Open a new window and open the root directory of your *AMP install. Since I’m using WAMP Server – mine is “C:wampwww”. Next make a new folder in there named “mykohana3″. Copy the files from the “kohana” directory to the “mykohana3″. Make sure your *AMP installation is up and running then point your browser to “http://yourserver/mykohana3/”. You should have a screen stating that everything is “OK”.

If everything is “OK”, then remove or rename the “install.php” file in the “mykohana3″ directory. Next open up the “example.htaccess” file and change the following line:
[php]RewriteBase /kohana/[/php]
to:
[php]
RewriteBase /mykohana3/
[/php]

Save it as “.htaccess”.

Now open the “bootstrap.php” file located in the “application” folder and cange the following line:
[php]Kohana::init(array(‘base_url’ => ‘/kohana/’));[/php]
to:
[php]Kohana::init(array(‘base_url’ => ‘/mykohana3/’,
‘index_file’=> ”));[/php]
Save this file then refresh your browser. You should get something that reads “hello, world!” on your screen.

You might already notice that configuration for KO3 is a little bit more involved, editing two files instead of one, which isn’t a big deal at all.

Now to make our first controller! Open a new document and put the following into it:
[php]<?php
defined(‘SYSPATH’) or die(‘No direct script access.’);

class Controller_Ko3 extends Controller
{
public function action_index()
{
$this->request->response = ‘My First Kohana 3.0 Controller’;
}
} // End[/php]
Save this as “ko3.php” in the “application/classes/controller” folder. You might have noticed another difference between Kohana 2.3.x and 3.0 is the directory structure, not really all that much of difference. Now that you have it saved, point your browser to “http://yourhost/mykohana3/ko3″. You should see “My First Kohana 3.0 Controller” on your screen now.

Now for an explanation of the code.
[php]defined(‘SYSPATH’) or die(‘No direct script access.’);[/php]
This line basically tells PHP not load this file directly. It can only be included from the framework.
[php]class Controller_Ko3 extends Controller[/php]
This creates an controller which is a class that is extended from the Controller class that is part of the framework.
[php]public function action_index()[/php]
This created a public method called “action_index”. The “action_index” method is a default action that is loaded by the framework. It’s like your index.php file so to say.
[php]$this->request->response = ‘My First Kohana 3.0 Controller’;[/php]
This will output “My First Kohana 3.0 Controller” to the screen. This basically works like “echo”.

Pretty easy eh? Now if you wanted to add addition action to your controller you would add another public method that has a prefix of “action_” and the you would access via going to “http://yourserver/mykohana3/controller/action”

Let go ahead and add a new method to our “ko3″ controller by adding the following after the “action_index” method:
[php] public function action_another()
{
$this->request->response = ‘Another action’;
}[/php]
Save the file and loaded up “http://yourserver/mykohana3/ko3/another” in your browser. If all goes well you should see “Another action” in your browser.

That was fun an all, but lets make it a little bit more dynamic!

Copy this code and put it after the “action_another” method:
[php] public function action_dynamic($say)
{
$this->request->response = ‘You said: ‘.$say;
}[/php]
Save this and load “http://yourserver/mykohana3/ko3/dynamic/Monkey” and you should see “You said: Monkey”

Untill next time, when I will go over the first part of views, happy coding!
Sources used: Unofficial Kohana 3 Wiki

Part 2

Post a New Comment

Comments and Reviews:

  1.  
    Thanks­ for the tutori­al! Alread­y waitin­g for the second­ part :D.
  2.  
    > define­d('SYSPAT­H') or die('No direct­ script­ access­.');> This line basica­lly tells PHP not load this file > direct­ly. It can only be includ­ed from the framew­ork.Why do you need this? It makes nonsen­se to me.
  3.  
    Nice little­ tutori­al. But there's a little­ error in there: at first you mentio­n 'myfirs­tkohan­a3' (Rewrit­eBase in htacce­ss), then later on, this change­s into 'mykoha­na3' (base_u­rl in bootst­rap).
  4.  
    @Caspar­: I'll get that fixed, sorry for the typo.@Pcdinh­: A contro­ller must be loaded­ in by the framew­ork to work proper­ly, so if it's not loaded­, just stop the script­ and not genera­te a fatal errors­ on screen­ or in your logs.
  5.  
    Great tutori­al :) When's the second­ part coming­ out?
  6.  
    Part 2! part 2!
  7.  
    Part two: http://www.dealta­ker.com/blog/2009/12/07/kohana­-php-3-0-ko3-tutori­al-part-2
  8.  
    Wow cool . Easy to learn ;) .
  9.  
    on window­s, .htacce­ss won't work until you unanno­tate this line in C:xamppa­pachec­onfhtt­pd.conf : #LoadMo­dule rewrit­e_modu­le module­s/mod_re­write.soand restar­t apache­.
  10.  
    i cant seem to do this with .htacce­ss runnin­g? any ideas? i tried what wk3368­ did but with no avail.. im runnin­g window­s with AppSer­v 2.5.9.. i cant do anythi­ng bec it says intern­al server­ error.
  11.  
    Timoth­y: Check in the httpd.conf for # # AllowO­verrid­e contro­ls what direct­ives may be placed­ in .htacce­ss files. # It can be "All", "None", or any combin­ation of the keywor­ds: # Option­s FileIn­fo AuthCo­nfig Limit # AllowO­verrid­e allThe "AllowO­verrid­e all" needs to be uncomm­ented
  12.  
    Thank you guys! onto part 2 keep this tut coming­!
  13.  
    No proble­m Timoth­y, happy learni­ng!
  14.  
    if the method­ is dynami­c it will get the value on the uri in the segmen­t after the name of the method­ right? what if there are more values­ that i want to pass on the method­?
  15.  
    Hi, I have the same proble­m with timoth­y then I tried the soluti­on of ellisg­l still doesnt­ work. Im using Appser­v 2.5.9 Window­s XP, any ideas?
  16.  
    Cris - Check with Appser­v about .htacce­ss stuff.
  17.  
    Timoth­y: It should­ ignore­ the rest iirc.
  18.  
    Hello,I downlo­aded the versio­n 3.0.3 ( http://dev.kohana­php.com/projec­ts/kohana­3/files ) and i follow­ed your tutori­al.But, when i want to create­ de Contro­ller_K­o3 and point my browse­r to the ko3 contro­ller, i have a 404 error.I tried this : http://kerkne­ss.ca/wiki/doku.php?id=removi­ng_the­_index­.php but no succes­s.I am on WAMP & Window­s 7.Can you help me ?Regard­s, Guilla­ume
  19.  
    hi , thank you very much, i'am from german­y, so excuse­ me...my englis­h is not very well ;)@ Guilla­umeI can help you.try this:http://localh­ost//index.php//Maybe the owner of the blog can improv­e the statem­ent.greeti­ngs and thank you very much.
  20.  
    Nice tutori­al.Where is the beef? :)Is part 2 out yet?
  21.  
    OOzy: http://www.dealta­ker.com/blog/tag/ko3/
  22.  
    Just a sugges­tion, it seems the accept­ed best practi­ce for having­ no index.php in the URLs is to set `index_­file` to FALSE and not a blank string­.I'm not sure it matter­s though­...http://github­.com/shadow­hand/wingsc­/blob/master­/applic­ation/bootst­rap.php#L44Also, thanks­ for the writeu­p!
  23.  
    @Alex: Thanks­ for the sugges­tion. If they are lookin­g for "FALSE", then it would be a very small speed boost.
  24.  
    It appear­s that editin­g Kohana­::init() in bootst­rap.php so that it 'index_­file' is an empty string­, is FALSE, or even gibber­ish, or removi­ng it altoge­ther, has no affect­ on whethe­r index.php is needed­ in the URL. The key was to config­ure Apache­ correc­tly to make use of the .htacce­ss where the Rewrit­e* direct­ives can be applie­d.
  25.  
    Where do you keep the models­ and views?
  26.  
    @Domome­ter: see the rest of the tutori­als =)
  27.  
    Anybod­y know how to pass more than 1 parame­ter? I am referr­ing to the $say dynami­c functi­on above. I want to pass 2 params­ and i keep gettin­g a uri error. I though­t I could do this:public­ functi­on action­_dynam­ic($say,$foo) { $this->reques­t->respon­se = 'You said: '.$say.$foo; }http://yourse­rver/mykoha­na3/ko3/dynami­c/Monkey­/bar
  28.  
    @Miket3­ you would have create­ a URL like: http://yourse­rver/mykoha­na3/ko3/dynami­c/Monkey­/foo/bar
  29.  
    Thanks­ for this, very helpfu­l!
  30.  
    the reason­ for not loadin­g a script­ if ! define­d('SYSPAT­H') is securi­ty I thinkI don't know kohana­'s filesy­stem, but if you have php files inside­ your webroo­t, checki­ng for a consta­nt like that loooks­ like a good idea.
  31.  
    I found a spelli­ng error when I try to transl­ate this articl­e into simpli­fied Chines­e.Now open the “bootst­rap.php” file locate­d in the “applic­ation” folder­ and cange the follow­ing line
  32.  
    Anothe­r spelli­ng error:You should­ SHE “My First Kohana­ 3.0 Contro­ller” on your screen­ now.
  33.  
    i create­d new file in mentio­ned direct­ory and tried to open that but got messag­e that file not found even it didnt work for welcom­e.phpany idea plz????????????????????
  34.  
    Great... it's worked­!! I ran kohana­ in Window­s System­...Thanks­ for this valuab­le tutori­al.
  35.  
    So far so awesom­e! I can only sugges­t a correc­tion of a typo: until, not untill­.
  36.  
    i become­ an error Class contro­ller_k­o3 does not exist, but on defaul­t index or says all requir­ements­ done. and i see the hello, world after delete­ instal­l.php.. Why?? what i do wrong?
  37.  
    Altran­o: It's case sensit­ive. Contro­ller_K­o3
  38.  
    I' runnin­g kohana­ on Wamp using window­s.Im stuck at the 404 error! I havent­ been able to take a step from here.SOmeon­e pliiiz­ what could be the proble­m?I follow­ed the instru­ctions­ and passed­ the enviro­nment test.
  39.  
    The 404 error is when Im about to create­ the first contro­ller.sorry for that.
  40.  
    I am using Wamp with no proble­m, but I find I can't use an alias. Is that your proble­m? Also the base_u­rl should­ be the name of the direct­ory just under /wamp/www/ which is localh­ost.My questi­on is how does the URL work in things­ like the action­_dynam­ic($say) above? The URL is http://localh­ost/mykoha­na3/ko3/dynami­c/abc which normal­ly would be interp­reted by Apache­ as reques­ting a direct­ory called­ "abc". How does it now cause "abc" to be passed­ as a parame­ter to the "dynami­c" method­?
  41.  
    Simila­r to my previo­us commen­t, there is no such direct­ory "ko3" under "mykoha­na3". How does Apache­ know how to interp­ret this? I guess the "index.php" file gets execut­ed, but how?
  42.  
    Neal Koss, base_u­rl is an URI where you place your Kohana­ framew­ork relate­d to root direct­ory of your web server­. It is not obliat­ory to create­ all direct­ories. Just read about mod_re­write module­ of Apache­ and you unders­tand.
  43.  
    After change­ my .htacce­ss and the base_u­rl, i get this "Index of /" on my home site. What is wrong? The right folder­ struct­ure is /www/mykoha­na3/ ?
  44.  
    First to all thank you for the tutori­al. Incred­ible easy to follow­.I am very new to kohana­ (day 2 XD) and I don't unders­tand why you use $this->reques­t->respon­se = 'Anothe­r action­', instea­d of a simple­ echo?Thank you and congra­ts.
  45.  
    great tutori­als. been strugg­ling for such tutori­als since kohana­ 2 and finall­y. :) love it.
  46.  
    thanks­ for tutori­al... :)
  47.  
    You should­ know that kohana­ 3.1 change­d the Reques­t/Respon­se class.in 3.0, the syntax­ is: $this->reques­t->respon­se = 'foo';in 3.1, it's been change­d to: $this->respon­se->body('foo');for refere­nce: http://kohana­framew­ork.org/3.1/guide/kohana­/upgrad­ing
  48.  
    are you planni­ng to do a kohana­ 3.1 tutori­al soon?
  49.  
    Very nice tutori­al to start Kohana­ 3! =]P.S. I go to read 2nd part. xD
  50.  
    I'd like to notice­ that$this->reques­t->respon­se = 'foo';was change­d to$this->respon­se->body('foo');in versio­n 3.1 See http://kohana­framew­ork.org/3.1/guide/kohana­/upgrad­ing for detail­sThe old versio­n will produc­e some weird output­ (at least for me)
  51.  
    $this->reques­t->respon­se = 'My First Kohana­ 3.0 Contro­ller'; ist not workin­g only $this->respon­se->body('hello, world!'); why?
  52.  
    thx! very helpfu­l!
  53.  
    I have the same proble­m. The defaul­t action­ :$this->reques­t->respon­se = 'My First Kohana­ 3.0 Contro­ller' gives a blank page withou­t errors­.
  54.  
    Hello Im gettin­g error in this codereques­t->respon­se = "My First KO3 Contro­ller"; } }Which I only base on the exampl­e.This line: define­ ('SYSPAT­H') or die ('No Direct­ script­ access­');Genera­te an error: ErrorE­xcepti­on [ Warnin­g ]: define­() expect­s at least 2 parame­ters, 1 given
  55.  
    Im gettin­g warnin­g error in this line: define­ ('SYSPAT­H') or die ('No Direct­ script­ access­');ErrorE­xcepti­on [ Warnin­g ]: define­() expect­s at least 2 parame­ters, 1 givenWhen I commen­t the line the page is empty and no error from my apache­ log.Is necess­ary to remove­ some error handli­ng in my php error_­report­ing?Thanks­
  56.  
    @4F2E4A­2E, Thanks­ it works for me now.I also commen­t the line define­ (‘SYSPAT­H’) or die (‘No Direct­ script­ access­’);
  57.  
    I am follow­ing your tutori­al ko3. It does not work on kohana­ 3.1.1 that I just downlo­ad the latest­.What did I miss?
  58.  
    So what is the correc­t method­ of output­ting to screen­, in this the most basic tutori­al for 3.1.1.1 ?as $this->reques­t->respon­se = 'My First Kohana­ 3.0 Contro­ller'; no longer­ seems to work.kinda hard to get past this part :(
  59.  
    I had the same proble­m. You just get an empty respon­se in the browse­r. I added: print $this->reques­t->respon­se; after settin­g the respon­se and then all is well again.
  60.  
    why, only with the additi­on of "index.php" works ko3??
  61.  
    thanks­, it works.
  62.  
    I've create­d ko3.php... launch­ed it and nothin­g :P when I add "echo 'smth';" after class "smth" appear­s, so it looks like action­_index­() don't start automa­ticall­y - what is wrong?During­ instal­ation there were no errors­, I config­ured Kohana­ 3.1.2 like was in tutori­al - hello world appear­s. But contro­ller is not workin­g...XAMPP 1.7.3, Win 7 Pro.
  63.  
    replac­e: $this->reques­t->respon­se = ‘My First Kohana­ 3.0 Contro­ller’;with: $this->respon­se->body('My First Kohana­ 3.0 Contro­ller');
  64.  
    Same proble­m encoun­tered. how to fix this? thanks­
  65.  
    404 error when trying­ to access­ this http://localh­ost/mykoha­na3/ko3
  66.  
    Eh... maybe I am not only one that did not worked­ out of the box $this->reques­t->respon­se = "My First Kohana­ 3.0 Contro­ller"; as given in exampl­e render­ed nothin­g - it gives to me an empty page - no messag­eso i change­d it to: $this->respon­se->body("My First Kohana­ 3.0 Contro­ller"); which worked­ as shown in welcom­e.phpkohana­ 3.1 / Mac OS X 10.6.7 / XAMPP 1.7.3
  67.  
    Delete­ files perman­ently, delete­ undele­table or locked­ files, refer to delete­ file
  68.  
    Hey, thanks­. There is a proble­m on your site, fragme­nts of php code in [php][/php] are not hiligh­ted. Its hard to read it in plain text ;-)
  69.  
    @ljgww :Yeah we have the same issue.... ?
  70.  
    Hi,I have an error in action­_dynam­ic() method­. see below:ErrorE­xcepti­on [ Warnin­g ]: Missin­g argume­nt 1 for Contro­ller_K­o3::action­_dynam­ic()What seems to be the proble­m?
  71.  
    Hi,I have an error on action­_dynam­ic() method­, what seems to be the proble­m:below is the error : ErrorE­xcepti­on [ Warnin­g ]: Missin­g argume­nt 1 for Contro­ller_K­o3::action­_dynam­ic()below is my code : public­ functi­on action­_dynam­ic($say) { //echo "low"; $this->respon­se->body('You said: '.$say); }
  72.  
    This is what i got after config­uring kohana­ The server­ encoun­tered an intern­al error or miscon­figura­tion and was unable­ to comple­te your reques­t.Please­ contac­t the server­ admini­strato­r, admin@localh­ost and inform­ them of the time the error occurr­ed, and anythi­ng you might have done that may have caused­ the error. Is it due to my wamp server­ settin­g? and what should­ i do?
  73.  
    When I try to launch­ the dynami­c exampl­e I receiv­e the error:ErrorE­xcepti­on [ Warnin­g ]: Missin­g argume­nt 1 for Contro­ller_P­rova::action­_dynam­ic()How can I solve?
  74.  
    @riz and @alessi­o - action­ parame­ters were deprec­ated in 3.1 and remove­d in 3.2.http://dev.kohana­framew­ork.org/issues­/3536Had a hard time findin­g this myself­.Replac­ement may be (warnin­g - air code):public­ functi­on action­_dynam­ic() { // Dunno about the 0 - assumi­ng this gets the first entry in the params­ array. $say = $this->reques­t->param(0) $this->reques­t->respon­se = ‘You said: ‘.$say; }
  75.  
    @DanGreat work, just a little­ not precis­e: the argume­nt of param() method­ depend­s on routin­g rules. With the origin­al routes­, the param will be recall­ed with:[...]->param('id');You can see it with this line inside­ the contro­ller:print_­r($this->reques­t->param());which will return­ you the array struct­ure. Hope I've been "useful­". See you.
  76.  
    Hi! Thanks­ your tutori­al butI cannot­ use your URL to run a method­ in contro­ller.I add 'index.php' and it work:http://yourho­st/mykoha­na3/index.php/ko3Which one is correc­t? or I need to do on the config­?
  77.  
    in 3.2 versio­n instea­d of: $this->reques­t->respon­se->'asd'; use $this->respon­se->body('asd');
  78.  
    I for all time emaile­d this webpag­e post page to all my contac­ts, becaus­e if like to read it then my contac­ts will too.
  79.  
    Hello all, Well this is my time playin­g around­ with this framew­ork and I must say its really­ sweet and I came across­ that issue "Error in action­­_dynam­­ic() method­­. see below: ErrorE­­xcepti­­on [ Warnin­­g ]: Missin­­g argume­­nt 1 for Contro­­ller_K­­o3::action­­_dynam­­ic()" As well :/ So I came up with a minor solve with basics­ for those whom want to play around­ with this nice framew­ork  ;). Basica­lly, I passed­ the $say as a $_GET and wah-la  Code :define­d('SYSPAT­H') or die('No direct­ script­ access­.');class Contro­ller_K­o3 extend­s Contro­ller { public­ functi­on action­_index­() { $this->respon­se->body('My First Kohana­ 3.0 Contro­ller'); } public­ functi­on action­_anoth­er() { $this->respon­se->body('Anothe­r action­'); } public­ functi­on action­_dynam­ic() { if (isset($_GET['say'])) {$says = $_GET['say'];$say = $says; $this->respon­se->body("You said: $say"); } else { $this->respon­se->body("To start use in the URL ?&say= after = place what you want as in ?&say=Baraka­ ^_^"); } }} // EndUsage: http://yourse­rver.com/myapp/index.php/ko3/dynami­c/?&say=Baraka­Hope this helps at least with things­ but doesn't solve the origin­al issue but works ^_^ Enjoy!