Flex 3 Modules -> What are they for?

In a recent project, I attempted to implement a flex interface to an e-learning application.  The basics of the application are as follows:

  1. Video game style e-learning application for a medical school.
  2. Administrative game scenario builder and cms

I thought I would use Flex Modules:

  1. Main Application – handles authentication and main navigation
    1. Admin Module
      1. Users Admin Module
      2. Foo Admin Module
      3. Bar Admin Module
    2. Game Module

This seemed logical today. I could load the modules and unload them as needed. This way I could have one application and all the resources available, but never loading all the overhead unless I needed it. That way, if I just looked on to do the Game, I would only use those resources and not have all the memory being used by the admin features.
I was wrong. Modules do not work that way. You can not load a module that registers any events, or many other common memory allocating tasks, and unload them to release the memory. Flex holds onto many instances which cause a number of problems, many of which are outlined here: Alexs Flex Closet.

Furthermore, If you try to use a class in a loaded module that hasn’t been registered by the main application, you must go to the main application and register it, otherwise you get an error on things like Lists, ComboBoxes.  This is not a lot of additional work but, to me, doesn’t seem like the way a module should work.

If I can’t load and unload modules without incurring memory leaks or errors, what good are modules.

Adobe, please fix this.  It is far more important than all the time/money you are spending making Data Intensive Web Apps accessible for Designers.  Just make it work for developers first, PLEASE, or we will find another technology to use.

Kohana v3 :: Routes Basics

I have found the routing in Kohana to be one of the most helpful and easiest features with wich to work.  In this tutorial I will show you how to use Routes to organize your Public site with your Back-End or Admin section of your site.

Step 1 :  Controllers

To help us organize our Admin and Public Controllers we create two folders:

  1. application/classes/controller/admin
  2. application/classes/controller/public

Using this folder structure will determine your class names, for example an Admin Users Controller like this:


class Controller_Admin_Users extends Controller_Template
{
/// class code
}

To access this controller you would need a url like:   www.mysite.com/admin_users/login

but who wants that ugly thing.  It would be much nicer to have :  www.mysite.com/admin/users

and we can easily achieve that with Routes.

Step 2

Open the file application/boostrap.php and look for the Route section, which should have something like this:


Route::set('default', '(<controller>(/<action>(/<id>)))')
->defaults(array(
'controller' => 'welcome',
'action'     => 'index',
));

This is the default route, so we are going to leave it alone for now and place all of our other Routes above it.

Step 3

We need to create and initial route for the admin home or welcome page. For this example, I’ll use a Home Controller located at  application/classes/controller/admin/home.php.  That is where I want people to go when they type  www.mysite.com/admin.  I do this by adding this route:

Route::set('admin', 'admin')
->defaults(array(
'controller' => 'admin_home',
'action'     => 'index',
));

Step 4

When someone simply trys to access the root of the site (www.mysite.com), I want them to go to the public home controller located at application/classes/controller/public/home.php.  So I just modify the Route that was there when I first intalled Kohana to this:

Route::set('default', '(<controller>(/<action>(/<id>)))')
->defaults(array(
'controller' => 'public_home',
'action'     => 'index',
));

Step 5

Now I want to add a route for that Admin Users controller located at application/classes/controller/admin/users.php, but I want that controller to have other Actions than just the index action, and I want to pass a variable in the url, so I simple do this:

Route::set('admin/users', 'admin/users(/<action>(/<id>))')
->defaults(array(
'controller' => 'admin_users',
'action'     => 'index',
));

And in that you have a model to build the rest of your controllers on..

Kohana v3 :: Custom 404 Page

A best practice for a web app/site in “production” is have an error page that looks like its part of your website – kind of a friendly error page. With Kohana v3 this is fairly easy to do, and only requires one new file, and a modification to one other file.

Note: This solution was found in the Kohana Forums.

Step 1 : application/boostrap.php

Define ‘IN_PRODUCTION’ in the Environment Setup Section


define('IN_PRODUCTION', true);

Catch the Exception coming from any invalid Request

After you define all your Routes, Kohana executes the request, sends the headers and renders the view. If you haven’t already made changes, it looks like this:


