Develop professional web applications with Kohana

  Kohana 3.0 Beginner's Guide

Develop professional web applications with Kohana

Jason D. Straughan

  BIRMINGHAM - MUMBAI

  Kohana 3.0 Beginner's Guide

  Copyright © 2011 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: August 2011 Production Reference: 1180811 Published by Packt Publishing Ltd.

  Livery Place

  35 Livery Street Birmingham B3 2PB, UK

  ISBN 978-1-849512-40-4 www.packtpub.com Cover Image by Asher Wishkerman ( ) a.wishkerman@mpic.de

  Credits Author

  Project Coordinator

  Cover Work

  Adline Swetha Jesuthas

  Production Coordinator

  Nilesh Mohite

  Graphics

  Clyde Jenkins

  Proofreader

  Michelle Quadros

  Hemangini Bari

  Jason D. Straughan

  Indexer

  Ajay Shanker

  Technical Editor

  Chris Rodrigues

  Development Editor

  Tarun Singh

  Acquisition Editor

  Geert De Deckere Paul Liversidge

  Reviewers

  Adline Swetha Jesuthas About the Author Jason D. Straughan lives in the beautiful Texas Hill Country, where he builds web

  applications, writes, and spends time with his family. He began programming in grade school, developing professionally in the early 1990s, and has spent his career working in project management and software development. His passion for open source technologies and the Web experience has been a driving force in his appreciation for PHP and the Kohana framework. Jason spends his days as a software engineer at Live Oak 360, a custom application development company focused on complex solutions and unique social platforms. During his time at Live Oak 360 and its sister company, 44Doors, Jason has assisted with the development of two software-as-a-service products, BudURL and BearHug, in addition to several custom application platforms. He also provides consultation and training to a select number of private clients, and is a founding partner in Straughan Photography (SanAntonioWeddingPhotography.com) with his wife and managing partner, Chrystina. You can follow Jason's blog, and read more about Kohana and web-related topics at . www.JDStraughan.com

  Most of all, I would like to think my wife, Chrystina, and my son, Michael, for all their love and support. This book would never have become a reality had it not been for their patience and understanding during many evenings and weekends of writing.

  I would also like to thank: Dr. Ken Jones, not only for convincing me to use PHP in the first place, but also for always offering inspiration and wise counsel; James Zimmermann, who has provided constant encouragement and optimism during this endeavor; and David Salazar, who is always willing to talk about code, and for introducing me to Kohana many years ago. Throughout the course of the writing, Isaac Castillo acted as an enthusiastic and helpful tester, sometimes without even knowing it—thanks Isaac.

  The technical reviewers for this book have provided many valuable insights, enhancements, and suggestions that are reflected in the final draft. This group of reviewers had a significant impact on the final text, and I genuinely thank each and every one who contributed. Specifically, I would like to thank Geert De Deckere for his level of dedication to the project, and for being a great resource throughout the revision process.

  Last, but not least, I congratulate the Kohana development team and community for consistently producing an incredible framework. Without these dedicated and outstanding developers, there wouldn't be a Kohana framework for us to use, much less write about.

  About the Reviewers

Geert De Deckere is a web designer and developer living in Belgium. Mostly in the earlier

  years of Kohana, he was involved in the development of the framework. Also, he is the creator of . When he is not building websites or playing around http://kohanajobs.com/ with regular expressions, he enjoys cycling. His personal website can be found at http:// . geertdedeckere.be/ is a freelance ICT management consultant by day, and a web developer

  Paul Liversidge

  by night. As a consultant, his role is to turnaround ailing ICT departments through the innovative use of technology, adopting best practice processes, and addressing the most critical assets—the people. With a technical background in network and server design, project management expertise and business acumen gained from multiple business sectors, he brings a formidable breadth of experience to bear on any ICT issue. As a web developer, he's excited by all things shiny, such as jQuery, Kohana, and pushing PHP, MySQL, CSS, and HTML forward. A frequent contributor to open source products that struggles to balance the responsibilities of a wife, two kids, and a dog, with a mania for writing code. Paul is originally from Yorkshire in the UK, but now calls Vancouver, BC, Canada home.

  I'd like to thank my wife and kids for allowing me to steal some time from them to review this book and my poor despondent dog that lost out on his long walks in the park. I'd also like to say a big thank you to Woody Gilk (Shadowhand) for sharing Kohana with the wider community, and I hope that my own involvement in reviewing this book has helped to widen the usage of Kohana. www.PacktPub.com Support files, eBooks, discount offers and more

  You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at and as a print www.PacktPub.com book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details. service@packtpub.com At , you can also read a collection of free technical articles, sign up for a www.PacktPub.com range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.

  Why Subscribe? ‹ Fully searchable across every book published by Packt ‹ Copy & paste, print and bookmark content ‹ On demand and accessible via web browser

  Free Access for Packt account holders

  If you have an account with Packt at , you can use this to access www.PacktPub.com

  PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

  Table of Contents

