Writing a module for Kohana3

December 20, 2010 No comments yet

In this tutorial we will cover how to build a module from scratch in Kohana 3. If you aren’t familiar with the Kohana framework then I recommend you read the beginners introduction to Kohana.

The Plan

We will be building a module that replaces Kohana’s own view layer (Kohana_View). It will use the PHP template library Twig. We want our own view layer to be API compatible with Kohana’s view layer. This will ensure that other modules work out of the box and that the only code the developer will need to alter in their application are the templates (so that they are Twig compatible). No code in any controller will need to be modified.

Because Kohana follows HMVC (see beginners introduction to Kohana) we will be calling our class View. This means that all calls in the application to the class of View will be to the View class in our module, not Kohana’s own View class.

Directory Structure

Enabling The Module

The name of any Kohana module is the same name as the directory inside the modules directory. So in this case it is twig. To activate any module, we must add it…

An Introduction to Kohana3 PHP Framework

December 12, 2010 No comments yet

This is a brief introduction into the Kohana framework. The next two tutorials will cover how to build a blog in Kohana.

Installation

Installing Kohana is very straight forward, just download the latest stable version of Kohana and unzip it. No need to mess around with yaml or xml files like other frameworks. Navigating to the directory on your web server should give you a page similar to…

Filesystem

The filesystem plays a big part in the operation of the Kohana framework. Kohana follows the HMVC pattern (hierarchical model view controller). This means that the same filesystem structure exists at multiple locations in the framework. The following directories exist in the application, system and in all module directories:

  • classes
  • config
  • i18n
  • messages
  • tests

When calling a class in Kohana, the autoloader checks if the class exists first in application/classes/ , then in each of the installed modules, classes subdirectory and finally in system/classes/. If the file cannot be found then an exception is thrown. Kohana follows the Zend_Class_Naming style. For example, if you instantiated a class named Hello_World, Kohana would look at each of the following locations in this order. If it finds that…

Writing an Event System in PHP

March 6, 2010 2 comments

In this tutorial you will learn how to create and implement an event system in PHP. You will be able to integrate it with your own web application or framework.

What is an event system?

An event system is a way to call prefined functions at a specified time in your application code. It’s main use is to allow developers to add functionality to your code without modifying the original source. Directly editing the source code of an application is proven not to work because every time the software gets updated, the changes made to the source get overwritten. By offering an event system in your application developers will be able to write plugin style code which will get executed at a specified time in the main application code. This makes your platform easier to develop for and offers a low entry level for coders wanting to add functionality themselves.

Overview of the system

event::$events is a static variable (array) which holds all of the registered events and associated Closure objects.

event::register(‘eventName’, function($args){}) accepts two arguments. The first being the name of the event and the second being a Closure object which will be called when the event is fired.…

Preventing CSRF in PHP

February 16, 2010 No comments yet

Cross site request forgery (CSRF) is where a malicious website will attempt to issue actions on another website without the user’s knowledge of it occuring.

Hypothetical Situation: You had just done some online banking and had ticked the ‘Remember me’ option when you logged in. The banking website easily allows you to transfer money to other people. While browsing the malicious site you see a link that seems to take you somewhere harmless but it actually sends you to www.my.bank/transfer?to=3740384342?amount=99999 . Because you ticked ‘remember me’ you are automatically logged in and the bank goes ahead and transfers the funds.

There are some obvious fundamental issues the bank could address such as checking with the user whether they want to send the funds and masking their URLs but the problem of the form still remains. Theres nothing from stopping anyone sending seemingly valid data to the URL the form submits to. This problem is known as Cross Site Request Forgery (CSRF) and it is a potential problem in every single dynamic website. While stealing money is an extreme example, CSRF could also be used to steal cookies from a website or post spammy comments on a blog without the user…

PHP in Action – Objects, Design, Agility

January 31, 2010 1 comment

Book Review

PHP in Action is a book aimed at people who are comfortable coding procedural or object orientated PHP scripts. It doesn’t teach you what a variable is or what function to use if you want to connect to a database but it does teach you design patterns, best practice techniques and useful information about PHP5′s object system. If you are looking into writing a PHP framework or want to further understand design patterns and objects in PHP then I highly recommend this book. It’s written by prominent members of the PHP community – Dagfinn Reiersol, Marcus Baker and Chris Shiflett and is 525 pages long.

Overview of the book

Chapters 2,3,4 cover the PHP5 class system. The book offers detailed and useful examples of each of the topics as well as plenty of metaphors to help the reader understand exactly what each feature should do and is capable of doing. I found this contrasted greatly with the almost minimal explanations and examples offered by the official documentation on php.net. The following features are covered:

  • Magic Methods – __get(), __set(), __construct(), __autoload()
  • Exception handling
  • Error handling

PHP Namespaces

January 8, 2010 No comments yet

Namespaces were introduced into PHP from version 5.3 onwards. They allow the developer to seperate their code into modules or groups which inturn makes the code easier to read. Namespaces prevent class and function name conflicts, it allows you to have numerous classes with the same name, as long as they are in different namespaces. Namespaces also make the old Zend/PEAR style of class name redundant (Framework_Database_Mysql_Query) because there will no longer be any class name conflicts.