echo Request::instance()
->execute()
->send_headers()
->response;

Here is the replacement you should make, with comments to explain:

// Instantiate your Request object
$request = Request::instance();
// The give it a try, to see if its a valid request
try
{
$request->execute();
}
catch (Exception $e) // if its not valid, it gets caught here
{
if (! IN_PRODUCTION) // if this is Development, its displays the error
{
throw $e;
}
// if its IN_PRODUCTION, it does the following:
// Logs the error
Kohana::$log->add(Kohana::ERROR, Kohana::exception_text($e));
// Marks the status as 404
$request->status = 404;
// Renders the View for your CUSTOM 404 of your choice
$request->response = View::factory('public/templates/main') //your view may be different
->set('title', '404')
->set('content', View::factory('errors/404')); //again, your view may be different
}
// then continues on with the request process to display your custom 404 page
$request->send_headers()->response;
echo $request->response;

Step 2 : Create A Custom Error View

Create a new folder in your views folder called “Kohana”

Create a file in that folder called “error.php”

Whatever you put in your application/views/Kohana/error.php file will take precedents over Kohana’s views/Kohana/error.php file, so this is where I styled my error page to look like the rest of my public application. I copied much of the error reporting code directly from Kohana’s error file and used a conditional to display it in development or display a friendlier message in production. See the code skeleton:


if (IN_PRODUCTION) ///defined in boostrap.php
/* Render your friendly error message */
else
/* Render Kohana's error which you copied from views/Kohana/error.php */

Kohana v3 :: URL Redirect

To perform a simple redirect in v3, all you have to do is:

Request::instance()->redirect('/foo/bar/1');

Kohana v3 :: Godaddy & Megahosters

I have the opportunity (or problem, depending on my mood) to work with a diverse group of clients and many of the small business owners have hosting accounts with Godaddy, and one with Megahosters. Unlike most developers, I actually don’t mind godaddy so much, but, thats another post.
The point of this post is that I had to figure out how to get Kohana v3 working on Godaddy and Megahosters, so I thought I would pass the solution along

  1. Note:  I am installing Kohana at the root of the domain in booth cases
  2. /.htaccess files
    • Godaddy

      # Turn on URL rewriting
      RewriteEngine On
      # Installation directory
      RewriteBase /
      # Protect application and system files from being viewed
      RewriteRule ^(application|modules|system) - [F,L]
      # Allow any files or directories that exist to be displayed directly
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      # Rewrite all other URLs to index.php/URL
      RewriteRule ^(.+)$ index.php?kohana_uri=$1 [L]
    • Megahosters

      AddHandler application/x-httpd-php5 .php
      # Turn on URL rewriting
      RewriteEngine On
      # Installation directory
      RewriteBase /
      # Protect application and system files from being viewed
      RewriteRule ^(application|modules|system)/ - [F,L]
      # Allow any files or directories that exist to be displayed directly
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      # Rewrite all other URLs to index.php/URL
      RewriteRule ^(.+)$ index.php?kohana_uri=$1 [L]
  3. /application/boostrap.php
    At the bottom of the bootstrap file, after the routing, is the execution statement. By default it looks like this:


    echo Request::instance()
    ->execute()
    ->send_headers()
    ->response;

    Basically, you can pass an array when you instantiate the Request, but if you don’t (defualt), Kohana will use some If / Else statements to see which node of the $_SERVER array contains the request information. This works fine on most servers, but on shared servers like Godaddy/Megahosters, the first $_SERVER node (PATH_INFO) checked sends bad information, so to fix it, you just need to pass the Request the correct node. For both Godaddy and Megahosters, its the same: REQUEST_URI. So here is how it should look:


    echo Request::instance($_SERVER['REQUEST_URI'])
    ->execute()
    ->send_headers()
    ->response;

HOPE THIS HELPS!

AddHandler application/x-httpd-php5 .php

# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /

