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.
*AMP (Apache MySQL PHP) install
Knowledge of PHP
Know what a frame work is (Framework Article)
Know what MVC is (Wikipedia Entry)
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:
RewriteBase /kohana/
to:
RewriteBase /mykohana3/
Save it as “.htaccess”.
Now open the “bootstrap.php” file located in the “application” folder and cange the following line:
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
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
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.
defined(‘SYSPATH’) or die(‘No direct script access.’);
This line basically tells PHP not load this file directly. It can only be included from the framework.
class Controller_Ko3 extends Controller
This creates an controller which is a class that is extended from the Controller class that is part of the framework.
public function action_index()
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.
$this->request->response = ‘My First Kohana 3.0 Controller’;
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:
public function action_another()
{
$this->request->response = ‘Another action’;
}
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:
public function action_dynamic($say)
{
$this->request->response = ‘You said: ‘.$say;
}
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
Welcome to the second part in this series on how to develop with Kohana PHP V3 (KO3). If you haven’t read the first part, I would read it before going on. In this tutorial we will be going over how to develop views.
Before we get into views, we’ll want to update the KO3 code base, So point your browser to http://dev.kohanaphp.com/projects/kohana3/files, download it, open it and extract everything inside the “kohana” folder to “mykohana3″. Once you have done that, delete or rename the “install.php” in your “mykohana3″ folder. Next, open up the “bootstrap.php” file in the “application” folder and change the following line:
Now that we are updated to the latest and greatest, lets get right in to developing a view. Create a new folder within the “application” folder named “views” and inside the “views” folder, create another folder named “pages”. Now open up a new document in your editor and put the following in it:
<html>
<head>
<title>Hello!</title>
</head>
<body>
<h1>This is my first view</h1>
</body>
</html>
Now save that in your “application/views/pages” as “ko3.php”. As you can tell, it’s a pretty simple HTML page with some PHP mixed in. Lets open the “ko3″ controller (“application/classes/controller/ko3.php”). Replace the “action_index” class with the following:
public function action_index()
{
$this->request->response = View::factory(‘pages/ko3′);
}
Save it, and load up “http://yourserver/myfirstkohana3/” in your browser. You should see “This is my first view”. The code above is pretty simple, we use the “Facotry” method of the view class to load the file “application/views/pages/ko3.php”, renders it and outputs it. Not very exciting, so let go back to the view (“application/views/pages/ko3.php”) and add:
<?php echo $content;?>
After the “h1″ tags. Your view should look like this:
<html>
<head>
<title>Hello!</title>
</head>
<body>
<h1>This is my first view</h1>
<?php echo $content;?>
</body>
</html>
If we were to refresh the browser, we would seen an exception error about an undefined variable. So let’s go ahead and fix that, by relating data to the view variable in our controller. So, change up “Action_Index” controller to look like this:
public function action_index()
{
$view = View::factory(‘pages/ko3′);
$view->content = ‘We have data!’;
$this->request->response = $view->render();
}
Now if we refresh the browser, we should see “This is my first view” and under that “We have data!”. Lets explain the the code line by line.
$view = View::factory(‘pages/ko3′);
This load our view file (“application/views/pages/ko3.php”) into the view controller.
$view->content = ‘We have data!’;
This assigns a variable for use by the view called “content” and we also assign data to that, in this case it’s “We have data!”
$this->request->response = $view->render();
This renders the view and outputs it.
Simple enough, but there is another way of doing the above. We could have also done the following:
public function action_index()
{
$data['content'] = ‘We have data!’;
$view = View::factory(‘pages/ko3′, $data);
$this->request->response = $view->render();
}
Basically the above use an array with element keys as the template variable names to assign the data. We are not done yet! There’s 2 more ways we can do the above.
public function action_index()
{
$view = View::factory(‘pages/ko3′)
->set(‘content’, ‘We have data!’);
$this->request->response = $view->render();
}
The above used the set method of the view class, which you can use method chaining to set all your template variables. And now for forth way:
public function action_index()
{
$content = ‘We have data!’;
$view = View::factory(‘pages/ko3′)
->bind(‘content’, $content);
$this->request->response = $view->render();
}
Now the above is using the bind method of the view class. Once again, this you can do method chaining here. This is a little bit different from the set method, since it will create a reference to a variable. So $content might equal ‘We have data!’ when we bound the variable to the template variable, but could change later on, since we are referencing the variable $content in our controller, instead of assigning data to the template variable.
If we were to do the following:
public function action_index()
{
$content = ‘We have data!’;
$view = View::factory(‘pages/ko3′)
->bind(‘content’, $content);
$content = ‘Our data changed’;
$this->request->response = $view->render();
}
Instead of “We have data!” showing on our screen, we would have “Our data changed”.
Now lets do a view with in a view! Create a new folder in your “application/views/” named “blocks”. Lets create another view file named “ko3_inner.php” and put this in it:
<h3>This is an inner view</h3>
Save that in your “application/views/blocks/” directory. Now lets edit the “ko3″ view (“application/views/pages/ko3.php”) and add the following:
<html>
<head>
<title>Hello!</title>
</head>
<body>
<h1>This is my first view</h1>
<?php echo $content;?>
<?php echo View::factory(‘blocks/ko3_inner’)->render(); ?>
</body>
</html>
So if we run it we should see what we had before, then “This is an inner view”. This would be useful for static content, but we won’t be able to use variables directly to that view. So let fix this. Lets go back to our controller (“application/classes/controllers/ko3.php”) and edit the “Action_Index” method to look like this:
public function action_index()
{
$ko3_inner['content'] = ‘We have more data’;
$ko3['content'] = ‘We have data’;
$ko3['ko3_inner'] = View::factory(‘blocks/ko3_inner’, $ko3_inner)
->render();
$view = View::factory(‘pages/ko3′, $ko3);
$this->request->response = $view->render();
}
This will render the view to a array that then is rendered by the main view. If you noticed I did the inner stuff first and went back to using array template variable setting style. Next we will need to edit the main view (“application/views/pages/ko3.php”). The line we put in before, we will change it to:
<?php echo $ko3_inner; ?>
The view should look like this:
<html>
<head>
<title>Hello!</title>
</head>
<body>
<h1>This is my first view</h1>
<?php echo $content;?>
<?php echo $ko3_inner; ?>
</body>
</html>
And the last change we need to make is to the inner view (“application/views/blocks/ko3_inner.php”). Make it look like this:
<h3>This is an inner view</h3>
<?php echo $content;?>
If you refresh the browser after saving, you should now see the following:
This is my first view
We have data
This is an inner view
We have more data
Pretty cool, now you can make your views more modular and reusable. Now lets get into making variables globally available to your views. Back to your controller (“applications/classes/controllers/ko3.php”) and edit the “Action_Index” method so the following is at the top of the method:
View::set_global(‘x’, ‘This is a global variable’);
So now the method should look like this:
public function action_index()
{
View::set_global(‘x’, ‘This is a global variable’);
$ko3_inner['content'] = ‘We have more data’;
$ko3['content'] = ‘We have data’;
$ko3['ko3_inner'] = View::factory(‘blocks/ko3_inner’, $ko3_inner)
->render();
$view = View::factory(‘pages/ko3′, $ko3);
$this->request->response = $view->render();
}
Now if you were to edit your views and add in:
<br/><?php echo $x;?>
You should now see “This is a global variable” two times on the page. As you can see this could be very handy. Basically, we are using the static method of “set” from the view class, so it ends up being available to all view object instances. You can also use the static method of “bind” to reference variables. This could be handy for dry things “DRY” and could be used in other place, like a contruct.
Untill next time, when I go over “templates” (advanced views and controller stuff), happy coding!
Sources used: Unofficial Kohana 3 Wiki
Welcome to the third part in this series on how to develop with Kohana PHP V3 (KO3). If you haven’t read the first and/or second parts yet, I would click here and read them before going on. In this tutorial we will be going over how to create a template.
In the last tutorial, we went over views and in this one we are going to extend the Controller classes which will allow us to create a template. A template, you might ask, is nothing more than a view that is more or less your base (X)HTML code. This will allow to keep things “DRY” in the view world. Before we get to putting code into a file, lets create a new directory under “/application/views/” named “templates”. Now open up your favorite IDE and make a new file and put the following into it:
Save the above as “default.php” in your “/application/views/templates/” folder.
As you can see the above pretty much looks like a view we have done before, a bit more expanded. I will go over the “foreach” a little bit later. Unlike a view, this will most likely be used by all of your project. Since we will point to this file for our template, or shell, this will reduce the amount of code you have to put in each view, keeping thing separated, easier to maintain, or basically “DRY”.
Now that we have a template, our system isn’t going to do anything with it until well tell it to use it. So lets go back to our IDE and create a new file and put the following into it:
<?php
defined(‘SYSPATH’) or die(‘No direct script access.’);
class Controller_DefaultTemplate extends Controller_Template
{
public $template = ‘templates/default’;
/**
* Initialize properties before running the controller methods (actions),
* so they are available to our action.
*/
public function before()
{
// Run anything that need ot run before this.
parent::before();
if($this->auto_render)
{
// Initialize empty values
$this->template->title = ”;
$this->template->meta_keywords = ”;
$this->template->meta_description = ”;
$this->template->meta_copywrite = ”;
$this->template->header = ”;
$this->template->content = ”;
$this->template->footer = ”;
$this->template->styles = array();
$this->template->scripts = array();
}
}
/**
* Fill in default values for our properties before rendering the output.
*/
public function after()
{
if($this->auto_render)
{
// Define defaults
$styles = array(‘assets/css/reset.css’ => ‘screen’);
$scripts = array(‘http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js’);
// Add defaults to template variables.
$this->template->styles = array_reverse(array_merge($this->template->styles, $styles));
$this->template->scripts = array_reverse(array_merge($this->template->scripts, $scripts));
}
// Run anything that needs to run after this.
parent::after();
}
}
And save this as “defaulttemplate.php” under your “/application/classes/controller/” folder.
The above code extends the “Controller_Template” class and does three main things, initialize some properties (variables) to be accessable by our methods (actions) and appends default values to them and then gets associates them to our template variables before we render the final output to the screen. This is where the foreach() loop in the template comes into play. The foreach() loop uses a static method for the helper class “HTML” to load CSS style sheets and load JS files. Both of these helper methods will iterate through an array and properly wrap it in the appropriate tag. They can take a path or a URL.
You might be wondering what a “Helper” is, so here is a quick definition from the Kohana PHP 2.x documents:
Helpers are simply “handy” functions that help you with development.
Helpers are similar to library methods, but there is a subtle difference. With a library, you have to create an instance of the library’s class to use its methods. Helpers are declared as static methods of a class, so there is no need to instantiate the class. You can think of them as “global functions”.
As with libraries, the helper classes are automatically loaded by the framework when they are used, so there is no need to load them yourself.
OK, back on course. You might have noticed there is a reference to “assets/css/reset.css”, so lets go ahead and get that in place. In your root create a folder named “assets” and in that folder create one named “css”. For the actual “reset.css” file, I went to Serene Destiny and copied the code from the article titled “Create The Perfect CSS Reset” into a file and saved it as “reset.css” in the “assets/css/” folder. You might want to also set up some other folders within “/assets/”, maybe “images”, “js” and “files”. Basically the assets folder should be used to store and organize static files and such.
At this point, our application still doesn’t know what to do what we have done, so we need to modify our controller. So open “/application/classes/controller/ko3.php”.
We want to change what class we are extending, so change the line:
We also need to change up our “index” action (action_index() method) to look like the following:
public function action_index()
{
$ko3_inner = array();
$ko3 = array();
$this->template->title = ‘Kohana 3.0′;
View::set_global(‘x’, ‘This is a global variable’);
$ko3_inner['content'] = ‘We have more data’;
$ko3['content'] = ‘We have data’;
$ko3['ko3_inner'] = View::factory(‘blocks/ko3_inner’, $ko3_inner)
->render();
$this->template->content = View::factory(‘pages/ko3′, $ko3);
}
Save it. Now you might noticed that we now have “$this->template->title = ‘Kohana 3.0′;”, this will assign a value to our templates “title” variable. The next thing you might notice is the absence of the last “render()” method. The “factory()” method actually will “auto render” it to our template’s “content” variable. Pretty simple, yes?
There is something we should probably do before loading up the page, so load up the “ko3.php” view file located in “application/views/pages/”. You might noticed that we have all the “shell” code in our view, so lets remove it. What you should only have in the view file is this:
<h1>This is my first view</h1>
<?php echo $content;?>
<?php echo $ko3_inner; ?>
<br/><?php echo $x;?>
Now if you load it up, you should see that page has a title of “Kohana 3.0″ and the page should pretty much look the same as it did from the last tutorial. If you view the source thou, it would look much different. But you might be wondering about the other variables in the template and what to do with them. OK, let go back and edit our “index” action again. Make it look like:
public function action_index()
{
$ko3_inner = array();
$ko3 = array();
$this->template->title = ‘Kohana 3.0′;
$this->template->meta_keywords = ‘PHP, Kohana, KO3, Framework’;
$this->template->meta_description = ‘A test of of the KO3 framework’;
$this->template->styles = array(‘assets/css/red.css’ => ‘screen’);
$this->template->scripts = array(‘assets/js/jqtest.js’);
View::set_global(‘x’, ‘This is a global variable’);
$ko3_inner['content'] = ‘We have more data’;
$ko3['content'] = ‘We have data’;
$ko3['ko3_inner'] = View::factory(‘blocks/ko3_inner’, $ko3_inner)
->render();
$this->template->content = View::factory(‘pages/ko3′, $ko3);
}
Pretty simple. You will notice I didn’t fill in the header or footer. I’m sure you know what to do there. Hint: Render a view to that variable =). Another thing you might notice is that I have put in “assets/css/red.css” and “assets/css/jqtest.js”. Lets make those two files starting with “/assets/css/red.css”:
Save them and refresh the site. You should see an alert pop up and the first line of text in red.
Today we have created a template file, extended a template controller and our controller use that template file. There is a lot of potential with what you could do with this already. So until next time when I will go over models, happy coding!
Sources used: Unofficial Kohana 3 Wiki, Kohana PHP 2.x Docs
Welcome to the fourth part in this series on how to develop with Kohana PHP V3 (KO3). If you haven’t read any of previous parts yet, I would search for and read them before going on. In this tutorial we will be going over how work with models.
So you might be asking your self, what is a model. From Kohana’s 2.x documents:
Models are classes designed to work with information given by or asked for by the controller. For example, you have a guestbook, the controller will ask the model to retrieve the last ten entries, the model returns those entries to the controller who passes them on to a view. The controller might also send new entries to the model, update existing ones or even delete some.
Simply a model is a data handler and manipulator.
The first thing we want to do is identify where and what the data is. Is it an XML feed, CSV, JSON, DB or something else? Well I’m going to make it easy. We are going to deal with our friend MySQL for this. The next step is to setup a MySQL DB connection.
Lets open up your bootstrap file (“application/bootstrap.php”) and find the like that reads “// ‘database’ => MODPATH.’database’, // Database access” and uncomment it. The whole block of code should look like the following:
Now save this. We’ve basically told the bootstrap to load the database module, but we need to configure it. Copy the “database.php” from “modules/database/config/” to “application/config/”. Open up the “application/config/database.php” file and edit accordingly to your settings. Mine looks like this:
Save this. You’ll notice I have a database setup just this tutorial series named “mykohana3″, you might want to do the same if you can. Now that we have saved, let get a table set up. Here’s the SQL:
Go run that in your favorite MySQL client, I personally like SQLYog. You might have noticed the “charset” is set to “utf8″ in both the config and create table statement. This will allow us to deal with i18n (Internationalization) stuff later on.
So let create a new folder under “application/classes” named “model”. Now lets create a new file and make it look like this:
<?php
defined(‘SYSPATH’) or die(‘No direct script access.’);
class Model_Post extends Kohana_Model
{
/**
* Get the last 10 posts
* @return ARRAY
*/
public function getLastTenPosts()
{
$sql = ‘SELECT *’.”n”.
‘FROM `posts`’.”n”.
‘ORDER BY `id` DESC’.”n”.
‘LIMIT 0, 10′;
return $this->_db->query(Database::SELECT, $sql, FALSE)
->as_array();
}
}
Save this as “post.php” under “application/classes/model/”. Here’s an line by line explaination of the code.
This return array of the result from a query. The “query” method in this example take 3 parameters. 1st being what type of query, our being select, we use the constant “Database::SELECT”. There are 3 others, “Database::INSERT”, “Database::UPDATE” and “Database::DELETE”. The “as_array()” will return an array of the results, no having to do “while($row = mysql_fetch_array())”.
Now that we have a model method, I’m sure we would want to put it use. Open up “ko3.php” in “/application/classes/controller” and lets add this into the class:
public function action_posts()
{
$posts = new Model_Post();
$ko3 = array();
$this->template->title = ‘Kohana 3.0 Model Test’;
$this->template->meta_keywords = ‘PHP, Kohana, KO3, Framework, Model’;
$this->template->meta_description = ‘A test of of the KO3 framework Model’;
$this->template->styles = array();
$this->template->scripts = array();
// Get the last 10 posts
$ko3['posts'] = $posts->getLastTenPosts();
$this->template->content = View::factory(‘pages/posts’, $ko3);
}
Basically we’ve called our model’s “getLastTenPosts()” method and assigned it to an array which we pass to our view. Talking about views, open up a new file and put the following into it:
Save to as “posts.php” under “application/views/pages/”. This view loops through the array we pass to it from the the controller and displays our posts from the DB. Wait, what? There’s no posts in our DB! Here’s some SQL you can run to populate your table:
insert into `posts`(`id`,`title`,`post`) values (1,’Test Post’,'This is some sample text.’);
insert into `posts`(`id`,`title`,`post`) values (2,’Another post’,'Some more text’);
Now if you point your browser to “http://yourserver/mykohana3/ko3/posts” you should see the two entries on the screen.
Now lets add something to put data into our DB. Open the the post model (“application/classes/model/post.php”) and add this to the class:
public function addPost($title, $post)
{
$sql = sprintf(‘INSERT INTO `posts`’.”n”.
‘SET `title` = %s,’.”n”.
‘ `post` = %s’,
$this->_db->escape($title),
$this->_db->escape($post));
$this->_db->query(Database::INSERT, $sql, FALSE);
}
The above is a pretty simple insert, but you may notice we are using “$this->_db>escape()”. This will wrap your strings in quotes and escape it content for you. Save it and now go back to the “posts.php” from “application/views/pages” and replace the contents with:
Save that and open the ko3 controller back up (“application/classes/controller/ko3.php”) and lets add a new method to it.
private function _addPost($title, $post_content)
{
// Load model
$post = new Model_Post();
// Check required fields
if(empty($title))
{
return(array(‘error’ => ‘Please enter a title.’));
}
elseif(empty($post_content))
{
return(array(‘error’ => ‘Please enter a post.’));
}
// Add to DB
$post->addPost($title, $post_content);
return TRUE;
}
The above code is pretty much a middle man between the “action_posts” and the model that saves the post it self. Lets go back to the “action_posts” method and make it look like this:
public function action_posts()
{
// Load model
$posts = new Model_Post();
// Setup view stuff
$ko3 = array();
$this->template->title = ‘Kohana 3.0 Model Test’;
$this->template->meta_keywords = ‘PHP, Kohana, KO3, Framework, Model’;
$this->template->meta_description = ‘A test of of the KO3 framework Model’;
$this->template->styles = array();
$this->template->scripts = array();
$ko3['msg'] = “”;
// Handle POST
if($_POST)
{
$ret = $this->_addPost((isset($_POST['title']) ? $_POST['title'] : “”),
(isset($_POST['post']) ? $_POST['post'] : “”));
if(isset($ret['error']))
{
$ko3['msg'] = $ret['error'];
}
else
{
$ko3['msg'] = ‘Saved.’;
}
}
// Get the last 10 posts
$ko3['posts'] = $posts->getLastTenPosts();
// Display it.
$this->template->content = View::factory(‘pages/posts’, $ko3);
}
Save this and reload your browser. Now you should see a pretty ugly form at bottom. Enter some stuff in and click the “submit” button. Your post should appear at the top along with the word “Saved”, this is if you entered stuff in both fields, if not you should see an error.
Before I end this tutorial, I want to go back to our little model for saving our posts. There are several ways to do queries in KO3, but want to quickly show you how you can use the query builder to do the same thing.
public function addPost($title, $post)
{
DB::insert(‘posts’, array(‘title’,'post’))
->values(array($title, $post))
->execute();
}
That’s pretty simple! It does the same thing as the previous one, with less “hassle” There are advantages using the query builder method, like being able to convert between different DB types (MySQL to Oracle to what ever).
While I might not have gone over doing updates with your model, I thought I would give you a homework assignment to see if you can come up with you own update model for this. Until next time when we go over “H” in “HMVC”, happy coding.
Welcome to the fifth part in this series on how to develop with Kohana PHP V3 (KO3). If you haven’t read any of previous parts yet, I would search for and read them before going on. In this tutorial we will be going over the “H” in HMVC.
So most of you know what MVC is, but might not know about HMVC. HMVC extends MVC by allowing a controller to call on other controllers on do stuff, or doing stuff in an Hierarchical manor. Think modules that can work by themselves or in a groups. If that didn’t help, check out this article about the Hierarchical-Model-View-Controller pattern.
So we’ve been design pages with a single controller as a page, with some actions that pulls data in from a model and populates a parts of a view to give us a complete browser page. Well, that can get messy with all the model calls and extra snippets we bring into with views. Using HMVC, we can organize our code a lot better, make more things reusable and with the way Kohana PHP 3 does HMVC, we can even make our application scale by calling out to other servers to give us our content for a section.
Lets go ahead and make a new controller:
<?php
defined(‘SYSPATH’) or die(‘No direct script access.’);
class Controller_Hmvc extends Controller_DefaultTemplate
{
public function action_index()
{
// Set meta data
$this->template->title = ‘Kohana 3.0 HMVC Test’;
$this->template->meta_keywords = ‘PHP, Kohana, KO3, Framework, HMVC’;
$this->template->meta_description = ‘A test of of the KO3 framework HMVC pattern’;
// Fill in content
$ko3 = array();
$ko3['posts'] = Request::factory(‘posts/getposts’)->execute()->response;
$this->template->content = View::factory(‘pages/hmvc’, $ko3);
}
}
Save this as “hmvc.php” in “application/classes/controller”. The above should look pretty familiar. One line should stand out:
This line is where the HMVC magic happen. This will call the controller “posts” an invoke the action “getposts”, execute the code and get the response. We take the response and save it to the array which we fill the view with.
Talking about views, let make our view for this controller:
<?php echo $posts;?>
Save this as “hmvc.php” in “application/views/pages/”
Now for the “posts” controller:
<?php
defined(‘SYSPATH’) or die(‘No direct script access.’);
class Controller_Posts extends Controller
{
public function action_index()
{
}
public function action_getposts()
{
// Load model
$posts = new Model_Post();
// Fill content array for view with last 10 posts.
$content = array();
$content['posts'] = $posts->getLastTenPosts();
// Render and output.
$this->request->response = View::factory(‘pages/hmvc_posts’, $content);
}
}
Save this as “posts.php” in “application/classes/controller”. Once again, pretty straight forward. This controller extends the basic controller, so nifty template or anything and is pretty much what we did in the last tutorial.
Save this as “hmvc_posts.php” under “applications/views/pages”.
Now if you point your browser to: “http://yourserver/mykohana3/hmvc”, you should see a couple posts up on the screen.
We can achieve the same result by calling the controller from the view instead of the controller. This is helpful for keeping it simple. So one template used all over the place, you wouldn’t have to worry about having to putting in all the HMVC stuff into the controllers that used that template.
Change the “hmvc” controller to look like this:
<?php
defined(‘SYSPATH’) or die(‘No direct script access.’);
class Controller_Hmvc extends Controller_DefaultTemplate
{
public function action_index()
{
// Set meta data
$this->template->title = ‘Kohana 3.0 HMVC Test’;
$this->template->meta_keywords = ‘PHP, Kohana, KO3, Framework, HMVC’;
$this->template->meta_description = ‘A test of of the KO3 framework HMVC pattern’;
// Fill in content
$ko3 = array();
$ko3['content'] = ‘Hello there!’;
$this->template->content = View::factory(‘pages/hmvc’, $ko3);
}
}
This is example is pretty simple and we could expand this to use parameters to deliver the data in different ways, say, simple html, full html, xml, json, etc..
Sources used: Unofficial Kohana 3 Wiki, iBuildings: Scaling Web Applications with HMVC
Welcome to the sixth part in this series on how to develop with Kohana PHP V3 (KO3). If you haven’t read any of previous parts yet, I would search for and read them before going on. In this tutorial we will be going over Routes and Routing.
What is Routing? Well Routing is nothing more than taking a request, looking at it and directing it to the right place. Think of it Kohana’s version of the .htaccess file. So why would you want to use routing you might ask. Well there are so many reasons why you would want to use routing, so I’m not going to over all of them, but give you a couple examples of how to setup routes for different scenarios.
So what does a route look like? Open up “bootstrap.php” located in “application/”, and scroll down to the comment that says:
/**
* Set the routes. Each route must have a minimum of a name, a URI and a set of
* defaults for the URI.
*/
The next thing you should see is something like this:
So we have a route setup initially for us, but what does this tell us. If we break it down we get:
1. Set a route with the name “default”
2. ‘((/(/)))’ Tells the route the controller, action and id are optional. The parentheses are containers that denote if an option is opional or not and the less / greater than symbols tell the the router to assign the value to the variable of the value in-between the less / greater than symbols.
3. The default values for the controller is “welcome” and the default value for the action is “index”
So when we go to “http://yourserver/mykohana3/”, the router see that we have not set a controller nor an action in our URL. It will go through the route rules that we have set to find a match. In our case, we have a default route, which is named “default”. This default route will replace the missing controller with “welcome” and the action with “index” and the rest of the system will process it. Simple so far?
If we were to to “http://yourserver/mykohana3/hmvc/”, the router would notice that the controller has been set, but not the action. The router then assign the default action value of “index” for us.
You might have noticed the optional “id” in the route. This I would say is pretty commonly used and we could pass an ID on to our action. Example:
“http://yourserver/mykohana3/hmvc/index/111″. Of course this example will not do anything special since we didn’t set up any logic to handle it. Now what if we browsed to “http://yourserver/mykohana3/hmvc/index/111/222″? We get an error. This is because our router rule is strict and says we can only route for upwards of 3 segments (action/controller/id) and the /222 creates a fourth. To over come this we can though in a overflow handler rule into our default route.
If you save the ‘bootstrap.php’ file and reload, you should not see an error now.
You might notice that we’ve added in an extra array “array(‘overflow’ => ‘.*?’)”. This basically sets up a REGEX rules for the “overflow” option which tell the router to capture everything, including slashes and pass it as our “overflow” argument. So if slashes are captured, the router will no longer try to split out the options on slashes.
Lets go back to this “id” option we see in our route. Well, anything we put in that area will be passed to our action. If our id’s are integers, we might want to error out if we pass a non integer. One way we can do this is with the route:
So now if you were go to: “http://yourserver/mykohana3/hmvc/index/xxx”, you would get an error about not being able to find the route, which should translate to a 404 in a production environment. Of course you could check the id for an integer inside the action action and decide how to handle it.
Now lets create a route that isn’t our default route. Add the following to the “bootstrap.php” before the default route:
Now if you were open up “http://yourserver/mykohana3/monkeys”, you would end up with the “posts” action of the “ko3″ controller. If you notice, the “monkeys” in the controller spot is not enclosed by parentheses, meaning that is not optional. So the router see “monkeys” in the controller spot and triggers this rule set.
Here’s an example you might want to use to serve up some static pages (Totally stole this from the Unofficial Kohana 3.0 Wiki):
Welcome to the seventh part in this series on how to develop with Kohana PHP V3 (KO3). If you haven’t read any of previous parts yet, . In this tutorial we will be going over helpers.
So what is a helper? The Kohana 2.0 documents defines helpers as:
Helpers are simply “handy” functions that help you with development.
Helpers are similar to library methods, but there is a subtle difference. With a library, you have to create an instance of the library’s class to use its methods. Helpers are declared as static methods of a class, so there is no need to instantiate the class. You can think of them as “global functions”.
As with libraries, the helper classes are automatically loaded by the framework when they are used, so there is no need to load them yourself.
So pretty much they are static methods that “help” with doing common things, IE: working with arrays or URLs. Kohana comes with quite a few “helpers” prepackaged. See the KO3 API Guide.
So how do we make a “helper”? Fire up your IDE and let get coding. The first thing we should is create a new directory called “helper” under “/application/classes”. Create a new file and put the following into it:
<?php
class Helper_MyUrl
{
public static function SEOIt($str)
{
$str = preg_replace(array(‘/s/’, ‘/[$.+!*'(),"]/’), array(‘-’, “”), $str);
return $str;
}
}
Save to this as “myurl.php” under “/application/classes/helper”. Now open “/application/views/pages/ko3.php” and add the following to the bottom and save it.:
<br /><?php echo Helper_MyUrl::SEOIt(‘This Is a string!!!’);?>
So if you point your browser to “http://yourserver/mykohana3/ko3/”, you should see “ThisIsastring” at the bottom. Pretty simple!
Until next time, when I go over modules, happy coding.
Welcome to the eighth part in this series on how to develop with Kohana PHP V3 (KO3). If you haven’t read any of previous parts yet, I would search for and read them before going on. In this tutorial we will be going over modules.
Before we get into views, we’ll want to update the KO3 code base. Go in to “application” directory and rename your “bootstrap.php” to “bootstrap.bak.php”. Now point your browser to http://kohanaframework.org/download (Yes there is a new site), download the latest stable (3.0.4.2), open it and extract everything inside the “kohana” folder to “mykohana3″. Once you have done that, delete or rename the “install.php” in your “mykohana3″ folder. Next, delete the “bootstrap.php” file in the “application” folder and rename the “bootstrap.bak.php” to “bootstrap.php”.
So what is a module? A module is pretty much just a plug in. It can extend the core, give you whole new section to your project (IE. blogs and forums), or just give you a set of classes that are available globally. So lets jump right in!
Add a new directory to the “modules” directory and name it “fortune”. In the “module/fortune” directory add the following directories “classes” and “views”. In “/module/fortune/classes” create a folder named “kohana”. In “/module/fortune/views” create a folder named “fortune”. So you should have a directory that looks something like this:
Create a new file in “/module/fortune/classes/” named “fortune.php” and put the following into it:
<?php
defined(‘SYSPATH’) or die(‘No direct script access.’);
class Fortune extends Kohana_Fortune{}
This is pretty simple. Just extends another class. If you’ve gone through the code base for KO3, this will probably look familiar. Now lets create the main class file, so open a new file and put the following into it:
<?php
defined(‘SYSPATH’) or die(‘No direct script access.’);
/**
* Fortune Cookie Module
*/
class Kohana_Fortune
{
// Merged configuration settings
protected $config = array(‘view’ => ‘fortune/default’);
protected $fortune = "";
/**
* Creates a new Fortune object.
*
* @return Forune
*/
public static function factory(array $config = array())
{
return new Fortune($config);
}
public function __construct(array $config = array())
{
// Overwrite system defaults with application defaults
$this->config = $this->config_group() + $this->config;
}
/**
* Retrieves a fortune config group from the config file. One config group can
* refer to another as its parent, which will be recursively loaded.
*
* @param STRING fortune config group; "default" if none given
* @return ARRAY config settings
*/
public function config_group($group = ‘default’)
{
// Load the fortune config file
$config_file = Kohana::config(‘fortune’);
// Initialize the $config array
$config = array(‘group’ => (string)$group);
// Recursively load requested config groups
while(isset($config['group']) && isset($config_file->$config['group']))
{
// Temporarily store config group name
$group = $config['group'];
unset($config['group']);
// Add config group values, not overwriting existing keys
$config += $config_file->$group;
}
// Get rid of possible stray config group names
unset($config['group']);
// Return the merged config group settings
return $config;
}
/**
* Randomly pick a fortune
*
* @return STRING fortune text
*/
public function getFortune()
{
// Stolen from: http://fortunes.cat-v.org/plan_9/
$fortunes = array(’2 is always smaller than 3, even for large values of 2.’,
‘A penny saved is a political breakthrough.’,
‘Avoid reality at all costs.’,
‘Bad taste is timeless.’);
$this->fortune = $fortunes[array_rand($fortunes, 1)];
}
/**
* Renders the fortune.
*
* @param MIXED string of the view to use, or a Kohana_View object
* @return STRING fortune output (HTML)
*/
public function render($view = NULL)
{
if($view === NULL)
{
// Use the view from config
$view = $this->config['view'];
}
if(!$view instanceof Kohana_View)
{
// Load the view file
$view = View::factory($view);
}
$this->getFortune();
// Pass on the whole Fortune object
return $view->set(get_object_vars($this))->set(‘page’, $this)->render();
}
/**
* Renders the fortune.
*
* @return STRING fortune output (HTML)
*/
public function __toString()
{
return $this->render();
}
}
Save this as “fortune.php” in “/modules/fortune/classes/kohana”. For the most part this looks like a simple Kohana core. We have 2 protected properties, config and fortune. The config property is for, well, a configuration. We only use the view configuration value here. The fortune property is hopefully the land that my house sits on… er… It is used to store a single fortune for our output.
Next we have our factory method so we can do the factory pattern. Then we have our constructor which pulls in a configuration from the config variable and recreates the config property with default configurations from a file, set array element and from what has been passed to it with the help of the next method called “config_group”.
The heart of this class is the getFortune method. I cheated here and used an array instead of creating a model and pulling stuff from the db. So I pull a random element and place it in our fortune property. Next up is the render method. This just runs the getFortune method and then renders the view. The last one, __toString calls the render method.
Save this as “default.php” under “/modules/fortune/views/fortune/default.php”. Pretty simple. You might notice that I’m echoing out $fortune, which happens to the protected property in our class. In the render method, we pass all the properties to the view. Makes things simple.
Next up is to edit a couple files. Open up the “/application/bootstrap.php” file and locate the section with “Kohana::modules” in it. Now replace that with:
We’ve added the new fortune module and enabled it in our system here. Now open the the “/application/views/pages/ko3.php” file and add the following to the bottom of it.
<?php echo Fortune::factory();?>
Now if you point your browser to “http://yourserver/mykohana3/ko3/” you should see the fortune at the bottom!
Until next time, when I go over including external libraries, happy coding.
Welcome to the ninth part in this series on how to develop with Kohana PHP V3 (KO3). If you haven’t read any of previous parts yet, I would search for and read them before going on. In this tutorial we will be going over using other frameworks’ libraries.
Before we get into loading external libraries, we’ll want to update the KO3 code base. Go in to “application” directory and rename your “bootstrap.php” to “bootstrap.bak.php”. Now point your browser to http://kohanaframework.org/download and download the latest stable (3.0.5), open it and extract everything inside the “kohana” folder to “mykohana3″. Once you have done that, delete or rename the “install.php” in your “mykohana3″ folder. Next, delete the “bootstrap.php” file in the “application” folder and rename the “bootstrap.bak.php” to “bootstrap.php”.
The first thing we need to do is create a folder named “vendors” under “application”. In the “vendors” folder, create another folder named “Zend” (yes, with a capital “Z”). Next we’ll need to download the latest version of Zend Framework, so click here to download 1.10.5. Open the archive up and extract everything from “ZendFramework-1.10.5-minimal/library/Zend/” into “application/vendors/Zend”.
Open the “application/bootstrap.php” file and add the following above the line which reads “echo Request::getInstance()”: