A base controller using Kohana v3.0.3

Here’s how I created a base controller for websites I develop using Kohana v3

1. create a website config file ( application/config/website.php ):

<?php defined('SYSPATH') OR die('No Direct Script Access');
return array( 'site_name' => 'Example site',);
<?php defined('SYSPATH') OR die('No Direct Script Access');
return array(
      'site_name'  => 'Example site',
);

2. Create a basic CSS file for your site ( html/template/default/css/style.css ):

body {
      font-size: 14px;
}

3. Create the website controller ( application/classes/controller/website.php ):

<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Website extends Controller_Template {
      public $template  = '';
      public $page_title  = '';
      public $site_name  = '';
      public $template_name  = '';
      public $styles  = array();
      public $scripts  = array();
      public function before()
      {
            $this->auto_render = false;
            parent::before();
            $this->auto_render = true;
            $this->template_name = 'default';
            $this->site_name = kohana::config('website.site_name');
            $this->styles = array(
            'template/' . $this->template_name . '/css/style.css' => 'screen',
      );
      $this->scripts = array(
            'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',
      );
      $this->template = View::factory('template/' . $this->template_name . '/default');
      if ($this->auto_render)
      {
            $this->template->bind('page_title', $this->page_title)
            ->bind('site_name', $this->site_name)
            ->bind('styles', $this->styles)
            ->bind('scripts', $this->scripts)
      ;
      }
      }
      public function action_index()
  {
  //$this->request->response = 'hello, world!';
  $this->template->content= '<!--Default website controller, you don't want to access this one-->';
  }
  public function after()
  {
  $this->template->bind('styles', $this->styles)
  ->bind('scripts', $this->scripts)
  ;
  parent::after();
  }
} // End Website

4. Create the template file ( application/views/template/default/default.php ):

<html>
  <head>
  <meta charset="utf-8" />
  <title><?php echo empty($page_name) ? '' : "$page_name - "; ?><?php echo empty($site_title) ? '' : $site_name; ?></title>
  <?php foreach ($styles as $file => $type) echo HTML::style($file, array('media' => $type)) . "n"; ?>
  <?php foreach ($scripts as $file) echo HTML::script($file) . "n"; ?>
  </head>
<body>
  <?php echo empty($content) ? '' : $content; ?>
</body>
</html>
Bookmark the permalink.

Leave a Reply