Note: throughout the tutorial we will use the hypothetical files.

/Framework/Database/Mysql/Query.php
/lib/myClass.php
/index.php

The Basics

To declare a namespace you simply use the namespace keyword followed by the name of your namespace. You can specify sub namespaces by using the backslash ( \ ). Best practices state that your namespace path should match the directory path. For example the file /Framework/Database/Mysql/Query.php should have the namespace Framework\Database\Mysql and the name of the class should be Query. You should have one namespace and class per file.

Using Namespaces

In /lib/myClass.php we declare a namespace, lib, and then define a simple class, myClass. In our index.php file we include the class and instantiate it. Because myClass is in the namespace lib, we must refer to…

PHP cURL

December 22, 2009 No comments yet

cURL is a library written in C that enables easy transfer of data in many different protocols including FTP, FTPS, HTTP, TELNET and LDAP. cURL does more than simply download a file. You can store cookies, upload files, use various types of authentication and tunnel all requests through a proxy. The cURL extension has been bundled with PHP since version 4.0.2 and is enabled by default in php.ini. In this tutorial we will look at the uses of cURL and how it compares to file_get_contents() , we will then write a cURL class which we can use to download the source code of a webpage and download a binary file.

cURL vs file_get_contents()

Many PHP scripts require the user to download and then parse the HTML source of a page. When people ask how to do this, the most common reply is to use the file_get_contents() function as it’s a simple one line solution – you just need to set the first argument to webpage you want to download and it will return the source code of it. While it may seem very easy to use, it has many pitfalls.

  1. cURL is significantly faster than file_get_contents() at retrieving the

PHP Regular expresssion URL Router

June 23, 2009 No comments yet

In this tutorial we will create a PHP URL router. The developer using the router will be able to define these routes with regular expressions, these will then map to a file, class and method which will be called – very similar to Django’s routing. By using regular expressions to define our URLs we get maximum customizability. /class/method/ based URL routing is too restrictive sometimes. We will assume the user is using an apache or similar web server with mod_rewite enabled. You can adapt this router and use it in your web application or framework.

Quick Note: This is taken straight out of one of my applications. I have a singleton registry object called $core which you’ll see referenced many times. I suggest you make your own or use global variables.

.htaccess

First of all we need to create a .htaccess file in the root directory of your project. We turn the RewriteEngine on, and then declare a rule to route everything except images/js/css through our index.php file. So even if the person goes to www.yoursite.com/directory/file.php , rather than executing that file it will execute our index.php instead.

RewriteEngine on
RewriteRule !\.(js|ico|txt|gif|jpg|png|css)$ index.php

If your building a framework or application…

PHP Autoload

May 30, 2009 No comments yet

In large PHP applications you typically see a “classes” directory that only contains classes which are used throughout the application (database, session management, forms etc..). A problem quickly appears: Everytime you wanted to use one of the classes, you would be forced to include() it at the top of the page. __autoload() solves this by automatically including the definition file when a class is called.

Example

We have a simple application with the index.php file in the root directory and a directory called classes that contains numerous classes.
classes/time.class.php

class time
{
	function fn1()
	{
		echo 'hello world';
	}
}

The code below shows what we’d need to do if we didn’t have autoload. While that code doesn’t seem so bad, imagine writing includes on each of your 30-40 files. It would get messy and very hard to maintain. Another option would be to have a single file that all of your classes are included in, there include that one file in each of your functional scripts but you could expect a performance loss as every one of your classes would be included on the page – even if it wasn’t needed.

index.php

include('classes/time.class.php');

$time = new

Easy RSS Consumption with Simple Pie in PHP

February 1, 2009 Comments Off

Introduction

RSS Feed consumption has always been a stick point in PHP. Simple Pie is a library that works with both PHP4 and PHP5 that enables you to easily parse and save RSS feeds. Today I’ll show you some common uses of Simple Pie and explain how it runs.

Simple Pie requires:

  • PHP 4.3.0 or higher
  • cURL Enabled.
  • zLib (Caching?)

As well as a few other PHP modules that will be enabled in a vanilla PHP install. To run the compatibility test, upload the un-compressed archive to your server and navigate to www.yourname.com/pathtosimplepie/compatibility_test/sp_compatibility_test.php .

Finding the RSS Feed

The first thing we need to do is include SimplePie and then make a new SimplePie feed.

include('path/to/simplepie.inc');
$feed = new SimplePie('lastkarrde.com');

Simple Pie has a very useful ‘auto feed discovery’ feature. If you give it a plain URL, such as Query7.com, it will automatically find the RSS feed. Of course you can specify the path to the .xml file or Feed Burner page if you wanted to. Although the feed has been pulled we need to do call on another function, handle_content_type, to ensure that the feed has the correct mime type and encoding.

$feed->handle_content_type();

Parsing the RSS Feed


Categories