# Protect application and system files from being viewed
RewriteRule ^(application|modules|system)/ – [F,L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule ^(.+)$ index.php?kohana_uri=$1 [L]

Kohana v3 :: Auth Module

I was just about to throw my monitor across the room when I finally got the Auth Module working:

  1. IMPORTANT – do not use the complete v3 download from the main Kohana site (It simply doesn’t work that way), instead git the project, the core, and all the modules individually from github: http://github.com/kohana.
  2. Note that the ORM and Auth Modules have been forked and have their own repositories, but the links are the main Kohana git page
  3. Create the necessary database tables (MySql):
    CREATE TABLE IF NOT EXISTS `roles` (
    `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
    `name` varchar(32) NOT NULL,
    `description` varchar(255) NOT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uniq_name` (`name`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    INSERT INTO `roles` (`id`, `name`, `description`) VALUES(1, 'login', 'Login privileges, granted after account confirmation');
    INSERT INTO `roles` (`id`, `name`, `description`) VALUES(2, 'admin', 'Administrative user, has access to everything.');CREATE TABLE IF NOT EXISTS `roles_users` (
    `user_id` int(10) UNSIGNED NOT NULL,
    `role_id` int(10) UNSIGNED NOT NULL,
    PRIMARY KEY (`user_id`,`role_id`),
    KEY `fk_role_id` (`role_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    CREATE TABLE IF NOT EXISTS `users` (
    `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
    `email` varchar(127) NOT NULL,
    `username` varchar(32) NOT NULL DEFAULT '',
    `password` varchar(255) NOT NULL,
    `logins` int(10) UNSIGNED NOT NULL DEFAULT '0',
    `last_login` int(10) UNSIGNED,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uniq_username` (`username`),
    UNIQUE KEY `uniq_email` (`email`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    CREATE TABLE IF NOT EXISTS `user_tokens` (
    `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
    `user_id` int(11) UNSIGNED NOT NULL,
    `user_agent` varchar(40) NOT NULL,
    `token` varchar(32) NOT NULL,
    `created` int(10) UNSIGNED NOT NULL,
    `expires` int(10) UNSIGNED NOT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uniq_token` (`token`),
    KEY `fk_user_id` (`user_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    ALTER TABLE `roles_users`
    ADD CONSTRAINT `roles_users_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
    ADD CONSTRAINT `roles_users_ibfk_2` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE;
    ALTER TABLE `user_tokens`
    ADD CONSTRAINT `user_tokens_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
  4. The only database change I made is to change the User.password field to varchar 255 to allow for large hashed passwords.
  5. Ensure that your database is configured correctly – per my previous post on Kohana’s Database Session.
  6. Then follow the tutorial on the Wiki for the Auth fork git repository: http://wiki.github.com/biakaveron/kohana-auth.

Kohana v3 :: Session Database Driver

I was having a little trouble getting the session to work while using the database driver (instead of the Native or Cookie drivers), but I eventually found the error. I was using the sessions table MySql create statement from Kohana 2.3 documentation, which is slightly different from the required table for 3.0. So here is a brief tutorial in using the Session with the database driver.

  1. create the sessions database table (mysql example):
    CREATE TABLE `sessions` (
    `session_id` varchar(127) NOT NULL,
    `last_active` int(10) unsigned NOT NULL,
    `contents` text NOT NULL,
    PRIMARY KEY (`session_id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
  2. In the bootstrap.php file, uncomment the line for the database module
  3. Copy the /modules/database/config/database.php file to /application/config/database.php and fill in the appropriate database connection variables
  4. to test, create a controller action and run it:
    public function action_set()
    {
    $session = Session::instance('database');
    $session->set('foo', 'hello from the session db');
    }
  5. then retrieve the session data in another controller action and run it:
    public function action_get()
    {
    $session = Session::instance('database');
    $data = $session->get('foo');
    echo Kohana::debug($data);
    }
  6. You should be greated with our session string: ‘hello from the session db’

Kohana v3

For the past year I have been building all of my web applications with Kohana in their 2.x branch.  With the release of version 3 (http://v3.kohanaphp.com), I will be delving into the new code for a new CMS based website for a big client of mine.  So, I thought that I would use this opportunity to blog about my learnings/progress with Kohana v3 and its new features, especially because there aren’t any tutorials yet on the subject.  So stay tuned.