6 entries in PHP

Comment Headings

Enable easy navigation of code using GIANT comments made up of block characters

Friday, November 14th, 2008

When navigating through large classes, it can be a real pain to find certain bits of code if you don't have a good IDE. As I often work in Flash IDE and DreamWeaver IDE, I have to rely on comment blocks here and there, with lots of - - - - - - - - - - delimiters, etc. which is an OK start.

However, I saw the PaperVision 3D classes had moved on a step from this, and had rather nice blocks at the top of each script with their logo, made out of characters. Why not extend this idea and actually build a small Flash application to let me build dirty-great big words that I can use in my scripts for navigation purposes?

Comment Headings

Edit the text in the left-hand text box to update the text in the right, then click Copy Text to copy the headings directly to the clipboard so you can paste to your IDE.

Note:Comment Headings works only with mono-spaced fonts! Mac users - you might have to experiment to find the best one.

Firefox 3 users: due to FF3's mono-spaced font tracking, the characters below may not display correctly, but rest-assured that in the final downloadable utility, and your IDE, the headings will appear just fine.

Demonstration

To demonstrate the differences between a comment-headered file and a normal file, compare the following two files, and see how much easier it is to skim through the one with larger comment headings.

Options

The following options are available to customize your headings:

  • Font - Choose from 12 available fonts of varying sizes and styles
  • Block - Various characters to create the block comments themselves
  • Comment - Various leading-comment styles to suit different languages
  • Delimiter - Various delimiter characters for the

Presets

If you change programming languages / tasks regularly, you can save time by storing oft-used combinations as presets. For example:

  • Input presets - Your most common heading text combinations
  • Output presets - Your most common settings for each language / editor / etc

Presets can be quickly called up by selecting them from the dropdown lists, which automatically updates related dropdowns as well as the output text.

Both Input Templates and Output Settings are stored in an editable text file, presets.xml, which is well-commented, allowing you to add or delete settings to suit your workflow.

To have the utility start with your chosen presets, for example having the MaxScript headings always open, just ensure its entry is first in the input list.

Customization

