Sign In  |   Register  

Kohana PHP 2.3.x Tutorial Part II

ellisgl | May 21, 2009 | 12 Comments

Welcome to the second tutorial in this series on how to develop with Kohana PHP. If you haven’t read the first part, I would read Part 1 before going on. In this tutorial we will be going over views, wonderful views, glorious views.

Let’s just dive straight into building our first picturesque view.
Create the file “myfirstkohana/application/views/hello.php” and put the following into it:

<html>
 <head>
  <title>Hello!</title>
 </head>
 <body>
  <h1>This is my first view</h1>
  <?php echo $content;?>
 </body>
</html>

Looking at the above, it’s pretty straight forward and simple HTML file with some simple PHP code thrown in.

Just because we put a view with the same name as our controller, it’s not going to be shown until we say so. Let’s go back to our wonderful controller “myfirstkohana/application/controllers/hello.php” and edit the index method to look like the following:

public function index()
 {
  $view          = new View('hello');
  $view->content = 'Hello World!';
  $view->render(TRUE);
 }

Let go through this line by line. The first line:

$view = new View('hello');

tells the framework to create a new “view” object and load the file :myfirstkohana/application/views/hello.php” into it. The next line:

$view->content = 'Hello World!';

creates a new property called “content” in the object that has the value “Hello World!”. The last line

$view->render(TRUE);

compiles the template with our assigned values and outputs it to the screen. What we should get when we load “http://youserver/myfirstkohana/hello” is “This is my first view” and below that should read “Hello World!”.

This might the simplist view you’ll see. Of course, I don’t think we’ll be wanting something so simple, so lets knock it up notch and create views with nested views.

Create the file “myfirstkohana/application/views/default_template.php” and put this in it:

<?php echo $header; ?>
<?php echo $content; ?>
<?php echo $footer; ?>

The above code is just a master template, or the template of templates if you will. Next lets create “myfirstkohana/application/views/default_header.php” and put the following into it:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" >
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title><?php echo $pageTitle;?></title>
 </head>

and then “myfirstkohana/application/views/default_content.php”:

 <body>
  <h1>This is my second view</h1>
  <?php echo $content;?>

finally “myfirstkohana/application/views/default_footer.php”:

 </body>
</html>

Above we taken a basic HTML page and split it up “logically” into a header, footer and a content section. Let open our controller to build out our more complex view. Edit “myfirstkohana/application/controllers/hello.php” to make the index method look like this:

  public function index()
   {
    $view                    = new View('default_template');
    $view->header            = new View('default_header');
    $view->content           = new View('default_content');
    $view->footer            = new View('default_footer');
    $view->header->pageTitle = 'I am on the top';
    $view->content->content  = 'Hello World!';

    $view->render(TRUE);
   }

That wasn’t too hard was it? Basically we load our first view, which is the main template. Then we populate our properties with objects of our inner templates. It’s like working with multi-demential arrays in a sense.

With the ability to nest views/templates inside each other, things are a lot nicer to deal with. There is a problem thou. Each method (action) that needs to have a templated view, you need to do what we did to our index action to each one. Kohana does have an answer.

The Template_Controller allows to give a default view to actions, which if you have a lot of actions for a controller, it can really cut down on development and debugging time. Let go ahead and re-work out the hello controller (“myfirstkohana/application/controllers/hello.php”).

<?php
defined('SYSPATH') or die('No direct access allowed.');

class Hello_Controller extends Template_Controller
 {
    public $template    = 'default_template'; // Default template (view) to use
    public $auto_render = TRUE;               // Auto render template after controller is done

    public function __call($method, $arguments)
     {
        $this->name($method);
     }

    public function __construct()
     {
        parent::__construct(); // Has to be here!

        // Load the inner templates
        $this->template->header            = new View('default_header');
        $this->template->content           = new View('default_content');
        $this->template->footer            = new View('default_footer');
        $this->template->header->pageTitle = 'My first Kohana App';
     }

    public function index()
     {
        // Put something useful in our variables.
        $this->template->header->pageTitle .= ' ::: I am on the top';
        $this->template->content->content   = 'Hello World!';
     }

    public function america()
     {
        $this->template->content->content = 'Hello America!';
     }

    public function name($name)
     {
        $this->template->content->content = 'Hello ',$name,'!';
     }
 }

Here we have defaulted our main template, so now we didn’t have to declare it in each method. Also in our constructor method, we loaded the sub templates in and gave a default value to one of the template variable that used in the title tag. In our index method we added on to the title tag (think SEO) and put some generic content in place.

Stay tuned for the third part of our series and find out about models and working with external data!

Post a New Comment

Comments and Reviews:

  1.  
    Keep the tutori­als coming­!
  2.  
    p.s.would be nice to have one includ­ing models­ (databa­se) and how it all ties in with contro­llers and views. Thanks­.
  3.  
    The next tutori­al will be about models­ which will tie in all that stuff. =)
  4.  
    keep on going!
  5.  
    I am receiv­ing the follow­ering error when trying­ to run the exampl­e. I 've create­d alle files but it still doesn't want to work. Here is the error I receiv­ed.An error was detect­ed which preven­ted the loadin­g of this page. If this proble­m persis­ts, please­ contac­t the websit­e admini­strato­r.D:/xampp/xamppl­ite/htdocs­/vakwin­kel/applic­ation/contro­llers/checko­ut/checko­ut.php [14]:Attemp­t to assign­ proper­ty of non-object­*Checko­ut_Con­trolle­r->__cons­truct( )* system­coreKo­hana.php [235]:Reflec­tionCl­ass->newIns­tance( )*Kohana­::instan­ce( )* system­coreEv­ent.php [209]:call_u­ser_fu­nc( Array ( [0] => Kohana­ [1] => instan­ce ) )* system­coreBo­otstra­p.php [55]:Event::run( system­.execut­e )* index.php [106]:requir­e( system­coreBo­otstra­p.php )
  6.  
    Ok, I know where the error was. You wrote " 'Hello ',$name,'!' " in the name functi­on. The right thing here would be " 'Hello '.$name.'!' " . Took a while to find the error(never worked­ with a framew­ork before­ and last time i wrote php is some time ago.thnx leo
  7.  
    Ah, yes. Before­ it was an echo statem­ent and now it's not. =) I'll have to fix that.
  8.  
    There are a few mistak­es here and there, but it I'd like this series­ so far. Going do 3rd part. Why did you extend­ the Templa­te_Con­troler­ here, but not in the zip'd code? I mean, there are some errors­ for inhert­ing this class and, so far, I cannot­ unders­tand them fairly­ well. But, overal­l, keep up the work, it's relati­vely hard to find this good presen­tation­ to the framew­ork. Thanks­ a lot.
  9.  
    Cacovs­ky, I'm waitin­g for Kohana­ 3.0 to come out and start the series­ over again. Hopefu­lly the I'll have clean code then =)
  10.  
    Anothe­r great tutori­al. Thanks­!
  11.  
    good work it is very helpfu­l for me thx again :)
  12.  
    Thanks­! I've been busy with all sorts of things­, but hope to get back on the Kohana­ tutori­al by starti­ng over and using Kohona­ 3.x