Chapter 1: Getting Started

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  Table of Contents

Chapter 2: Using Views and Controllers

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  Table of Contents

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  Table of Contents

  

  

  

  

  

  

  

Chapt

  

  

  

  

  

  

  

  

  

  

Chapt

  

  

  

  

  

  Table of Contents

  

  

  

  

  

  

  

  

  

  

  

  

Chapt

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

Chapt

  

  

  

  

  

  Table of Contents

  

Chapter 9: Securing and Deploying Kohana 3 283 Securing our applications

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  

  Preface

  The Kohana framework for PHP 5 is a robust library for rapidly creating applications. No previous experience with Kohana, CodeIgniter, or MVC frameworks is assumed or needed to understand and use this book, and any previous experience will only assist you as we learn the Kohana framework from the ground up.

  Brief history of Kohana

  Before Kohana, there was CodeIgniter. Developed by EllisLab, and the driving force behind Expression Engine, CodeIgniter, gained huge popularity in the PHP community, especially among developers seeking MVC solutions for their growing needs.

  Eventually, CodeIgniter was forked to bring it up to speed with PHP 5, and Kohana was born. Kohana 2 relied on the open source community for its development, and quickly grew into a production-ready framework, used by developers all over the world.

  Kohana 3 is a completely rebuilt framework, utilizing a HMVC design pattern, and leveraging the power of PHP 5 like never before. Although Kohana 2 is still being supported, all new applications written with Kohana are recommended to use the Kohana 3 release to allow for a longer support cycle. Kohana 3 is not backwards compatible with Kohana 2 or CodeIgniter, and migration can be difficult. If you have experience with Kohana 2, and would like to see the differences in more details, and understand the process of moving from Kohana 2 to Kohana 3, please take at look at the

  Appendix: Upgrading from CodeIgniter and Kohana 2

  . This is also a good resource if you have a Kohana 2 application you want to migrate to the Kohana 3 platform.

  Preface Kohana's user guide and API reference

  Kohana ships with a complete user guide and API reference. In Chapter 1, we will install the framework with the user guide module, allowing us to browse the guide from within our application. The official guide is available on the Kohana website at http:// kohanaframework.org/guide/about.kohana

  The guide contains basic information about Kohana, installation, configuration, and tutorials. Most importantly, it includes the API reference, which allows easily us to explore and view the methods and properties of every class in the library see.

  As we build our applications, the guide expands to include our code, documentation, and help files. This can be quite a resource for developing large projects with multiple developers, revisiting old projects for which you need to refresh your memory, and making it generally easier to find your way around.

  It is a good idea to familiarize yourself with the documentation online, and spend some time looking over the pages and API Reference.

  Structure and patterns

  In order for Kohana to work properly, some basic patterns and coding conventions must be followed. You are encouraged to follow the Allman/BSD style that is consistent throughout the framework; however, not following exactly will not break your application. That being said, not following certain coding conventions will prevent Kohana from autoloading your files, and thereby breaking your application. Because Kohana embraces Convention over Configuration, the naming of your directories, files, and classes determine how (and if) they are automatically loaded into the framework. This is a great feature as we do not have to write a lot of or statements, and it eliminates the include() require() need for trying to find files before we can use them.

  Another advantage of using this convention is we can utilize Kohana's cascading filesystem, which allows us to easily extend and override lower-level classes. Essentially, this means we can put a class in a module, and use it directly. All we need to do to extend it in our application is to drop a file with the same name into our application directory structure, and we can begin extending and overloading the class. We will get into this in more detail in Chapter 3.

  To begin working with Kohana, there are a few very important rules you must know, and we will cover the rest of the nuances as we progress through the book. The main thing to know now is: all class names must adhere to the following conventions:

  ‹ All classes live in the directory, usually located in the application

  /classes/ directory or in a module.

  Preface

