<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Inside DealTaker &#187; PHP</title>
	<atom:link href="http://www.dealtaker.com/blog/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dealtaker.com/blog</link>
	<description>All Things Deal Oriented</description>
	<lastBuildDate>Thu, 18 Mar 2010 17:09:10 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Kohana PHP 3.0 (KO3) Tutorial Part 6</title>
		<link>http://www.dealtaker.com/blog/2010/03/03/kohana-php-3-0-ko3-tutorial-part-6/</link>
		<comments>http://www.dealtaker.com/blog/2010/03/03/kohana-php-3-0-ko3-tutorial-part-6/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 22:02:12 +0000</pubDate>
		<dc:creator>ellisgl</dc:creator>
				<category><![CDATA[technology]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[KO3]]></category>
		<category><![CDATA[kohana]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[routes]]></category>
		<category><![CDATA[routing]]></category>

		<guid isPermaLink="false">http://www.dealtaker.com/blog/?p=2037</guid>
		<description><![CDATA[Welcome to the sixth part in this series on how to develop with Kohana PHP V3 (KO3). If you haven&#8217;t read any of previous parts yet, I would click here 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 [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to the sixth part in this series on how to develop with Kohana PHP V3 (KO3). If you haven&#8217;t read any of previous parts yet, <a href="../tag/ko3/">I would click here and read them before going on</a>. In this tutorial we will be going over Routes and Routing.<br />
<span id="more-2037"></span><br />
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&#8217;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&#8217;m not going to over all of them, but give you a couple examples of how to setup routes for different scenarios.</p>
<p>So what does a route look like? Open up &#8220;bootstrap.php&#8221; located in &#8220;application/&#8221;, and scroll down to the comment that says:</p>
<pre>/**
 * Set the routes. Each route must have a minimum of a name, a URI and a set of
 * defaults for the URI.
 */</pre>
<p>The next thing you should see is something like this:</p>
<pre>Route::set('default', '(&lt;controller&gt;(/&lt;action&gt;(/&lt;id&gt;)))')
     -&gt;defaults(array('controller' =&gt; 'welcome',
                      'action'     =&gt; 'index'));</pre>
<p>So we have a route setup initially for us, but what does this tell us. If we break it down we get:<br />
1. Set a route with the name &#8220;default&#8221;<br />
2. &#8216;(&lt;controller&gt;(/&lt;action&gt;(/&lt;id&gt;)))&#8217;  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.<br />
3. The default values for the controller is &#8220;welcome&#8221; and the default value for the action is &#8220;index&#8221;</p>
<p>So when we go to &#8220;http://yourserver/mykohana3/&#8221;, 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 &#8220;default&#8221;. This default route will replace the missing controller with &#8220;welcome&#8221; and the action with &#8220;index&#8221; and the rest of the system will process it. Simple so far?</p>
<p>If we were to to &#8220;http://yourserver/mykohana3/hmvc/&#8221;, the router would notice that the controller has been set, but not the action. The router then assign the default action value of &#8220;index&#8221; for us.</p>
<p>You might have noticed the optional &#8220;id&#8221; in the route. This I would say is pretty commonly used and we could pass an ID on to our action. Example:<br />
&#8220;http://yourserver/mykohana3/hmvc/index/111&#8243;. Of course this example will not do anything special since we didn&#8217;t set up any logic to handle it. Now what if we browsed to &#8220;http://yourserver/mykohana3/hmvc/index/111/222&#8243;? 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.</p>
<pre>Route::set('default', '(&lt;controller&gt;(/&lt;action&gt;(/&lt;id&gt;(/&lt;overflow&gt;))))', array('overflow' =&gt; '.*?'))
     -&gt;defaults(array('controller' =&gt; 'welcome',
                      'action'     =&gt; 'index'));</pre>
<p>If you save the &#8216;bootstrap.php&#8217; file and reload, you should not see an error now.</p>
<p>You might notice that we&#8217;ve added in an extra array &#8220;array(&#8217;overflow&#8217; =&gt; &#8216;.*?&#8217;)&#8221;. This basically sets up a REGEX rules for the &#8220;overflow&#8221; option which tell the router to capture everything, including slashes and pass it as our &#8220;overflow&#8221; argument. So if slashes are captured, the router will no longer try to split out the options on slashes.</p>
<p>Lets go back to this &#8220;id&#8221; option we see in our route. Well, anything we put in that area will be passed to our action. If our id&#8217;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:</p>
<pre>Route::set('default', '(&lt;controller&gt;(/&lt;action&gt;(/&lt;id&gt;(/&lt;overflow&gt;))))', array('id' =&gt; '[[:digit:]]{1,}', 'overflow' =&gt; '.*?'))
     -&gt;defaults(array('controller' =&gt; 'welcome',
                      'action'     =&gt; 'index'));</pre>
<p>So now if you were go to: &#8220;http://yourserver/mykohana3/hmvc/index/xxx&#8221;, 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.</p>
<p>Now lets create a route that isn&#8217;t our default route. Add the following to the &#8220;bootstrap.php&#8221; before the default route:</p>
<pre>Route::set('monkeys', 'monkeys(/&lt;action&gt;(/&lt;id&gt;))')
     -&gt;defaults(array('controller' =&gt; 'ko3',
                      'action'     =&gt; 'posts'));</pre>
<p>Now if you were open up &#8220;http://yourserver/mykohana3/monkeys&#8221;, you would end up with the &#8220;posts&#8221; action of the &#8220;ko3&#8243; controller. If you notice, the &#8220;monkeys&#8221; in the controller spot is not enclosed by parentheses, meaning that is not optional. So the router see &#8220;monkeys&#8221; in the controller spot and triggers this rule set.</p>
<p>Here&#8217;s an example you might want to use to serve up some static pages (Totally stole this from the <a href="http://kerkness.ca/wiki/doku.php?id=routing:routing_basics" target="_blank">Unofficial Kohana 3.0 Wiki</a>):</p>
<pre>Route::set('static', '&lt;page&gt;', array('page' =&gt; 'about|faq|locations'))
	   -&gt;defaults(array('controller' =&gt; 'page',
                      'action'     =&gt; 'static'));</pre>
<p>There is a bit more you could do with routes, but the above should cover the majority of things you would want to use route for.</p>
<p>Until next time when we will go over modules and helpers, happy coding.<br />
Sources used: <a href="http://kerkness.ca/wiki/doku.php" target="_blank">Unofficial Kohana 3 Wiki</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dealtaker.com/blog/2010/03/03/kohana-php-3-0-ko3-tutorial-part-6/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Kohana PHP 3.0 (KO3) Tutorial Part 5</title>
		<link>http://www.dealtaker.com/blog/2010/02/25/kohana-php-3-0-ko3-tutorial-part-5/</link>
		<comments>http://www.dealtaker.com/blog/2010/02/25/kohana-php-3-0-ko3-tutorial-part-5/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 22:44:23 +0000</pubDate>
		<dc:creator>ellisgl</dc:creator>
				<category><![CDATA[technology]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[HMVC]]></category>
		<category><![CDATA[KO3]]></category>
		<category><![CDATA[kohana]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.dealtaker.com/blog/?p=1991</guid>
		<description><![CDATA[Welcome to the fifth part in this series on how to develop with Kohana PHP V3 (KO3). If you haven&#8217;t read any of previous parts yet, I would click here and read them before going on. In this tutorial we will be going over the &#8220;H&#8221; in HMVC.

So most of you know what MVC is, [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to the fifth part in this series on how to develop with Kohana PHP V3 (KO3). If you haven&#8217;t read any of previous parts yet, <a href="../tag/ko3/">I would click here and read them before going on</a>. In this tutorial we will be going over the &#8220;H&#8221; in HMVC.<br />
<span id="more-1991"></span><br />
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&#8217;t help, <a href="http://techportal.ibuildings.com/2010/02/22/scaling-web-applications-with-hmvc/">check out this article about the Hierarchical-Model-View-Controller pattern</a>.</p>
<p>So we&#8217;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.</p>
<p>Lets go ahead and make a new controller:</p>
<pre>&lt;?php
defined('SYSPATH') or die('No direct script access.');

class Controller_Hmvc extends Controller_DefaultTemplate
 {
    public function action_index()
     {
        // Set meta data
        $this-&gt;template-&gt;title            = 'Kohana 3.0 HMVC Test';
        $this-&gt;template-&gt;meta_keywords    = 'PHP, Kohana, KO3, Framework, HMVC';
        $this-&gt;template-&gt;meta_description = 'A test of of the KO3 framework HMVC pattern';

        // Fill in content
        $ko3                              = array();
        $ko3['posts']                     = Request::factory('posts/getposts')-&gt;execute()-&gt;response;

        $this-&gt;template-&gt;content          = View::factory('pages/hmvc', $ko3);
     }

 }</pre>
<p>Save this as &#8220;hmvc.php&#8221; in &#8220;application/classes/controller&#8221;. The above should look pretty familiar. One line should stand out:</p>
<pre>$ko3['posts'] = Request::factory('posts/getposts')-&gt;execute()-&gt;response;</pre>
<p>This line is where the HMVC magic happen. This will call the controller &#8220;posts&#8221; an invoke the action &#8220;getposts&#8221;, execute the code and get the response. We take the response and save it to the array which we fill the view with.</p>
<p>Talking about views, let make our view for this controller:</p>
<pre>&lt;?php echo $posts;?&gt;</pre>
<p>Save this as &#8220;hmvc.php&#8221; in &#8220;application/views/pages/&#8221;</p>
<p>Now for the &#8220;posts&#8221; controller:</p>
<pre>&lt;?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-&gt;getLastTenPosts();

        // Render and output.
        $this-&gt;request-&gt;response   = View::factory('pages/hmvc_posts', $content);
     }
 }</pre>
<p>Save this as &#8220;posts.php&#8221; in &#8220;application/classes/controller&#8221;. 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.</p>
<p>Now for the view.</p>
<pre>&lt;?php foreach($posts as $post):?&gt;
 &lt;h1&gt;&lt;?php echo $post['title'];?&gt;&lt;/h1&gt;
 &lt;?php echo $post['post'];?&gt;
 &lt;hr /&gt;
&lt;?php endforeach;?&gt;</pre>
<p>Save this as &#8220;hmvc_posts.php&#8221; under &#8220;applications/views/pages&#8221;.</p>
<p>Now if you point your browser to: &#8220;http://yourserver/mykohana3/hmvc&#8221;, you should see a couple posts up on the screen.</p>
<p>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&#8217;t have to worry about having to putting in all the HMVC stuff into the controllers that used that template.</p>
<p>Change the &#8220;hmvc&#8221; controller to look like this:</p>
<pre>&lt;?php
defined('SYSPATH') or die('No direct script access.');

class Controller_Hmvc extends Controller_DefaultTemplate
 {
    public function action_index()
     {
        // Set meta data
        $this-&gt;template-&gt;title            = 'Kohana 3.0 HMVC Test';
        $this-&gt;template-&gt;meta_keywords    = 'PHP, Kohana, KO3, Framework, HMVC';
        $this-&gt;template-&gt;meta_description = 'A test of of the KO3 framework HMVC pattern';

        // Fill in content
        $ko3                              = array();
        $ko3['content']                   = 'Hello there!';
         $this-&gt;template-&gt;content          = View::factory('pages/hmvc', $ko3);
     }
 }</pre>
<p>Now edit the &#8220;hmvc&#8221; view to look like this:</p>
<pre>&lt;?php echo $content;?&gt;&lt;br/&gt;
&lt;?php echo Request::factory('posts/getposts')-&gt;execute()-&gt;response;?&gt;</pre>
<p>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..</p>
<p>If you enjoyed this series of tutorials and want to throw me a bone, <a href="http://tk2.us/kmttax" target="_blank">click here to get your 10% off Turbo Tax coupon</a>!</p>
<p><a href="http://images.dealtaker.com/dealtaker/blog/ko3-tutorial/mykohana3_5.zip">Get the file for this tutorial here</a></p>
<p>Sources used: <a href="http://kerkness.ca/wiki/doku.php" target="_blank">Unofficial Kohana 3 Wiki</a>, <a href="http://techportal.ibuildings.com/2010/02/22/scaling-web-applications-with-hmvc/" target="_blank">iBuildings: Scaling Web Applications with HMVC</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dealtaker.com/blog/2010/02/25/kohana-php-3-0-ko3-tutorial-part-5/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Kohana PHP 3.0 (KO3) Tutorial Part 4</title>
		<link>http://www.dealtaker.com/blog/2010/02/01/kohana-php-3-0-ko3-tutorial-part-4/</link>
		<comments>http://www.dealtaker.com/blog/2010/02/01/kohana-php-3-0-ko3-tutorial-part-4/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 18:20:40 +0000</pubDate>
		<dc:creator>ellisgl</dc:creator>
				<category><![CDATA[technology]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[KO3]]></category>
		<category><![CDATA[kohana]]></category>
		<category><![CDATA[models]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.dealtaker.com/blog/?p=1921</guid>
		<description><![CDATA[Welcome to the fourth part in this series on how to develop with Kohana PHP V3 (KO3). If you haven&#8217;t read any of previous parts yet, I would click here 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 [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to the fourth part in this series on how to develop with Kohana PHP V3 (KO3). If you haven&#8217;t read any of previous parts yet, <a href="http://www.dealtaker.com/blog/tag/ko3/">I would click here and read them before going on</a>. In this tutorial we will be going over how work with models.<br />
<span id="more-1921"></span><br />
So you might be asking your self, what is a model. From <a href="http://docs.kohanaphp.com/">Kohana&#8217;s 2.x documents</a>:</p>
<blockquote cite="http://docs.kohanaphp.com/general/models"><p>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.</p></blockquote>
<p>Simply a model is a data handler and manipulator.</p>
<p>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.</p>
<p>Lets open up your bootstrap file (&#8221;application/bootstrap.php&#8221;) and find the like that reads &#8220;// &#8216;database&#8217;   =&gt; MODPATH.&#8217;database&#8217;,   // Database access&#8221; and uncomment it. The whole block of code should look like the following:</p>
<pre>Kohana::modules(array(
	// 'auth'       =&gt; MODPATH.'auth',       // Basic authentication
	// 'codebench'  =&gt; MODPATH.'codebench',  // Benchmarking tool
	 'database'   =&gt; MODPATH.'database',   // Database access
	// 'image'      =&gt; MODPATH.'image',      // Image manipulation
	// 'orm'        =&gt; MODPATH.'orm',        // Object Relationship Mapping
	// 'pagination' =&gt; MODPATH.'pagination', // Paging of results
	// 'userguide'  =&gt; MODPATH.'userguide',  // User guide and API documentation
	));</pre>
<p>Now save this. We&#8217;ve basically told the bootstrap to load the database module, but we need to configure it. Copy the &#8220;database.php&#8221; from &#8220;modules/database/config/&#8221; to &#8220;application/config/&#8221;. Open up the &#8220;application/config/database.php&#8221; file and edit accordingly to your settings. Mine looks like this:</p>
<pre>&lt;?php defined('SYSPATH') OR die('No direct access allowed.');

return array
(
	'default' =&gt; array
	(
		'type'       =&gt; 'mysql',
		'connection' =&gt; array(
			/**
			 * The following options are available for MySQL:
			 *
			 * string   hostname
			 * integer  port
			 * string   socket
			 * string   username
			 * string   password
			 * boolean  persistent
			 * string   database
			 */
			'hostname'   =&gt; 'localhost',
			'username'   =&gt; 'root',
			'password'   =&gt; FALSE,
			'persistent' =&gt; FALSE,
			'database'   =&gt; 'mykohana3',
		),
		'table_prefix' =&gt; '',
		'charset'      =&gt; 'utf8',
		'caching'      =&gt; FALSE,
		'profiling'    =&gt; TRUE,
	),
	'alternate' =&gt; array(
		'type'       =&gt; 'pdo',
		'connection' =&gt; array(
			/**
			 * The following options are available for PDO:
			 *
			 * string   dsn
			 * string   username
			 * string   password
			 * boolean  persistent
			 * string   identifier
			 */
			'dsn'        =&gt; 'mysql:host=localhost;dbname=mykohana3',
			'username'   =&gt; 'root',
			'password'   =&gt; FALSE,
			'persistent' =&gt; FALSE,
		),
		'table_prefix' =&gt; '',
		'charset'      =&gt; 'utf8',
		'caching'      =&gt; FALSE,
		'profiling'    =&gt; TRUE,
	),
);</pre>
<p>Save this. You&#8217;ll notice I have a database setup just this tutorial series named &#8220;mykohana3&#8243;, you might want to do the same if you can. Now that we have saved, let get a table set up. Here&#8217;s the SQL:</p>
<pre>CREATE TABLE `posts` (
  `id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(255) DEFAULT NULL,
  `post` TEXT,
  PRIMARY KEY  (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;</pre>
<p>Go run that in your favorite MySQL client, I personally like <a href="http://code.google.com/p/sqlyog/">SQLYog</a>. You might have noticed the &#8220;charset&#8221; is set to &#8220;utf8&#8243; in both the config and create table statement. This will allow us to deal with i18n (Internationalization) stuff later on.</p>
<p>So let create a new folder under &#8220;application/classes&#8221; named &#8220;model&#8221;. Now lets create a new file and make it look like this:</p>
<pre>&lt;?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-&gt;_db-&gt;query(Database::SELECT, $sql, FALSE)
                         -&gt;as_array();
     }
 }</pre>
<p>Save this as &#8220;post.php&#8221; under &#8220;application/classes/model/&#8221;. Here&#8217;s an line by line explaination of the code.</p>
<pre>        $sql = 'SELECT *'."\n".
               'FROM   `posts`'."\n".
               'ORDER BY `id` DESC'."\n".
               'LIMIT  0, 10';</pre>
<p>This is a basic MySQL statement that selects up to ten rows from the DB which are sorted by the &#8216;id&#8217; in a descending direction.</p>
<pre>        return $this-&gt;_db-&gt;query(Database::SELECT, $sql, FALSE)
                         -&gt;as_array();</pre>
<p>This return array of the result from a query. The &#8220;query&#8221; method in this example take 3 parameters. 1st being what type of query, our being select, we use the constant &#8220;Database::SELECT&#8221;. There are 3 others,  &#8220;Database::INSERT&#8221;,  &#8220;Database::UPDATE&#8221; and &#8220;Database::DELETE&#8221;. The &#8220;as_array()&#8221; will return an array of the results, no having to do &#8220;while($row = mysql_fetch_array())&#8221;.</p>
<p>Now that we have a model method, I&#8217;m sure we would want to put it use. Open up &#8220;ko3.php&#8221; in &#8220;/application/classes/controller&#8221; and lets add this into the class:</p>
<pre>    public function action_posts()
     {
        $posts                            = new Model_Post();
        $ko3                              = array();
        $this-&gt;template-&gt;title            = 'Kohana 3.0 Model Test';
        $this-&gt;template-&gt;meta_keywords    = 'PHP, Kohana, KO3, Framework, Model';
        $this-&gt;template-&gt;meta_description = 'A test of of the KO3 framework Model';
        $this-&gt;template-&gt;styles           = array();
        $this-&gt;template-&gt;scripts          = array();

        // Get the last 10 posts
        $ko3['posts']                     = $posts-&gt;getLastTenPosts();
        $this-&gt;template-&gt;content          = View::factory('pages/posts', $ko3);

     }</pre>
<p>Basically we&#8217;ve called our model&#8217;s &#8220;getLastTenPosts()&#8221; 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:</p>
<pre>&lt;?php foreach($posts as $post):?&gt;
  &lt;h1&gt;&lt;?php echo $post['title'];?&gt;&lt;/h1&gt;
  &lt;?php echo $post['post'];?&gt;
 &lt;hr /&gt;
&lt;?php endforeach;?&gt;</pre>
<p>Save to as &#8220;posts.php&#8221; under &#8220;application/views/pages/&#8221;. This view loops through the array we pass to it from the the controller and displays our posts from the DB. Wait, what? There&#8217;s no posts in our DB! Here&#8217;s some SQL you can run to populate your table:</p>
<pre>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');</pre>
<p>Now if you point your browser to &#8220;http://yourserver/mykohana3/ko3/posts&#8221; you should see the two entries on the screen.</p>
<p>Now lets add something to put data into our DB. Open the the post model (&#8221;application/classes/model/post.php&#8221;) and add this to the class:</p>
<pre>    public function addPost($title, $post)
     {
       $sql = sprintf('INSERT INTO `posts`'."\n".
                      'SET         `title` = %s,'."\n".
                      '            `post`  = %s',
                       $this-&gt;_db-&gt;escape($title),
                       $this-&gt;_db-&gt;escape($post));

       $this-&gt;_db-&gt;query(Database::INSERT, $sql, FALSE);
    }</pre>
<p>The above is a pretty simple insert, but you may notice we are using &#8220;$this-&gt;_db&gt;escape()&#8221;. This will wrap your strings in quotes and escape it content for you. Save it and now go back to the &#8220;posts.php&#8221; from &#8220;application/views/pages&#8221; and add the following to the bottom:</p>
<pre>&lt;form method="POST" action=""&gt;
  &lt;table&gt;
    &lt;tr&gt;
     &lt;td&gt;
       Title
     &lt;/td&gt;
     &lt;td&gt;
       &lt;input type="text" name="title" style="border: 1px solid #000000;"/&gt;
     &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
     &lt;td&gt;
      Post
     &lt;/td&gt;
     &lt;td&gt;
      &lt;textarea cols="20" rows="5" name="post"&gt;&lt;/textarea&gt;
      &lt;input type="submit" name="submit" value="Submit"/&gt;
     &lt;/td&gt;
  &lt;/table&gt;
&lt;/form&gt;</pre>
<p>Save that and open the ko3 controller back up (&#8221;application/classes/controller/ko3.php&#8221;) and lets add a new method to it.</p>
<pre>    private function _addPost($title, $post_content)
     {
       // Load model
       $post = new Model_Post();

       // Check required fields
       if(empty($title))
        {
           return(array('error' =&gt; 'Please enter a title.'));
        }
       elseif(empty($post_content))
        {
           return(array('error' =&gt; 'Please enter a post.'));
        }

       // Add to DB
       $post-&gt;addPost($title, $post_content);
       return TRUE;
     }</pre>
<p>The above code is pretty much a middle man between the &#8220;action_posts&#8221; and the model that saves the post it self. Lets go back to the &#8220;action_posts&#8221; method and make it look like this:</p>
<pre>   public function action_posts()
     {
        // Load model
        $posts                            = new Model_Post();

        // Setup view stuff
        $ko3                              = array();
        $this-&gt;template-&gt;title            = 'Kohana 3.0 Model Test';
        $this-&gt;template-&gt;meta_keywords    = 'PHP, Kohana, KO3, Framework, Model';
        $this-&gt;template-&gt;meta_description = 'A test of of the KO3 framework Model';
        $this-&gt;template-&gt;styles           = array();
        $this-&gt;template-&gt;scripts          = array();
        $ko3['msg']                       = "";

        // Handle POST
        if($_POST)
         {
            $ret = $this-&gt;_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-&gt;getLastTenPosts();

        // Display it.
        $this-&gt;template-&gt;content          = View::factory('pages/posts', $ko3);
     }</pre>
<p>Save this and reload your browser. Now you should see a pretty ugly form at bottom. Enter some stuff in and click the &#8220;submit&#8221; button. You post should appear at the top along with the word &#8220;Saved&#8221;, this is if you entered stuff in both fields, if not you should see an error.</p>
<p>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.</p>
<pre>    public function addPost($title, $post)
     {
        DB::insert('posts', array('title','post'))
          -&gt;values(array($title, $post))
          -&gt;execute();
     }</pre>
<p>That&#8217;s pretty simple! It does the same thing as the previous one, with less &#8220;hassle&#8221; There are advantages using the query builder method, like being able to convert between different DB types (MySQL to Oracle to what ever).</p>
<p>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 &#8220;H&#8221; in &#8220;HMVC&#8221;, happy coding.</p>
<p>Sources used: <a href="http://kerkness.ca/wiki/doku.php" target="_blank">Unofficial Kohana 3 Wiki</a>, <a href="http://docs.kohanaphp.com/" target="_blank">Kohana PHP 2.x Docs</a>, <a href="http://v3.kohanaphp.com/guide/api" target="_blank">KO3 API Guide</a></p>
<p><a href="http://images.dealtaker.com/dealtaker/blog/ko3-tutorial/mykohana3_4.zip">Get the file for this tutorial here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dealtaker.com/blog/2010/02/01/kohana-php-3-0-ko3-tutorial-part-4/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Kohana PHP 3.0 (KO3) Tutorial Part 3</title>
		<link>http://www.dealtaker.com/blog/2009/12/30/kohana-php-3-0-ko3-tutorial-part-3/</link>
		<comments>http://www.dealtaker.com/blog/2009/12/30/kohana-php-3-0-ko3-tutorial-part-3/#comments</comments>
		<pubDate>Wed, 30 Dec 2009 15:08:30 +0000</pubDate>
		<dc:creator>ellisgl</dc:creator>
				<category><![CDATA[technology]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[KO3]]></category>
		<category><![CDATA[kohana]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.dealtaker.com/blog/?p=1873</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to the third part in this series on how to develop with Kohana PHP V3 (KO3). If you havenâ€™t read the <a href="http://www.dealtaker.com/blog/2009/11/20/kohana-php-3-0-ko3-tutorial-part-1/" target="_blank">first</a> and/or <a href="http://www.dealtaker.com/blog/2009/12/07/kohana-php-3-0-ko3-tutorial-part-2/" target="_blank">second parts</a> yet, I would click here and read them before going on. In this tutorial we will be going over how to create a template.<br />
<span id="more-1873"></span><br />
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 &#8220;DRY&#8221; in the view world. Before we get to putting code into a file, lets create a new directory under &#8220;/application/views/&#8221; named &#8220;templates&#8221;.  Now open up your favorite IDE and make a new file and put the following into it:</p>
<pre>
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;
&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;en&quot; lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;meta http-equiv=&quot;Content-type&quot; content=&quot;text/html; charset=UTF-8&quot; /&gt;
    &lt;meta http-equiv=&quot;Content-Language&quot; content=&quot;en-us&quot; /&gt;
    &lt;title&gt;&lt;?php echo $title;?&gt;&lt;/title&gt;
    &lt;meta name=&quot;keywords&quot; content=&quot;&lt;?php echo $meta_keywords;?&gt;&quot; /&gt;
    &lt;meta name=&quot;description&quot; content=&quot;&lt;?php echo $meta_description;?&gt;&quot; /&gt;
    &lt;meta name=&quot;copyright&quot; content=&quot;&lt;?php echo $meta_copywrite;?&gt;&quot; /&gt;
    &lt;?php foreach($styles as $file =&gt; $type) { echo HTML::style($file, array('media' =&gt; $type)), &quot;\n&quot;; }?&gt;
    &lt;?php foreach($scripts as $file) { echo HTML::script($file), &quot;\n&quot;; }?&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=&quot;container&quot;&gt;
     &lt;?php echo $header;?&gt;
     &lt;?php echo $content;?&gt;
     &lt;?php echo $footer;?&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Save the above as &#8220;default.php&#8221; in your &#8220;/application/views/templates/&#8221; folder. </p>
<p>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 &#8220;foreach&#8221; 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 &#8220;DRY&#8221;.</p>
<p>Now that we have a template, our system isn&#8217;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:</p>
<pre>
&lt;?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-&gt;auto_render)
          {
            // Initialize empty values
            $this-&gt;template-&gt;title            = '';
            $this-&gt;template-&gt;meta_keywords    = '';
            $this-&gt;template-&gt;meta_description = '';
            $this-&gt;template-&gt;meta_copywrite   = '';
            $this-&gt;template-&gt;header           = '';
            $this-&gt;template-&gt;content          = '';
            $this-&gt;template-&gt;footer           = '';
            $this-&gt;template-&gt;styles           = array();
            $this-&gt;template-&gt;scripts          = array();
          }
      }

     /**
      * Fill in default values for our properties before rendering the output.
      */
     public function after()
      {
         if($this-&gt;auto_render)
          {
             // Define defaults
             $styles                  = array('assets/css/reset.css' =&gt; 'screen');
             $scripts                 = array('http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js');

             // Add defaults to template variables.
             $this-&gt;template-&gt;styles  = array_reverse(array_merge($this-&gt;template-&gt;styles, $styles));
             $this-&gt;template-&gt;scripts = array_reverse(array_merge($this-&gt;template-&gt;scripts, $scripts));
           }

         // Run anything that needs to run after this.
         parent::after();
      }
 }
</pre>
<p>And save this as &#8220;defaulttemplate.php&#8221; under your &#8220;/application/classes/controller/&#8221; folder.</p>
<p>The above code extends the &#8220;Controller_Template&#8221; 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 &#8220;HTML&#8221;, one to <a href="http://v3.kohanaphp.com/guide/api/HTML#style" target="_blank">load CSS style sheets</a> and one to <a href="http://v3.kohanaphp.com/guide/api/HTML#script" target="_blank">load JS files</a>. 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. </p>
<p>You might be wondering what a &#8220;Helper&#8221; is, so here is a quick definition from the Kohana PHP 2.x documents:</p>
<blockquote cite="http://docs.kohanaphp.com/general/helpers"><p>
Helpers are simply &#8220;handy&#8221; functions that help you with development.</p>
<p>Helpers are similar to library methods, but there is a subtle difference. With a library, you have to create an instance of the library&#8217;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â€.</p>
<p>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.
</p></blockquote>
<p>OK, back on course. You might have noticed there is a reference to &#8220;assets/css/reset.css&#8221;, so lets go ahead and get that in place. In your root create a folder named &#8220;assets&#8221; and in that folder create one named &#8220;css&#8221;. For the actual &#8220;reset.css&#8221; file, I went to <a href="http://serenedestiny.com/" target="blank">Serene Destiny</a> and copied the code from the article titled &#8220;<a href="http://serenedestiny.com/blog/2009/04/open-thread-create-the-perfect-css-reset/" target="_blank">Create The Perfect CSS Reset</a>&#8221; into a file and saved it as &#8220;reset.css&#8221; in the &#8220;assets/css/&#8221; folder. You might want to also set up some other folders within &#8220;/assets/&#8221;, maybe &#8220;images&#8221;, &#8220;js&#8221; and &#8220;files&#8221;. Basically the assets folder should be used to store and organize static files and such.</p>
<p>At this point, our application still doesn&#8217;t know what to do what we have done, so we need to modify our controller. So open &#8220;/application/classes/controller/ko3.php&#8221;.<br />
We want to change what class we are extending, so change the line:</p>
<pre>class Controller_Ko3 extends Controller</pre>
<p>to:</p>
<pre>lass Controller_Ko3 extends Controller_DefaultTemplate</pre>
<p>We also need to change up our &#8220;index&#8221; action (action_index() method) to look like the following:</p>
<pre>
    public function action_index()
     {
        $ko3_inner               = array();
        $ko3                     = array();
        $this-&gt;template-&gt;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)
                                       -&gt;render();
        $this-&gt;template-&gt;content = View::factory('pages/ko3', $ko3);
     }
</pre>
<p>Save it. Now you might noticed that we now have &#8220;$this-&gt;template-&gt;title   = &#8216;Kohana 3.0&#8242;;&#8221;, this will assign a value to our templates &#8220;title&#8221; variable. The next thing you might notice is the absence of the last &#8220;render()&#8221; method. The &#8220;factory()&#8221; method actually will &#8220;auto render&#8221; it to our template&#8217;s &#8220;content&#8221; variable. Pretty simple, yes?</p>
<p>There is something we should probably do before loading up the page, so load up the &#8220;ko3.php&#8221; view file located in &#8220;application/views/pages/&#8221;. You might noticed that we have all the &#8220;shell&#8221; code in our view, so lets remove it. What you should only have in the view file is this:</p>
<pre>
  &lt;h1&gt;This is my first view&lt;/h1&gt;
  &lt;?php echo $content;?&gt;
  &lt;?php echo $ko3_inner; ?&gt;
  &lt;br/&gt;&lt;?php echo $x;?&gt;
</pre>
<p>Now if you load it up, you should see that page has a title of &#8220;Kohana 3.0&#8243; 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 &#8220;index&#8221; action again. Make it look like:</p>
<pre>
    public function action_index()
     {
        $ko3_inner                        = array();
        $ko3                              = array();
        $this-&gt;template-&gt;title            = 'Kohana 3.0';
        $this-&gt;template-&gt;meta_keywords    = 'PHP, Kohana, KO3, Framework';
        $this-&gt;template-&gt;meta_description = 'A test of of the KO3 framework';
        $this-&gt;template-&gt;styles           = array('assets/css/red.css' =&gt; 'screen');
        $this-&gt;template-&gt;scripts          = array('assets/js/jqtest.js', NULL, TRUE);

        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)
                                                -&gt;render();
        $this-&gt;template-&gt;content          = View::factory('pages/ko3', $ko3);
     }
</pre>
<p>Pretty simple. You will notice I didn&#8217;t fill in the header or footer. I&#8217;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 &#8220;assets/css/red.css&#8221; and &#8220;assets/css/jqtest.js&#8221;. Lets make those two files starting with &#8220;/assets/css/red.css&#8221;:</p>
<pre>
h1
 {
    color: #FF0000;
 }
</pre>
<p>Next &#8220;/assets/js/jqtest.js&#8221;:</p>
<pre>
$("document").ready(function()
                     {
                        alert('Hello Kohana!');
                     });
</pre>
<p>Save them and refresh the site. You should see an alert pop up and the first line of text in red.</p>
<p>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!<br />
Sources used: <a href="http://kerkness.ca/wiki/doku.php" target="_blank">Unofficial Kohana 3 Wiki</a>, <a href="http://docs.kohanaphp.com/" target="_blank">Kohana PHP 2.x Docs</a></p>
<p><a href="http://images.dealtaker.com/dealtaker/blog/ko3-tutorial/mykohana3_3.zip">Get the file for this tutorial here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dealtaker.com/blog/2009/12/30/kohana-php-3-0-ko3-tutorial-part-3/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Kohana PHP 3.0 (KO3) Tutorial Part 2</title>
		<link>http://www.dealtaker.com/blog/2009/12/07/kohana-php-3-0-ko3-tutorial-part-2/</link>
		<comments>http://www.dealtaker.com/blog/2009/12/07/kohana-php-3-0-ko3-tutorial-part-2/#comments</comments>
		<pubDate>Mon, 07 Dec 2009 15:47:54 +0000</pubDate>
		<dc:creator>ellisgl</dc:creator>
				<category><![CDATA[technology]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[KO3]]></category>
		<category><![CDATA[kohana]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[views]]></category>

		<guid isPermaLink="false">http://www.dealtaker.com/blog/?p=1835</guid>
		<description><![CDATA[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 click here and read it before going on. In this tutorial we will be going over how to develop views.

Before we get into views, we&#8217;ll want to update the [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to the second part in this series on how to develop with Kohana PHP V3 (<acronym title="Kohana PHP 3">KO3</acronym>). If you havenâ€™t read the first part, I would <a href="http://www.dealtaker.com/blog/2009/11/20/kohana-php-3-0-ko3-tutorial-part-1/">click here</a> and read it before going on. In this tutorial we will be going over how to develop views.<br />
<span id="more-1835"></span><br />
Before we get into views, we&#8217;ll want to update the KO3 code base, So point your browser to <a href="http://dev.kohanaphp.com/projects/kohana3/files">http://dev.kohanaphp.com/projects/kohana3/files</a>, download it, open it and extract everything inside the &#8220;kohana&#8221; folder to &#8220;mykohana3&#8243;. Once you have done that, delete or rename the &#8220;install.php&#8221; in your &#8220;mykohana3&#8243; folder. Next, open up the &#8220;bootstrap.php&#8221; file in the &#8220;application&#8221; folder and change the following line:</p>
<pre>Kohana::init(array('base_url' =&gt; '/kohana/'));</pre>
<p>to</p>
<pre>Kohana::init(array('base_url'   =&gt; '/mykohana3/',
                   'index_file' =&gt; ''));</pre>
<p>Now that we are updated to the latest and greatest, lets get right in to developing a view. Create a new folder within the &#8220;application&#8221; folder named &#8220;views&#8221; and inside the &#8220;views&#8221; folder, create another folder named &#8220;pages&#8221;. Now open up a new document in your editor and put the following in it:</p>
<pre>&lt;html&gt;
 &lt;head&gt;
  &lt;title&gt;Hello!&lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
  &lt;h1&gt;This is my first view&lt;/h1&gt;
 &lt;/body&gt;
&lt;/html&gt;</pre>
<p>Now save that in your &#8220;application/views/pages&#8221; as &#8220;ko3.php&#8221;. As you can tell, it&#8217;s a pretty simple HTML page with some PHP mixed in. Lets open the &#8220;ko3&#8243; controller (&#8221;application/classes/controller/ko3.php&#8221;). Replace the &#8220;action_index&#8221; class with the following:</p>
<pre>    public function action_index()
     {
        $this-&gt;request-&gt;response = View::factory('pages/ko3');
     }</pre>
<p>Save it, and load up &#8220;http://yourserver/myfirstkohana3/&#8221; in your browser. You should see &#8220;This is my first view&#8221;. The code above is pretty simple, we use the &#8220;Facotry&#8221; method of the view class to load the file &#8220;application/views/pages/ko3.php&#8221;, renders it and outputs it. Not very exciting, so let go back to the view (&#8221;application/views/pages/ko3.php&#8221;) and add:</p>
<pre>  &lt;?php echo $content;?&gt;</pre>
<p>After the &#8220;h1&#8243; tags. Your view should look like this:</p>
<pre>&lt;html&gt;
 &lt;head&gt;
  &lt;title&gt;Hello!&lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
  &lt;h1&gt;This is my first view&lt;/h1&gt;
  &lt;?php echo $content;?&gt;
 &lt;/body&gt;
&lt;/html&gt;</pre>
<p>If we were to refresh the browser, we would seen an exception error about an undefined variable. So let&#8217;s go ahead and fix that, by relating data to the view variable in our controller. So, change up &#8220;Action_Index&#8221; controller to look like this:</p>
<pre>    public function action_index()
     {
        $view                       = View::factory('pages/ko3');
        $view-&gt;content              = 'We have data!';
        $this-&gt;request-&gt;response = $view-&gt;render();
     }</pre>
<p>Now if we refresh the browser, we should see &#8220;This is my first view&#8221; and under that &#8220;We have data!&#8221;. Lets explain the the code line by line.</p>
<pre>$view = View::factory('pages/ko3');</pre>
<p>This load our view file (&#8221;application/views/pages/ko3.php&#8221;) into the view controller.</p>
<pre>$view-&gt;content = 'We have data!';</pre>
<p>This assigns a variable for use by the view called &#8220;content&#8221; and we also assign data to that, in this case it&#8217;s &#8220;We have data!&#8221;</p>
<pre>$this-&gt;request-&gt;response = $view-&gt;render();</pre>
<p>This renders the view and outputs it.</p>
<p>Simple enough, but there is another way of doing the above. We could have also done the following:</p>
<pre>    public function action_index()
     {
        $data['content']         = 'We have data!';
        $view                    = View::factory('pages/ko3', $data);
        $this-&gt;request-&gt;response = $view-&gt;render();
     }</pre>
<p>Basically the above use an array with element keys as the template variable names to assign the data. We are not done yet! There&#8217;s 2 more ways we can do the above.</p>
<pre>    public function action_index()
     {
        $view                    = View::factory('pages/ko3')
                                       -&gt;set('content', 'We have data!');

        $this-&gt;request-&gt;response = $view-&gt;render();
     }</pre>
<p>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:</p>
<pre>    public function action_index()
     {
        $content                 = 'We have data!';
        $view                    = View::factory('pages/ko3')
                                       -&gt;bind('content', $content);
        $this-&gt;request-&gt;response = $view-&gt;render();
     }</pre>
<p>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 &#8216;We have data!&#8217; 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.</p>
<p>If we were to do the following:</p>
<pre>    public function action_index()
     {
        $content                 = 'We have data!';
        $view                    = View::factory('pages/ko3')
                                       -&gt;bind('content', $content);
        $content                 = 'Our data changed';
        $this-&gt;request-&gt;response = $view-&gt;render();
     }</pre>
<p>Instead of &#8220;We have data!&#8221; showing on our screen, we would have &#8220;Our data changed&#8221;.</p>
<p>Now lets do a view with in a view! Create a new folder in your &#8220;application/views/&#8221; named &#8220;blocks&#8221;. Lets create another view file named &#8220;ko3_inner.php&#8221; and put this in it:</p>
<pre>  &lt;h3&gt;This is an inner view&lt;/h3&gt;</pre>
<p>Save that in your &#8220;application/views/blocks/&#8221; directory. Now lets edit the &#8220;ko3&#8243; view (&#8221;application/views/pages/ko3.php&#8221;) and add the following:</p>
<pre>  &lt;?php echo View::factory('blocks/ko3_inner')-&gt;render(); ?&gt;</pre>
<p>You view should like this:</p>
<pre>&lt;html&gt;
 &lt;head&gt;
  &lt;title&gt;Hello!&lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
  &lt;h1&gt;This is my first view&lt;/h1&gt;
  &lt;?php echo $content;?&gt;
  &lt;?php echo View::factory('blocks/ko3_inner')-&gt;render(); ?&gt;
 &lt;/body&gt;
&lt;/html&gt;</pre>
<p>So if we run it we should see what we had before, then &#8220;This is an inner view&#8221;. This would be useful for static content, but we won&#8217;t be able to use variables directly to that view. So let fix this. Lets go back to our controller (&#8221;application/classes/controllers/ko3.php&#8221;) and edit the &#8220;Action_Index&#8221; method to look like this:</p>
<pre>    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)
                                       -&gt;render();
        $view                    = View::factory('pages/ko3', $ko3);
        $this-&gt;request-&gt;response = $view-&gt;render();
     }</pre>
<p>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 (&#8221;application/views/pages/ko3.php&#8221;). The line we put in before, we will change it to:</p>
<pre>  &lt;?php echo $ko3_inner; ?&gt;</pre>
<p>The view should look like this:</p>
<pre>&lt;html&gt;
 &lt;head&gt;
  &lt;title&gt;Hello!&lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
  &lt;h1&gt;This is my first view&lt;/h1&gt;
  &lt;?php echo $content;?&gt;
  &lt;?php echo $ko3_inner; ?&gt;
 &lt;/body&gt;
&lt;/html&gt;</pre>
<p>And the last change we need to make is to the inner view (&#8221;application/views/blocks/ko3_inner.php&#8221;). Make it look like this:</p>
<pre>  &lt;h3&gt;This is an inner view&lt;/h3&gt;
  &lt;?php echo $content;?&gt;</pre>
<p>If you refresh the browser after saving, you should now see the following:</p>
<pre>This is my first view

We have data

This is an inner view

We have more data</pre>
<p>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 (&#8221;applications/classes/controllers/ko3.php&#8221;) and edit the &#8220;Action_Index&#8221; method so the following is at the top of the method:</p>
<pre>       View::set_global('x', 'This is a global variable');</pre>
<p>So now the method should look like this:</p>
<pre>    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)
                                       -&gt;render();
        $view                    = View::factory('pages/ko3', $ko3);
        $this-&gt;request-&gt;response = $view-&gt;render();
     }</pre>
<p>Now if you were to edit your views and add in:</p>
<pre>  &lt;br/&gt;&lt;?php echo $x;?&gt;</pre>
<p>You should now see &#8220;This is a global variable&#8221; two times on the page. As you can see this could be very handy. Basically, we are using the static method of &#8220;set&#8221; from the view class, so it ends up being available to all view object instances. You can also use the static method of &#8220;bind&#8221; to reference variables. This could be handy for dry things &#8220;<acronym title="Don't Repeat Yourself">DRY</acronym>&#8221; and could be used in other place, like a contruct.</p>
<p>Untill next time, when I go over &#8220;templates&#8221; (advanced views and controller stuff), happy coding!<br />
Sources used: <a href="http://kerkness.ca/wiki/doku.php?id=template-site:create_the_template" target="_blank">Unofficial Kohana 3 Wiki</a></p>
<p><a href="http://images.dealtaker.com/dealtaker/blog/ko3-tutorial/mykohana3_2.zip">Get the file for this tutorial here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dealtaker.com/blog/2009/12/07/kohana-php-3-0-ko3-tutorial-part-2/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Kohana PHP 3.0 (KO3) Tutorial Part 1</title>
		<link>http://www.dealtaker.com/blog/2009/11/20/kohana-php-3-0-ko3-tutorial-part-1/</link>
		<comments>http://www.dealtaker.com/blog/2009/11/20/kohana-php-3-0-ko3-tutorial-part-1/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 21:47:05 +0000</pubDate>
		<dc:creator>ellisgl</dc:creator>
				<category><![CDATA[technology]]></category>
		<category><![CDATA[controller]]></category>
		<category><![CDATA[controllers]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[KO3]]></category>
		<category><![CDATA[kohana]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.dealtaker.com/blog/?p=1768</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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!<span id="more-1768"></span></p>
<p>Lets check to make sure we have everything needed before going on.</p>
<ul>
<li>*AMP (Apache MySQL PHP) install</li>
<li>Knowledge of PHP</li>
<li>Know what a frame work is (<a href="http://www.dealtaker.com/blog/2009/02/10/frameworks-frameworks-frameworks/">Framework Article</a>)</li>
<li>Know what MVC is (<a href="http://en.wikipedia.org/wiki/Model-view-controller">Wikipedia Entry</a>)</li>
</ul>
<p>Lets go!<br />
Download:<br />
<a href="http://dev.kohanaphp.com/projects/kohana3/files">Download the latest Kohana 3.0 PHP</a> (At the time of this writing: 3.0.1.2) and unpack it somewhere.</p>
<p>Install:<br />
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 &#8220;kohana&#8221; 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 &#8220;C:\wamp\www\&#8221;. Next make a new folder in there named &#8220;mykohana3&#8243;. Copy the files from the &#8220;kohana&#8221; directory to the &#8220;mykohana3&#8243;. Make sure your *AMP installation is up and running then point your browser to &#8220;http://yourserver/mykohana3/&#8221;. You should have a screen stating that everything is &#8220;OK&#8221;.<br />
<img src="//images.dealtaker.com/dealtaker/blog/ko3-tutorial/ko3-tut1-1.png" alt="" /></p>
<p>If everything is &#8220;OK&#8221;, then remove or rename the &#8220;install.php&#8221; file in the &#8220;mykohana3&#8243; directory. Next open up the &#8220;example.htaccess&#8221; file and change the following line:</p>
<pre>RewriteBase /kohana/</pre>
<p>to:<br />
<code><br />
RewriteBase /mykohana3/<br />
</code></p>
<p>Save it as &#8220;.htaccess&#8221;.</p>
<p>Now open the &#8220;bootstrap.php&#8221; file located in the &#8220;application&#8221; folder and cange the following line:</p>
<pre>Kohana::init(array('base_url' =&gt; '/kohana/'));</pre>
<p>to:</p>
<pre>Kohana::init(array('base_url'  =&gt; '/mykohana3/',
                   'index_file'=&gt; ''));</pre>
<p>Save this file then refresh your browser. You should get something that reads &#8220;hello, world!&#8221; on your screen.</p>
<p>You might already notice that configuration for KO3 is a little bit more involved, editing two files instead of one, which isn&#8217;t a big deal at all.</p>
<p>Now to make our first controller! Open a new document and put the following into it:</p>
<pre>&lt;?php
defined('SYSPATH') or die('No direct script access.');

class Controller_Ko3 extends Controller
 {
    public function action_index()
     {
        $this-&gt;request-&gt;response = 'My First Kohana 3.0 Controller';
     }
 } // End</pre>
<p>Save this as &#8220;ko3.php&#8221; in the &#8220;application/classes/controller&#8221; 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 &#8220;http://yourhost/mykohana3/ko3&#8243;. You should she &#8220;My First Kohana 3.0 Controller&#8221; on your screen now.</p>
<p>Now for an explanation of the code.</p>
<pre>defined('SYSPATH') or die('No direct script access.');</pre>
<p>This line basically tells PHP not load this file directly. It can only be included from the framework.</p>
<pre>class Controller_Ko3 extends Controller</pre>
<p>This creates an controller which is a class that is extended from the Controller class that is part of the framework.</p>
<pre>public function action_index()</pre>
<p>This created a public method called &#8220;action_index&#8221;. The &#8220;action_index&#8221; method is a default action that is loaded by the framework. It&#8217;s like your index.php file so to say.</p>
<pre>$this-&gt;request-&gt;response = 'My First Kohana 3.0 Controller';</pre>
<p>This will output &#8220;My First Kohana 3.0 Controller&#8221; to the screen. This basically works like &#8220;echo&#8221;.</p>
<p>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 &#8220;action_&#8221; and the you would access via going to &#8220;http://yourserver/mykohana3/controller/action&#8221;</p>
<p>Let go ahead and add a new method to our &#8220;ko3&#8243; controller by adding the following after the &#8220;action_index&#8221; method:</p>
<pre>    public function action_another()
     {
        $this-&gt;request-&gt;response = 'Another action';
     }</pre>
<p>Save the file and loaded up &#8220;http://yourserver/mykohana3/ko3/another&#8221; in your browser. If all goes well you should see &#8220;Another action&#8221; in your browser.</p>
<p>That was fun an all, but lets make it a little bit more dynamic!</p>
<p>Copy this code and put it after the &#8220;action_another&#8221; method:</p>
<pre>    public function action_dynamic($say)
     {
        $this-&gt;request-&gt;response = 'You said: '.$say;
     }</pre>
<p>Save this and load &#8220;http://yourserver/mykohana3/ko3/dynamic/Monkey&#8221; and you should see &#8220;You said: Monkey&#8221;</p>
<p>Untill next time, when I will go over the first part of views, happy coding!<br />
Sources used: <a href="http://kerkness.ca/wiki/doku.php">Unofficial Kohana 3 Wiki</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dealtaker.com/blog/2009/11/20/kohana-php-3-0-ko3-tutorial-part-1/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Kohana PHP Tuturial &#8211; Part III</title>
		<link>http://www.dealtaker.com/blog/2009/06/19/kohana-php-tuturial-part-iii/</link>
		<comments>http://www.dealtaker.com/blog/2009/06/19/kohana-php-tuturial-part-iii/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 13:26:09 +0000</pubDate>
		<dc:creator>ellisgl</dc:creator>
				<category><![CDATA[technology]]></category>
		<category><![CDATA[db]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[kohana]]></category>
		<category><![CDATA[models]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.dealtaker.com/blog/?p=1013</guid>
		<description><![CDATA[It&#8217;s been a couple weeks now, so lets get back on track with this series of tutorials. This tutorial will get into models and how to play with data.

The first thing I have to is tell you is that Kohana PHP has been updated since the last tutorial. So I have gone ahead and took [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a couple weeks now, so lets get back on track with this series of tutorials. This tutorial will get into models and how to play with data.<br />
<span id="more-1013"></span></p>
<p>The first thing I have to is tell you is that Kohana PHP has been updated since the last tutorial. So I have gone ahead and took the last tutorial and updated the core and made sure it worked with Kohana 2.3.4. <a href="http://images.dealtaker.com/dealtaker/blog/kohana/dealtaker-kohana-2-2.3.4.zip">You can grab that here</a>. Now onward to the glory!</p>
<p>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&#8217;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.</p>
<p>Go into your system/config folder and copy the database.php file to your application/config folder. Edit the application/config/database.php to reflect your server settings. Mine looks like this:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">$config['default'] = array
(
	'benchmark'     =&gt; TRUE,
	'persistent'    =&gt; FALSE,
	'connection'    =&gt; array
	(
		'type'     =&gt; 'mysql',
		'user'     =&gt; 'root',
		'pass'     =&gt; 'root',
		'host'     =&gt; 'localhost',
		'port'     =&gt; FALSE,
		'socket'   =&gt; FALSE,
		'database' =&gt; 'myfirstkohana'
	),
	'character_set' =&gt; 'utf8',
	'table_prefix'  =&gt; '',
	'object'        =&gt; TRUE,
	'cache'         =&gt; FALSE,
	'escape'        =&gt; TRUE
);</pre>
<p>Now that we have a configuration a connection for our database, we should probably set up a database and a table. Here&#8217;s the SQL:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`myfirstkohana` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `myfirstkohana`;

/*Table structure for table `posts` */
DROP TABLE IF EXISTS `posts`;

CREATE TABLE `posts` (
  `id` mediumint(8) unsigned NOT NULL auto_increment,
  `title` varchar(255) default NULL,
  `post` text,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC;

/*Data for the table `posts` */
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;</pre>
<p>This is a pretty straight forward &#8220;Create a DB and one table&#8221; setup. You might notice that we have everything set for UTF8. This will match the DB configuration setting and also will allow us to deal with i18n (Internationalization) stuff later on.</p>
<p>Onward to creating an actual model. There are a couple things to keep in mind with naming conventions, well really one. From the docs &#8220;The model class name is capitalized, does have _Model appended to it and should be the singular form of the name.&#8221;. There are so other rules when you are dealing with ORM, but we won&#8217;t be dealing with ORM in this tutorial.</p>
<p>Create a file named post.php in the &#8216;application/models/&#8217; folder and make it look like the following:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">&lt;?php
defined('SYSPATH') or die('No direct script access.');

class Post_Model extends Model
 {
    public function __construct()
    	{
		      parent::__construct();
    	}

 }</pre>
<p>As you can tell the above really doesn&#8217;t do much, so let&#8217;s give it some functionality:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">&lt;?php
defined('SYSPATH') or die('No direct script access.');

class Post_Model extends Model
 {
    public function __construct()
    	{
		      parent::__construct();
    	}

    public function getPosts()
     {
        $sql = 'SELECT *
                FROM   `posts`
                LIMIT  0, 10';

        return $this-&gt;db-&gt;query($sql);
     }
 }</pre>
<p>So we have a model method that pulls 10 posts from the table with a pretty simple query. We use &#8220;$this-&gt;query()&#8221; to run queries, which will return object and we return that to the calling entity. Check the query method <a href="http://docs.kohanaphp.com/libraries/database/query" target="_blank">docs here</a> for more information.</p>
<p>Let&#8217;s update our &#8216;Hello&#8217; controller to use this the model.</p>
<p>In your application/controllers/hello.php update your index() method to look like this:</p>
<pre>    public function index()
     {
        // Load the models
        $post  = new Post_Model;
        $posts = $post-&gt;getPosts();
        $rpsts = "";

        // Loop thru the posts
        foreach($posts-&gt;result_array(FALSE) as $row)
         {
          // Simple output of
          $rpsts .= '
    &lt;h1&gt;'.$row['title'].'&lt;/h1&gt;
    '.$row['post'].'&lt;hr /&gt;';
         }

        // Put something useful in our variables.
        $this-&gt;template-&gt;header-&gt;pageTitle .= ' ::: I am on the top';
        $this-&gt;template-&gt;content-&gt;content   = $rpsts;
     }</pre>
<p>When we run the hello controller, we won&#8217;t get much but &#8216;This is my second view&#8217;. We need to put stuff in the table. Use your favorite method of accessing your DB and insert some rows. Now when you run it you will see stuff!</p>
<p>If you notice there is a &#8220;$post-&gt;result_array()&#8221; inside a foreach loop. This allows us to loop though the results of the query easily from within the controller.</p>
<p>You might have notice something of bad practice. I pretty much created HTML inside the controller. As we all know, we shouldn&#8217;t do this. Let&#8217;s fix this!</p>
<p>Create a new view named main_posts.php and make it look like:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">&lt;?php foreach($posts as $post): ?&gt;
&lt;h1&gt;&lt;?php echo $post['title'];?&gt;&lt;h1&gt;
&lt;?php echo $post['post'];?&gt;&lt;hr /&gt;
&lt;?php endforeach; ?&gt;</pre>
<p>This view does a foreach on our query results and fills in our little view.</p>
<p>In the the index method of our controller we will need to change up the controller to use our new view.</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">   public function index()
     {
        // Load the models
        $post  = new Post_Model;
        $posts = $post-&gt;getPosts();

        // Put something useful in our variables.
        $this-&gt;template-&gt;header-&gt;pageTitle .= ' ::: I am on the top';

        // Posts view
        $this-&gt;template-&gt;content-&gt;content        = new View('main_posts');
        $this-&gt;template-&gt;content-&gt;content-&gt;posts = $posts-&gt;result_array(FALSE);
     }</pre>
<p>As you can tell, it&#8217;s pretty simple and it&#8217;s clean! Here&#8217;s a quick sample on how to do an insert. We are going to add a method to the post model called addPost.</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">  public function addPost($title, $post)
    {
       $sql = sprintf('INSERT INTO `posts`
                       SET         `title` = %s,
                                   `post`  = %s',
                       $this-&gt;db-&gt;escape($title),
                       $this-&gt;db-&gt;escape($post));
      $this-&gt;db-&gt;query($sql);
    }</pre>
<p>We need to add a method to handle adding of posts to our hello controller:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">   public function addpost()
     {
        // Load the models
        $post  = new Post_Model;
        $post-&gt;addPost($_POST['title'], $_POST['post']);
        url::redirect('hello');
     }</pre>
<p>And lets add a form to the end of the main_post.php in the views:</p>
<pre style="white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">&lt;form method="POST" action="&lt;?php echo url::base();?&gt;hello/addpost/"&gt;
  &lt;table&gt;
    &lt;tr&gt;
     &lt;th&gt;
       Title
     &lt;/th&gt;
     &lt;th&gt;
       Post
     &lt;/th&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
     &lt;td&gt;
      &lt;input type="text" name="title" /&gt;
     &lt;/td&gt;
     &lt;td&gt;
      &lt;textarea cols="20" rows="5" name="post"&gt;&lt;/textarea&gt;
      &lt;input type="submit" name="submit" value="Submit"/&gt;
     &lt;/td&gt;
  &lt;/table&gt;
&lt;/form&gt;</pre>
<p>Once again, pretty simple right? I could go on and give you how to edit entries, but I&#8217;m leaving that to you for your home work. Free free to post your results! Until next time when will go over libraries and helpers, keep on coding till your fingers bleed!</p>
<p><a href="http://images.dealtaker.com/dealtaker/blog/kohana/dealtaker-kohana-3.zip">Get the file for this tutorial here.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dealtaker.com/blog/2009/06/19/kohana-php-tuturial-part-iii/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Kohana PHP 2.3.x Tutorial Part II</title>
		<link>http://www.dealtaker.com/blog/2009/05/21/kohana-php-23x-tutorial-part-ii/</link>
		<comments>http://www.dealtaker.com/blog/2009/05/21/kohana-php-23x-tutorial-part-ii/#comments</comments>
		<pubDate>Thu, 21 May 2009 14:51:27 +0000</pubDate>
		<dc:creator>ellisgl</dc:creator>
				<category><![CDATA[technology]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[kohana]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[templates]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[views]]></category>

		<guid isPermaLink="false">http://www.dealtaker.com/blog/?p=633</guid>
		<description><![CDATA[Welcome to the second tutorial in this series on how to develop with Kohana PHP. If you haven&#8217;t read the first part, I would click here and read it 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 [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to the second tutorial in this series on how to develop with Kohana PHP. If you haven&#8217;t read the first part, I would <a href="http://www.dealtaker.com/blog/2009/04/23/kohana-php-23x-tutorial-part-1/">click here</a> and read it before going on. In this tutorial we will be going over views, wonderful views, glorious views.<br />
<span id="more-633"></span></p>
<p>Letâ€™s just dive straight into building our first picturesque view.<br />
Create the file &#8220;myfirstkohana/application/views/hello.php&#8221; and put the following into it:</p>
<pre>&lt;html&gt;
 &lt;head&gt;
  &lt;title&gt;Hello!&lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
  &lt;h1&gt;This is my first view&lt;/h1&gt;
  &lt;?php echo $content;?&gt;
 &lt;/body&gt;
&lt;/html&gt;</pre>
<p>Looking at the above, it&#8217;s pretty straight forward and simple HTML file with some simple PHP code thrown in.</p>
<p>Just because we put a view with the same name as our controller, it&#8217;s not going to be shown until we say so. Letâ€™s go back to our  wonderful controller &#8220;myfirstkohana/application/controllers/hello.php&#8221; and edit the index method to look like the following:</p>
<pre>public function index()
 {
  $view          = new View('hello');
  $view-&gt;content = 'Hello World!';
  $view-&gt;render(TRUE);
 }</pre>
<p>Let go through this line by line. The first line:</p>
<pre>$view = new View('hello');</pre>
<p>tells the framework to create a new &#8220;view&#8221; object and load the file :myfirstkohana/application/views/hello.php&#8221; into it. The next line:</p>
<pre>$view-&gt;content = 'Hello World!';</pre>
<p>creates a new property called &#8220;content&#8221; in the object that has the value &#8220;Hello World!&#8221;. The last line</p>
<pre>$view-&gt;render(TRUE);</pre>
<p>compiles the template with our assigned values and outputs it to the screen. What we should get when we load &#8220;http://youserver/myfirstkohana/hello&#8221; is &#8220;This is my first view&#8221; and below that should read &#8220;Hello World!&#8221;.</p>
<p>This might the simplist view you&#8217;ll see. Of course, I don&#8217;t think we&#8217;ll be wanting something so simple, so lets knock it up notch and create views with nested views.</p>
<p>Create the file &#8220;myfirstkohana/application/views/default_template.php&#8221; and put this in it:</p>
<pre>&lt;?php echo $header; ?&gt;
&lt;?php echo $content; ?&gt;
&lt;?php echo $footer; ?&gt;</pre>
<p>The above code is just a master template, or the template of templates if you will. Next lets create &#8220;myfirstkohana/application/views/default_header.php&#8221; and put the following into it:</p>
<pre>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" &gt;
 &lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
  &lt;title&gt;&lt;?php echo $pageTitle;?&gt;&lt;/title&gt;
 &lt;/head&gt;</pre>
<p>and then &#8220;myfirstkohana/application/views/default_content.php&#8221;:</p>
<pre> &lt;body&gt;
  &lt;h1&gt;This is my second view&lt;/h1&gt;
  &lt;?php echo $content;?&gt;</pre>
<p>finally &#8220;myfirstkohana/application/views/default_footer.php&#8221;:</p>
<pre> &lt;/body&gt;
&lt;/html&gt;</pre>
<p>Above we taken a basic HTML page and split it up &#8220;logically&#8221; into a header, footer and a content section. Let open our controller to build out our more complex view.  Edit &#8220;myfirstkohana/application/controllers/hello.php&#8221; to make the index method look like this:</p>
<pre>  public function index()
   {
    $view                    = new View('default_template');
    $view-&gt;header            = new View('default_header');
    $view-&gt;content           = new View('default_content');
    $view-&gt;footer            = new View('default_footer');
    $view-&gt;header-&gt;pageTitle = 'I am on the top';
    $view-&gt;content-&gt;content  = 'Hello World!';

    $view-&gt;render(TRUE);
   }</pre>
<p>That wasn&#8217;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&#8217;s like working with multi-demential arrays in a sense.</p>
<p>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.</p>
<p>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 (&#8221;myfirstkohana/application/controllers/hello.php&#8221;).</p>
<pre>&lt;?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-&gt;name($method);
     }

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

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

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

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

    public function name($name)
     {
        $this-&gt;template-&gt;content-&gt;content = 'Hello ',$name,'!';
     }
 }</pre>
<p>Here we have defaulted our main template, so now we didn&#8217;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.</p>
<p>Stay tuned for the third part of our series and find out about models and working with external data!<br />
<a href="http://images.dealtaker.com/dealtaker/blog/kohana/dealtaker-kohana-2.zip">Click here to download the files</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dealtaker.com/blog/2009/05/21/kohana-php-23x-tutorial-part-ii/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Kohana PHP 2.3.x Tutorial Part 1</title>
		<link>http://www.dealtaker.com/blog/2009/04/23/kohana-php-23x-tutorial-part-1/</link>
		<comments>http://www.dealtaker.com/blog/2009/04/23/kohana-php-23x-tutorial-part-1/#comments</comments>
		<pubDate>Thu, 23 Apr 2009 15:22:25 +0000</pubDate>
		<dc:creator>ellisgl</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[controllers]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[install]]></category>
		<category><![CDATA[kohana]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.dealtaker.com/blog/?p=558</guid>
		<description><![CDATA[So after reading my article about frameworks, you might want to try one out. Today we are going start a series of tutorials on how to use the Kohana PHP framework beginning with how to install it and creating a controller.

Before we get into this tutorial, lets go over what will be required.

*AMP (Apache MySQL [...]]]></description>
			<content:encoded><![CDATA[<p>So after reading <a href="2009/02/10/frameworks-frameworks-frameworks/">my article about frameworks</a>, you might want to try one out. Today we are going start a series of tutorials on how to use the Kohana PHP framework beginning with how to install it and creating a controller.<br />
<span id="more-558"></span></p>
<p>Before we get into this tutorial, lets go over what will be required.</p>
<ul>
<li>*AMP (Apache MySQL PHP) install</li>
<li>Knowledge of PHP</li>
<li>Know what a frame work is (<a href="http://www.dealtaker.com/blog/2009/02/10/frameworks-frameworks-frameworks/">Framework Article</a>)</li>
<li>Know what MVC is (<a href="http://en.wikipedia.org/wiki/Model-view-controller">Wikipedia Entry</a>)</li>
</ul>
<p>Lets get started!<br />
Download:<br />
Load <a href="http://www.kohanaphp.com/">http://www.kohanaphp.com</a> in your favorite browser and click the <a href="http://www.kohanaphp.com/download">download link</a>. On this page, click the &#8220;<a href="http://www.kohanaphp.com/download?languages%5Ben_US%5D=en_US&amp;format=zip">Download Kohana!</a>&#8221; button. You should be prompted to save a file. Go a head and save the file some where. At the time of this writing, the version was at 2.3.2.</p>
<p>Install:<br />
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 &#8220;Kohana_v2.3.2&#8243; or something like that. Open that folder. Open a new window and open the root directory of your *AMP install. Since I&#8217;m using WAMP Server &#8211; mine is C:\wamp\www\. Next make a new folder in there named &#8220;myfirstkohana&#8221;. Copy the files from the &#8220;Kohana_v2.3.2&#8243; directory to the &#8220;myfirstkohana&#8221;.  Make sure your *AMP installation is up and running then point your browser to http://yourserver/myfirstkohana/ . You should have a screen stating that everything is &#8220;OK&#8221;.<br />
<img src="http://images.dealtaker.com/dealtaker/blog/kohana/kohana-1-1.png" alt="" /></p>
<p>If everything is &#8220;OK&#8221;, then remove or rename the &#8220;install.php&#8221; file in the &#8220;myfirstkohana&#8221; directory. Next we want to navigate into the application folder, then in the the config folder. Open the file named &#8220;config.php&#8221; in your favorite editor. There should be a line that reads: &#8220;$config['site_domain'] = &#8216;/kohana/&#8217;;&#8221; (Line 7 for me). We need to change the &#8220;/kohana/&#8221; part to reflect our install. So replace &#8220;/kohana/&#8221; with &#8220;/myfirstkohana/&#8221;. Also search for &#8220;$config['index_page'] = &#8216;index.php&#8217;;&#8221; and make the &#8220;index.php&#8221; part blank, so that line (Line 21 for me) should now read &#8220;$config['index_page'] = &#8221;;&#8221;.  Save that file.</p>
<p>Create a new document, cut and paste the following into it:</p>
<pre># Turn on URL rewriting
RewriteEngine On

# Put your installation directory here:
# If your URL is www.example.com/, use /
# If your URL is www.example.com/kohana/, use /kohana/
RewriteBase /myfirstkohana/

# Do not enable rewriting for files or directories that exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# For reuests that are not actual files or directories,
# Rewrite to index.php/URL
RewriteRule ^(.*)$ index.php/$1 [PT,L]</pre>
<p>Save this file in the &#8220;myfirstkohana&#8221; directory as &#8220;.htaccess&#8221;.</p>
<p>These changes will help with creating clean URLs that help with SEO efforts.</p>
<p>Reload the browser page and you should get something like this:<br />
<img src="http://images.dealtaker.com/dealtaker/blog/kohana/kohana-1-2.png" alt="" /></p>
<p>If everything looks good, then we have successfully installed Kohana PHP.  Now lets make it do stuff!</p>
<p>My first controller:<br />
Open a new document and put the following into it:</p>
<pre>&lt;?php
defined('SYSPATH') or die('No direct access allowed.');

class Hello_Controller extends Controller
 {
  public function index()
   {
    echo 'Hello World!';
   }
 }</pre>
<p>Save this in &#8220;myfirstkohana/application/controllers&#8221; as &#8220;hello.php&#8221;. Here&#8217;s a little explaination of what we did. The line &#8220;defined(&#8217;SYSPATH&#8217;) or die(&#8217;No direct access allowed.&#8217;);&#8221; basically prevents the file from being executed by itself. The next line &#8220;class Hello_Controller extends Controller&#8221; creates a class called &#8220;Hello_Controller&#8221; that extends the controller object. The rules to follow for creating controllers is as follows:</p>
<ul>
<li>Must reside in a controllers (sub-)directory</li>
<li>Controller filename must be lowercase, e.g. articles.php</li>
<li>Controller class must map to filename and capitalized, and must be appended with _Controller, e.g. Articles_Controller</li>
<li>Must have the Controller class as (grand)parent</li>
<li>Controller methods preceded by &#8216;_&#8217; (e.g. _do_something() ) cannot be called by the URI mapping</li>
</ul>
<p>stolen from: <a href="http://docs.kohanaphp.com/general/controllers">Kohana Docs</a></p>
<p>The first method, &#8220;index&#8221; is the default action. Pretty easy right? If you point your browser to &#8220;http://yourserver/myfirstkohana/hello/&#8221; you should see &#8220;Hello World!&#8221; on the screen now.</p>
<p>What if you wanted to exend the controller to do something else? Let add another method in the class that looks like:</p>
<pre>public function america()
 {
  echo 'Hello America!';
 }</pre>
<p>Now the hello.php should look like:</p>
<pre>&lt;?php
defined('SYSPATH') or die('No direct access allowed.');

class Hello_Controller extends Controller
 {
  public function index()
   {
    echo 'Hello World!';
   }

  public function america()
   {
    echo 'Hello America!';
   }
 }</pre>
<p>Save this and open &#8220;http://yourserver/hello/america/&#8221;. Notice that is now show &#8220;Hello America!&#8221; on the screen. That wasn&#8217;t too hard, but lets make this a little more dynamic with arguements. Make a new method that will look like this:</p>
<pre>public function name($name)
 {
  echo 'Hello ',$name,'!';
 }</pre>
<p>Load up &#8220;http://yourserver/hello/name/monkey&#8221; and you should see &#8220;Hello monkey!&#8221; on your screen. Pretty straight forward. Let make it even more &#8216;friendly&#8217;. Add this to the top of the class:</p>
<pre>public function __call($method, $arguments)
 {
  $this-&gt;name($method);
 }</pre>
<p>If we load up &#8220;http://yourserver/myfirstkohana/hello/MrGuy/&#8221; we should get the same thing as if we loaded &#8220;http://yourserver/myfirstkohana/hello/name/MrGuy/&#8221; which would be &#8220;Hello MrGuy!&#8221;.</p>
<p>That&#8217;s it for this lesson. Next time we&#8217;ll be looking over Views.<br />
<a href="http://images.dealtaker.com/dealtaker/blog/kohana/dealtaker-kohana-1.zip">Click here</a> to download the files and don&#8217;t forget to check out some <a title="Tech Deals" href="http://www.dealtaker.com/tech-deals.html">great computer and electronic deals</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dealtaker.com/blog/2009/04/23/kohana-php-23x-tutorial-part-1/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