Once tinkering in the presets file, the following elements are configurable:

  • Comments - Choose the leading comments (//, --, etc) according to programming language
  • Blocks - Choose which characters you want to physically build the words from
  • Delimiters - Choose which characters you want to use to delineate each comment block
  • Fonts - Choose from any of 12 fonts to be available

3dsmax users

In order to display the full-block style of comments, you will need to set up the SCiTE editor to use the extended Unicode character set. To do so, you will need to add the following lines to your User Preferences file:

code.page = 65001
character.set = 204

Obviously this is only applicable if you are using 3dsmax 2008 or above.

Download

Kohana: Default controller for serving static pages

Save development time by routing un-routable content to default views

Thursday, September 11th, 2008

A brief overview of the problem

A framework such as Kohana is really useful when serving lots of dynamic pages, as it allows you organise both your thoughts and your code into folders, creating order from what could potentially be chaos, at the expense of having to adhere to a structured way of working, in this case setting up controllers and methods that are correctly mapped from URLs (routes).

Whilst this is necessary for dynamic pages that need access to models, helpers and such like, for static pages that literally just need to be output to the browser, it's quite a lot of overhead, and your controllers can very quickly end up bloated with itty-bitty "view this page" methods.

What would be great would be some magic method to automatically handle static pages, without having to set up an actual controller and method, that way all you really need to create is the view file, and you leave your controllers folder nice and lean.

Note: this tutorial is for Kohana 2.2. I haven't investigated how it will work with 2.3 and the routing yet. Please comment if you have something to add!

The Fallback controller

The solution is using a default or "fallback" controller that takes care of serving views from routes that don't map to an existing controller and method.

Essentially, this new controller kicks in just after the routing has drawn a blank, locates the appropriate view file, then serves it - instead of serving a 404 page.

Step-by-step

Let's a take a look at how this works in a step-by-step approach from Kohana's perspective. Don't worry - it's actually pretty simple, I've just mapped it out specifically so you can see what's happening every step of the way.

Let's start with a route

  • The user navigates to a route, lets say /about/company/history
  • Kohana looks for
    • an about controller, with
    • a company method, and intends to supply it with
    • a history argument

Here's the thing though, because we did't want the hassle of setting up ALL our controllers with methods just to load views, our about controller doesn't have a company method! So what is Kohana to do?

Let's load the Fallback Controller!
Well, normally, a 404 page would be served, but using the magic of hooks, we're going to give Kohana one last chance to do something before serving that horrid 404 page.

So:

  • The system.post_routing hook kicks in, and due to the way we've set up the hook file
  • It loads our Fallback controller, which is designed to do something useful with the route before bombing out.

Let's have the Fallback Controller do it's stuff and find the view!
In this case, we want it to attempt to find a view, so:

  • The Fallback controller builds a path from the arguments /about that will (hopefully) map to a view, in this case views/main/about.php, then
  • Attempts to find this view using Kohana::find_file, and
    • if found - loads the view!
    • if not found - serves the 404 page

Summary

Pretty useful, huh? Basically all that happened is

  • Kohana couldn't find a controller, so loaded a Fallback controller
  • The fallback controller took the route and found a view
  • Kohana loads the view (or the 404 page if the view didn't exist)

OK, perhaps it's time to look at some code

Code

You will need to create or edit code in 3 separate places:

  1. Enable hooks in your application's configuration file
  2. Create a hook file which tells Kohana what to do in the system.post_routing event
  3. Create the actual Fallback Controller that will do the finding and loading of your view files

.

application/config/config.php - Enable hooks in the main config file...

$config['enable_hooks'] = TRUE;

.

application/hooks/fallback_page.php - Add a hook file to the hooks directory...

Event::add('system.post_routing' ,'call_fallback_page');

function call_fallback_page()
{
    if (Router::$controller === NULL)
    {
        Router::$controller = 'fallback_page';
        Router::$arguments = Router::$segments;
        Router::$controller_path = APPPATH.'controllers/fallback_page.php';
    }
}

.

application/controllers/fallback_page.php - Set up a controller to do the business

class Fallback_Page_Controller extends Page_Controller // page controller is my standard page template
{

    public function __construct()
    {

    // the constructor can be omitted if you're not doing anything special,
    // as the parent constructor it is called automatically
        parent::__construct();
    }

    public function __call($function, $arguments)
    {

    // search for a view, and load it if it exists
    // it's up to you how you handle the mapping of arguments to folders here!
        $route =  implode('/', $arguments);
        if(Kohana::find_file('views/main', $route))
        {
            $this->template->content = new View('main/'.$route);
        }

    // display alternative content if not found
        else
        {
            $view = new View('common/404');
            $view->info = array($function, $arguments);
            $this->template->content = $view;
        }
    }

}

Conculsion

So now you should be able to set up a bunch of views, but needn't worry about building controllers for them if nothing exciting is happening.

The fallback controller will run, will attempt to find a matching view, and if found, will echo it the page. The main thing is - it keeps your controllers folder and classes nice and lean, and you only need to build controllers that actually DO any controlling!

Nice.

Kohana ‘filesystem’ Helper

A robust helper to handle everything file and folder-related within Kohana

Wednesday, August 20th, 2008

Kohana is just an excellent framework to work with, but one of my beefs is that the structure of its bundled libraries and helpers is a little haphazard, missing basic functions you'd expect to find in the core (so you can rely on them when writing modules) omitted!

For this reason, here's my attempt at a more integrated helper class. It's somewhat of a Frankenstein's monster with bits borrowed from Code Igniter, and my own code thrown in as well. Apart from this, it:

  • Adds a few new methods
  • Improves on some existing methods
  • Combines the 'download' helper functionality
  • Tidies up various method calls

The methods are:

  • map()
  • get_folders()
  • get_files()
  • delete_files()
  • read_file()
  • write_file()
  • make_path()
  • download()

Download filesystem.php here.

(more...)

I love CodeIgniter!

A brief introduction to the wonderful PHP CodeIgniter framework

Monday, June 30th, 2008

I don't normally write a post unless I'm specifically publishing code, but I wanted to write a brief post about Code Igniter as it's the best damn thing I've discovered since jQuery!

Overview

If you haven't heard of it already, CodeIgniter is a rapid application-development framework for PHP that uses the Model-View-Controller pattern to separate the presentation, logic and data from each other whilst building your web application.

What this means in practice is that instead of building one large linear PHP file that...

  1. Contains swathes of PHP in the head to filter user input (logic), then
  2. Gets results from a database (data) and does something meaningful with them, then finally
  3. Outputs the HTML (presentation) and continues to escape in and out of PHP during the process

...you end up working on many different smaller files that do one task only, with which the framework pieces together for you to deliver finished web pages.

However, before I delve into MVC, I want to touch upon CodeIgniters excellent class library.

A excellent and fully-integrated set of Library classes

The primary reason I started using CodeIgniter in the first place, is that it provides an incredibly robust and integrated set of classes to handle everything web-app related, from database classes, to session classes, to file uploading and email.

Had it not been for the fact that you have to use them within the overall CodeIgniter structure, I may well have gone off and carried on the way I was going, with logic at the top of my pages, and presentation at the bottom.

However, in order to actually use them, you have to accept you'll start coding within the CodeIgniter framework, and things will never be the same again...

An intelligent and modular approach to building web applications

The vast majority of what you do within CodeIgniter will be written within class files, that will fall under one of the three MVC areas:

  1. Controllers - classes responsible for making overall decisions, such as deciding what task is being undertaken in response to user-input, as well as loading supporting classes and logic to get the job done. Controllers are the first step in processing a task, and outputting a web page.

    It helps to think of controllers and their methods as the "folder" and "page" structure of a site. For example a "Home Controller" might have an "index" function would handle loading the home page, whilst a "Messaging Controller" and might have a "List" and "Compose" methods would handle listing messages, composing new messages, etc.

    Both these methods would take high-level decisions about the task in hand, offloading the drudgery of the tasks to other elements, such as...

  2. Models - classes responsible for everything "data" related, such as read and writing from databases, storing representations of said data, configuration, etc.

    In practice, what this means is that a Controller would never read or write data directly, it would hand all responsibility for that to a Model, and would just make calls such as "get the last 10 unread messages". The model would do the grunt-work, leaving the Controller to get on with more important things.

  3. Views - static or dynamic files that are read by CodeIgniter, populated with data, and are output to the user. Views are analogous with the final page output you'd see in procedural PHP programming.

    A view file need not be an entire web page, it could just be a segment, such as a sidebar, a form, a graph, a header, or a footer. By combining views, you have a lot of power with regards to the output of the final page, as well as a really flexible way to store individual representations of data.

    For example, depending on user input, you could load either a Table View or a Graph View that would be populated by the Model data. Inside the view you'd have written code that would receive Model data and would know what to do with it.

The benefit of this approach is that it's much easier and quicker to build and maintain your site, as everything's modular, and can be loaded and swapped out according to the task at hand (and no more huge sprawling pages).

There aren't really that many downsides to this approach, but it can be a little tricky sometimes, as due to the way CodeIgniter works behind teh scenes, you don't work with a traditional one-to-one file / page structure, but once you're used to it, you'll never want to go back.

Flash “PHPLoadVars” class

Natively send complex / multidimensional variables from Flash to PHP with this extended LoadVars class

Thursday, February 28th, 2008

I was pitching in on a forum thread Send an object to a php script the other day and some chap wanted to send complex objects to PHP using LoadVars. "Can't be done!" was the reply.

Oh yeah? Well if PHP can deserialize array variables from HTML forms, I don't see why we can't do the same with Flash.

Well it took about 15 minutes to work up a rough proof-of-concept that worked for GETs only, but it got me thinking to do something nice with:

  • a proper class
  • that works with POST (so you can send BIG objects!)
  • and has a recursive serialization routine (so you just give it any nested data-structure, and it chews through all of it)

PHPLoadVars (also works with Ruby)

Well it couldn't be simpler, really. Just create a new PHPLoadVars object, ask it to serialize your data, and send:

var data :Object      = {data:[1,2,{sub_object:{name:'Dave',age:33,gender:'male'}},3,4,5]}
var lv	 :LoadVars    = new PHPLoadVars();
lv.serialize(data)
lv.send('process.php')

Then PHP receives the complex variables natively like so (a quick print_r($_POST); shows the results):

Array
(
    [data] => Array
        (
            [0] => 1
            [1] => 2
            [2] => Array
                (
                    [sub_object] => Array
                        (
                            [gender] => male
                            [age] => 33
                            [name] => Dave
                        )

                )

            [3] => 3
            [4] => 4
            [5] => 5
        )

)

Just to be absolutely clear - this result isn't manually de-serialized, or run through any processing routines - PHP automatically reads in data serialized using square brackets (which is how things were serialized in Flash) as numeric or associative arrays, so your data is literally ready to go as soon as the headers have been processed!

And you can make your data-structure as deep as you like...

Could it be any easier!? No. It couldn't! Not even XML is this easy!

Download

Download the class file, sample .fla, and a basic PHP file to echo the variables to screen.

LoadPHPVars.zip

Wordpress “Page Redirect” template

Have any page in the Wordpress "Pages" list invisibly redirect to a static page or other url

Wednesday, February 20th, 2008

The very nature of Wordpress demands that you work within it's infrastructure in order to maintain flexibility. Sometimes, though, the structure of your pages demand that you need to operate outside of this constraint.

This template lets you specify a single URL as the page content, then as the page loads, the template automatically redirects the page to this new location.

Usage

Once you've uploaded the template-redirect.php file to your themes directory...

1 - Create a new Page in your Wordpress control panel

2 - In the Page Content panel, just enter the URL (or local path) you want to redirect to:

3 - Set the Page Template dropdown to "Page Redirect":

That's it!

Examples

Examples of URLS might be:

  • category/flowers (a relative link to the permalink for "flowers")
  • ../page.html (a page outside of a Wordpress subfolder (the WP folder being /blog/) but still in your site)
  • http://www.davestewart.co.uk/resources/ (a page on a completely different site)

The "Latest developments…" page in my sidebar automatically redirects to /category/development/ - or in other words, the archive for my "Development" category, as my home page is not the standard "last-post first" format.

Download

template-redirect.zip