‹ Underscores ( _ ) represent directories, example: would be

  Controller_Foo located in . classes/controller/foo

  ‹ All class filenames and directory names must be lowercase.

  To get a more detailed look at the conventions and patterns used in Kohana, please visit: http://kohanaframework.org/guide/about.conventions . For more information and examples of Allman/BSD syntax, please visit http://en.wikipedia.org/wiki/

  Indent_style#Allman_style_.28bsd_in_Emacs.29

  HMVC in a nutshell

  Most modern PHP frameworks use, or at least offer, a Model View Controller (MVC) pattern for constructing and organizing your project. The advantages of using Object-Oriented Programming (OOP) were recognized with the release of PHP 5, and the development community quickly began finding ways to create more reusable, lightweight, and expandable code. The MVC pattern fits perfectly for web application development, allowing developers to create code once, and use it across multiple projects.

  The MVC design pattern allows presentation, data, and logic layers to all be coded separately and used together. Traditionally, MVCs use a front-controller to handle all requests, route and load a controller, and the render the output from a view. Hierarchical MVC (HMVC) takes this approach one step further. Much like AJAX allows web browsers to interact with the server without reloading the page, HMVC allows your server- side application to handle multiple requests without having to display a page every time. Where MVCs allow for one controller to be loaded and executed, the HMVC pattern loads a primary controller, and then allows requests to be created repeating the loop of routing and loading controllers, and allowing for even more requests. Although this can be confusing at first, it is actually quite powerful. Having full control over routing and requests gives developers a lot of flexibility and power when writing code. We will take a much deeper look at the HMVC structure in Kohana when we explore routing and request handling in Chapter 3.

  Models, Views, and Controllers

  Finding the right place for our code is important, especially as our application grows. Anyone who has ever worked on a project consisting of more than a few pages quickly realizes that code can become convoluted in no time, and good organization pays off. To keep our code clean and DRY (an acronym for Don't Repeat Yourself—a motto meaning write code once), we will use Models, Views, and Controllers to house our data logic, business logic, and presentation files.

  Preface ‹ CONTROLLERS – These are the driving force behind our applications. Our controllers

  are loaded immediately after the request, and will delegate data modeling to our models, and presentation duties to our views. Controllers are where we utilize our models and prepare our data for output.

  

‹ MODELS – Any external data that needs to be used by our application will live in a

  model. More often than not, models are used to interact with a database or other data store. We will store any methods necessary for creating, updating, reading, and deleting data from any data stores with which we interact.

  ‹

  VIEWS – Perhaps the easiest way to think of views is just to imagine HTML. These are the files where all of our markup will go, with minimal logic. View files should contain the least amount of PHP code of the three types, and should utilize PHP's alternative syntax for control structures when it is necessary to use server-side scripting. The above definitions are made with broad strokes, and I do not suggest they completely outline where and how to use each. In Chapter 2, we will take an in-depth look at Controllers and Views, and in Chapter 6 we use Models to interact with our database. For now, knowing the basic use for each of the MVC layers will give you an idea of how it all fits together.

  Alternative syntax

  It is not uncommon for HTML and PHP to be intermixed within the same document. In fact, many of us began web development by making very long files with PHP and HTML so mixed together, it was sometimes hard to tell them apart. Kohana allows us to keep our business logic in our controllers and models, and our markup in views. Although view files are used for presentation, and mainly consist of HTML code, we will need do have some PHP for dynamic content. Instead of using curly braces everywhere, making our code confusing to read, we will be using PHP's alternative syntax. You can read more about alternative syntax here: http:// php.net/manual/en/control-structures.alternative-syntax.php

  Routing and request overview

  As explained earlier, Kohana utilizes the HMVC design pattern, and allows us to create requests essentially anywhere within our applications. The request flow is the order in which files are loaded, starting with and moving throughout the framework, loading index.php essential files, processing the requests, and rendering any output. We will examine the request flow and routing systems throughly in Chapter 3, giving examples and analysis of the entire process.

  Preface What this book covers

  Chapter 1 , Getting Started, covers Kohana 3 installation—displaying the default welcome content and user guide for the framework.

Chapter 2 , Using Views and Controllers, will jump into using Kohana's controllers and views,

and make something more robust than a simple "hello, world" script. Chapter 3 , Routing and Request Handling, will talk about the way Kohana routes our

  requests, and how to use request handling and routing to make our applications more robust. We will also learn more about Kohana's cascading filesystem, the Heirarchy aspect of HMVC, and how Kohana works at runtime.

  Chapter 4 , Working with Helpers and Classes, will look at some of the helper and

  service-oriented classes provided in Kohana, and take a look at extending their functionality, and creating a few of our own.

  Chapter 5 , Installing and Configuring Modules, will cover how to extend Kohana's core

  functionality by implementing modules. We will be exploring the modules that ship with the framework, learn how to use third-party modules, and how to create modules of our own.

  

Chapter 6 , Interacting with the Database, will take a more detailed look at the Database and

ORM modules, their use, and a more in depth look at some of the official modules that use

  and rely on these very important modules. Working with databases has never been more fun and easy, and in this chapter, we will expand our case study website to make it work with dynamic data, user authentication, and related data.

  Chapter 7

  , Using the ORM and Auth Modules, will take an in-depth look at two modules that rely on the Database module to function: the ORM and the Auth modules. By implementing these modules in your projects, you can make working with data even easier and authorizing users a breeze.

  Chapter 8

  , Troubleshooting and Error Handling, will be covering troubleshooting and error handling, and we will be able to see how to detect and debug errors in our applications while adding the final touches to the case study site.

  

Chapter 9 , Securing and Deploying Kohana, will discuss methods to secure our applications,

and keep our code safe from attacks.

Appendix , Upgrading from CodeIgniter and Kohana 2, will look at migrating from an earlier

version of Kohana and CodeIgniter to the newest version of Kohana.

  Preface Who this book is for

  If you are a developer who understands PHP, has some experience with Object-Oriented Programming (OOP), and has a desire to harness the power of a Hierarchical Model-View- Controller (HMVC) framework, then this book is for you.

  Conventions In this book, you will find several headings appearing frequently.

  To give clear instructions of how to complete a procedure or task, we use:

  Time for action – heading 1.

  Action 1 2. Action 2 3. Action 3

  Instructions often need some extra explanation so that they make sense, so they are followed with:

  What just happened? This heading explains the working of tasks or instructions that you have just completed.

  You will also find some other learning aids in the book, including:

  Pop quiz – heading

  These are short multiple-choice questions intended to help you test your own understanding.

  Have a go hero – heading

  These set practical challenges and give you ideas for experimenting with what you have learned. You will also find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: "Because Kohana utilizes a front controller design pattern, the only application file that must be exposed is our file." index.php

  Preface

  A block of code is set as follows: foreach (ORM::factory('post', 1)->where('active', '=', 1)->author- >find_all() as $author) { echo $author->name . '<br />'; }

  When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: <div class="field">

   <?php $body = isset($value) ? $value : ''; ?> <?php echo Form::textareắcontent', $body); ?>

  </div> Any command-line input or output is written as follows:

  $ git clone https://github.com/kohana/kohana.git -b 3.0/master egotist New terms and important words are shown in bold. Words that you see on the screen,

  in menus or dialog boxes, for example, appear in the text like this: " By clicking the Edit Message link, you can now edit the message:".

  Warnings or important notes appear in a box like this.

  Tips and tricks appear like this.

  Reader feedback

  Feedback from our readers is always welcome. Let us know what you think about this book— what you liked or may have disliked. Reader feedback is important for us to develop titles out of which you really get the most. To send us general feedback, simply send an e-mail to , and feedback@packtpub.com mention the book title via the subject of your message.

  Preface

  If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on , or e-mail . www.packtpub.com suggest@packtpub.com

  If there is a in which that you have expertise, and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors .

  Customer support

  Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

  Downloading the example code for this book

  You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

  Errata

  Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code— we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting , selecting http://www.packtpub.com/support your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted, and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.

  . packtpub.com/support

  Piracy

  Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

  Please contact us at with a link to the suspected pirated copyright@packtpub.com material.

  We appreciate your help in protecting our authors, and our ability to bring you valuable content.

  Preface Questions

  You can contact us at questions@packtpub.com if you are having a problem with any aspect of the book, and we will do our best to address it.

  1 Getting Started To start using Kohana 3, you must first learn how to install and configure the framework.

  Here, you will learn how to install Kohana from the website and via the official Git repository, configure Kohana for development, and display the default welcome page. This chapter includes:

  ‹ System requirements ‹

  Installation from Kohana's website

  ‹

  Installing from Kohana's Git repository

  ‹

  Overview of Kohana's filesystem

  ‹

  Configuring the framework for a development environment

  ‹ Displaying your welcome page

  No previous experience or exposure to Kohana is required to follow the instructions and examples in this book. You will start off by setting up the framework from scratch, examine the necessary steps to configure Kohana, and apply your knowledge by building a real application.

  By the end of this chapter, you will have a full Kohana 3 installation displaying the default welcome content and user guide for the framework. So, let's get started!

  Getting Started System requirements

  The exact system requirements for Kohana are somewhat fluid, with newer versions of the framework requiring newer versions of PHP. The basic requirements are essentially the same: a newer version of PHP5, some common extensions, and a few optional extensions that allow Kohana to do more. My experience has been that most hosting providers, and out-of-the-box development servers (WAMP, MAMP, XAMPP, etc), come pretty well suited for Kohana right out of the box.

  At the time of writing, Kohana requires the following:

  ‹ PHP 5.2.3 or newer ‹

  PCRE with UTF-8 Support

  ‹ PHP SPL Enabled ‹

  PHP Reflection Enabled

  ‹ Filters Extension ‹ Iconv Extension ‹ Native MBString (not overloaded by extension) ‹ Character Type (CTYPE) Extension

  The following extensions are not required, however, they are recommended for full functionality. Through the course of this book, you will assume these extensions will be present: cURL, mcrypt, GD, and PDO. Again, most providers and development packages should work fine. Also, during installation, Kohana will check for all the required and optional extensions and let us know if anything is out of order. For more information, visit the Kohana website at http://kohanaframework.org

  Don't worry about getting too caught up with the system requirements. Everything that is required, even optionally, is open source and free, installed on most systems, and there is a lot of support out there. Let's move right along and prepare to get Kohana installed and running on your system.

  Case Study

  Throughout the course of this book, you will be creating a web application that will allow users to create simple profiles, post messages for their friends, and manage their public page. Because this site is for sample purposes, we will be concentrating on backend code, and not the HTML, CSS, and JavaScript that would normally go into a site scheduled for production. You will create a fully functioning application, and secure it for a production environment.

Chapter 1 Our sample application will be called "Egotist", and will encourage users to befriend each

  other and share details about their daily activities. They will be able to post comments, and see comments that are posted by their 'friends'. We will implement basic authorization, session handling, a database for your posts, users, and friendships, and do it all in Kohana.

  Downloading and installing from the Web

  Kohana's website hosts an archive of the latest releases http://kohanaframework.org/ in its download section. Here, you will also find user forums, documentation, and other releases of the framework.

  The website makes it very easy to obtain and install the most current stable release of Kohana, browse the documentation, and interact with the Kohana community.

  Time for action – Downloading from web

  Let's take a look at installing Kohana from their website: 1.

  Open http://kohanaframework.org/ in your web browser.

  2. Navigate to the download page and select the newest 3.0.x version marked Stable.

  3. Clicking the download link will retrieve a file named Kohana-3.X.X.zip (where X could be any number, representing the version of the framework).

  4. Create a web directory called egotist.

  5. Unzip the downloaded file into your egotist site folder on your development environment.

  A listing of your directory should contain the framework: /egotist/

  Getting Started What just happened?

  As you can see, you have unarchived Kohana into your webroot directory. Take note of the mark-down ( .md ) files, especially those labelled DEVELOPERS, TESTING, and README. It is recommended that you give these files a read. Also, notice the framework comes complete with index.php , a system folder, application folder, and modules folder.

  Although installing Kohana via the download archive is a quick and easy way of obtaining the framework, the code repository is hosted and maintained on GitHub ( http://github.

  ), and can be accessed and updated via this resource. If you would like to install Kohana com via GitHub, the next section is for you.

  Installing Kohana from GitHub

  In a nutshell, Git is a Distributed Version Control System (DVCS) or Source Code Management (SCM) tool written by Linus Torvalds originally designed for the Linux kernel developers. Its popularity, especially amongst open source developers, has grown considerably in recent years, for many reasons. Git provides developers with many features that make working with your code more convenient. Using Git, you can easily create and merge different branches, create forks of existing repositories, and issue pull requests for patches or upgrades made to forked projects. The distributed nature of Git allows every team member to keep the entire repository duplicated in their environment. GitHub is a storage solution for Git repositories, with free hosting for open source projects. Kohana uses GitHub for hosting, and you can get Kohana directly from GitHub.

  Installing Kohana via GitHub makes it easier to keep your application up to date with the most recent releases of both the Kohana 3 system files, but also any submodules that you may be using that are also hosted on GitHub. When you want to use one of hundreds of actively developed modules for Kohana, installing them using Git will be painless.

  To access repositories on GitHub, you must first have Git installed on your system. For more information on installing and using Git, please visit . Git is free and http://git-scm.com/ open-source, and is available for all popular operating systems. Most providers that offer secure shell access also offer Git.

  Time for action – downloading using Git

  The Kohana repository can be found at , where http://github.com/kohana/kohana you find the most current version of Kohana 3 in the 'trunk' of the repository. Git allows for tagging and branching of projects, and the Kohana team has done a very good job of tagging releases and creating branches for new release cycles.

Chapter 1 For your development project, you will simply use the most current stable release in the

  trunk of the master branch that contains the basic framework with official modules. This is easiest way to keep the current stable version of Kohana for your projects.

1. First, let's create a place to put your application. For the case study in this book,

  you will be creating a social networking application called Egotist. So, in your web directory, let's create a directory named . egotist 2.

  Now, you can run the following command to retrieve Kohana and place it in your egotist directory:

  $ git clone https://github.com/kohana/kohana.git -b 3.0/master egotist Git should retrieve the repository, and make a copy of it into your site directory.

  Remember to execute the command from within your or site root egotist directory.

  Getting Started 3.

  After the clone has completed, you can list the contents of your site root directory.

  It should contain all the Kohana files with a few files associated with Git and all the submodules in place for your system and modules directories.

  Included in the repo are some submodules, the 'official' modules sanctioned by the Kohana 3 development team to be included in the basic installation of the framework. The master Kohana repository keeps these submodule locations up to date. Right now these submodules have not downloaded any files to your system.

1. Download each of these repositories directly into your project, you will want to

  update these submodules by running the following:

  $ gitsubmodule init

Chapter 1 2. Now that you have let Git know about the submodules you want to install, you need to do an initial update to clone all the submodules into your install.

  $ gitsubmodule update

  The update may take a little while. Git will go through each submodule and download its newest stable release.

  What just happened?

  The Git clone available at https://github.com/kohana/kohana.git tells Git to clone, or to make an exact copy of, the repository located at https://github.com/kohana/

  , the second argument, tells GitHub which branch you want kohana.git –b 3.0/master to clone, and the final argument tells Git where to place the cloned repository, in this case the directory. egotist

  In the future, updating the codebase will be as simple as returning to the site root and running:

   $ git pull $ gitsubmodule update

  The first command will pull, or download, the newest content from GitHub in the master branch. The second command updates, or downloads, all the submodules you have installed for your project. Currently, you are only updating submodules that are included with the Kohana install. Later, in Chapter 5, you will be adding modules to your project, and some of these will be installed using Git. Once installed, they can be updated in a similar fashion.

  Advanced installation with Git

  By cloning the kohana.git repository, you got a copy of the entire repository that is meant to build the compressed files for download, and it is not really designed to be cloned into projects for use. The method described above is used by many beginners, but has some drawbacks. First, the repo is now pointed to / , not the repository you

  Kohana Kohana.git wish to use for your project. Secondly, it has all the commits for the files in the application path, where your files will eventually live for your project. Next, when you update your application, Git will want to merge the changes in your application directory with the repo.

  Lastly, you are tied to the directory structure that this repo subscribes to, making changes like we will explore later in the book harder, if not impossible.

  Getting Started

  Creating your project's directory structure and using existing repositories on GitHub as submodules will make your application more flexible, and easier to maintain. Although there are a few more steps involved here, the savings in the long run are enormous. If you are running a UNIX-compatible operating system, like Linux or Mac OS X, you can use an install a script written by Kohana's Benevolent Dictator for Life, Woody Gilk, aka shadowhand, which handles this process quite elegantly. The script, and instructions for use, can be found here:

  . https://github.com/shadowhand/kohana-installer

  If you prefer to set up your application environment by hand, you can create your directory structure, add the Kohana core repository ( ) to https://github.com/kohana/core your system directory, add all the modules you need to your path, create your modules application structure, bootstrap, and front controller. This provides you with the most flexibility and is the preferred method for most professional developers. For a full tutorial on installing Kohana in this manner, please visit: http://kohanaframework.org/3.0/ guide/kohana/tutorials/git Although you can use Git to manage the code for your project, we will leave Git behind here, and move forward with your Kohana project. For more information on Git, please visit http://git-scm.com .

  Now, your development directory has the Kohana 3 framework with the official submodules in place, ready for configuration. Before you dive into installation, let's make sure your environment is properly set up to handle Kohana 3.

  Taking inventory

  A quick look at the files you have downloaded reveals some files you are familiar with, and others that you may not be. You can see there is the standard file, some index.php mark-down files, a readme file, and 3 sub-directories: application, modules, and system.

  One of the nice things about Kohana is that it comes with the file structure and core files necessary to get your project up and running very quickly. We will explore Kohana's routing a bit more later on, but it is important to know that index.php will be the first file loaded by the framework. The index file will create the necessary configurations and definitions to run Kohana, and then bootstrap the application by loading application/bootstrap.php . You will be working with bootstrap.php very soon when you begin configuring Kohana for first use.

Chapter 1 The application directory is where the majority of your code will live. This is where you will

  create your application's controllers, models, config files, and views. You will also keep your logs and various other items here, well-organized, and easy to access and update. Unlike previous versions of Kohana and CodeIgniter, all of the classes for your app (Controllers, Helpers, Models, etc) will live in the application/classes directory, in their respective sub-directories ( , , application/classes/model application/classes/controller etc). You may remember that helper classes in previous versions of the framework had their own designated place to live, and now simply reside in , and are application/classes not designated has 'helpers'.

  The system folder houses the core files for Kohana, and although you are free to override any file in the library, you are discouraged from changing the contents of any files in the system directory. If you need to make changes to the Kohana system, you can do so by extending and overriding classes in the framework. We will cover this in more detail when you explore routing and requests in Chapter 3. Any modules you install or create will be stored in the modules folder. Kohana comes with some modules bundled with the distribution, like the user-guide, database, oAuth, and others. There are hundreds of modules available from other developers online, and we will learn how to create your own modules in Chapter 5. Although these modules ship with the framework, they are not enabled by default. We will cover how these modules are activated and used later in the book.

  Preparing the Filesystem

  In order for Kohana to work properly, it must have the ability to write cache and log files to the filesystem. By default, the framework uses for caching, and application/cache for its log files. You can change these locations in the or application/logs index.php files, however, the default location is just fine for your needs. application/bootstrap.php To make these directories writeable, you will need to change their permissions. Using a Linux system, you can accomplish this using the command. On a Windows system, you chmod need to make sure the folder is writeable by your web server.

  Make sure you are in your site directory, in your case /egotist/.

  $ chmod -R 777 application/cache $ chmod -R 777 application/logs

  Getting Started