SithTemplate is dead, long live SithTemplate

Piotr Legnica recently announced that he is abandoning SithTemplate due to not using PHP anymore. As you might know i have been a long-time user of SithTemplate, and am a bit sad though.

Now what does this mean for King23? King23 is comming bundled with SithTemplate atm, using it for its templates. Now while all of this might sound “bad” at the moment, it actually isn’t. Piotr has relicensed SithTemplate under the ‘unlicense’ which basically says ‘you can do whatever the fuck you want with this’.

So whats going to happen is:
a) the current King23 Version 0.0.3 still comes with SithTemplate bundled.
b) for 0.0.4 i will fork SithTemplate, rename it to King23_Template, and make a few changes to better integrate it with King23.

Basically this means in not-so-far future you will see the templating system of King23 a bit more integrated (mostly classloading, how it is configured etc.), and support for it will be continued by the King23 project (so Piotr won’t have anyone bugging him about it anymore).

Whats not going to happen: King23_Template will not work outside a King23 environment, if you need that, you have to fork SithTemplate yourself.

King23 Benchmark – playing a numbers game

Several People have been asking me why i actually started writing King23,
with that many OpenSource Frameworks arround.

Well, first of all, because i enjoy doing that. Second is my dislike for some of the
things other frameworks do. When i started with ECOTRA/Northern Crusade
(the first website running on this framework), i looked at several PHP Frameworks
and decided to do King23, basically because i did not need most functionality of
other Frameworks, because i wanted to use SithTemplates as a templating system,
and because of the resource/performance waste that comes with the large frameworks.

Today i had a bit of free time and decided, for the fun of it, to do a bit of
speed testing on a few Frameworks.
The Setup for this is quite simple, the machine i tested on is a cloud level 1
jiffybox
running a basic 64bit Debian 5.0 with Apache + PHP 5.2 + suhosin.
The test itself is a simple apache bench with 500 requests
and a concurrency of 20. (please note that i run ab on the same machine as the webserver).

Please note that i’ve chosen to use PHP 5.2 here, since php 5.3 is still a bit
of an underdog at most hosters, and since none of the frameworks that i tested required
5.3 functionality.

For each framework that i tested i set up a virtual host, and run pretty
much with the default install, with the exception of King23, i used the http://king23.net
websites source for this (since the default starting page barely uses the template system).

Now the values that where of interest from me where Requests per second
and time per request.

cakephp:

Requests per second:    23.02 [#/sec] (mean)
Time per request:       868.960 [ms] (mean)

Cakephp was the slowest of all that i tested, however i want to add that
cake did some checks on the filesystem if the caches are readable and such,
so it did a bit more then just showing a welcome page.

symfony:

Requests per second:    29.75 [#/sec] (mean)
Time per request:       672.324 [ms] (mean)

Symfony didnt really have many suprises for me, we are using it at work,
so i was aware of its performance.

zend:

Requests per second:    54.09 [#/sec] (mean)
Time per request:       369.784 [ms] (mean)

Zend actually did suprise me, i expected it to be at arround
the same speed as symfony if not even slower, but it seems
that Zend doesnt load as much unneeded stuff as cake and symfony
do (symfony included several doctrine related classes that where not needed for the example, cake included some form-handling classes that where not needed either)

king23:

Requests per second:    209.76 [#/sec] (mean)
Time per request:       95.345 [ms] (mean)

Not really a suprise here either, king23′s smaller callstacks, less includes, and more simple structure make a difference. Even with using a more complex template system than symfony for example.

Now before people start crucifying me, let me admit it first: Yes this Benchmark is unfair!!!
As mentioned before, King23 does do alot less, also you can get alot of performance out of all frameworks
if you specifically tune the system for that. Also this benchmarks doesnt say much about the quality,
or about the performance under real conditions. If you add Database stuff to it, if you add a bit more logic
the results will be much closer to eachother then they are in this simple case.

However, before people claim that i tuned the setup for King23,
or tuned the King23 website for the benchmark – i didn’t. Its not using any additional caches,
besides the template cache, meaning for example that it is building the maps for the Autoloader
each time etc. Just to show how a small change in the setup can influence the outcome:
king23+m

Requests per second:    2222.91 [#/sec] (mean)
Time per request:       8.997 [ms] (mean)

This is the same sourcecode, the same application configuration etc. than used before, all i did was
kick apache2 out of the equation, in favour of a php extension called “mistral”, more on mistral in another post soon..

King23: extracting parameters from the hostname…

I just added a small feature to King23s routing that allows you to use parts of the domain as parameters.

An example use for this would be a multi user photoalbum, where the users name is part of the subdomain, for deeplink to his photos… or a multiuser blog etc. pretty much everything where a hostname is preferred.

This is not in the current release yet, but allready available in the git repository on github.

A very simple usage example:

<?php
// get instace of the mainrouter
$router = King23_Router::getInstance();
$router->addRoute("/", "My_View", "index", array('param1'), array('hparam1'));

This adds a route which will match a regular parameter aswell as a hostbased one. Now to explain a bit further, lets look at a full url:
http://example.king23.net/foo
the route in the example would cause the method “index” to be called in My_View, handing one parameter, which is an array, looking like: array(‘param1′ => “foo”, ‘hparam1′ => ‘net’).. “net” you wonder? well, the parts of the host are matched in reverse order, so example.king23.net first parameter would be net, second king23 and third example.
This is mostly to ensure that if you have more parameters than host segments this gets filled in a logical way.

Now this is nice, but actually you did not want the actual domain name as paramters, just subdomains of it? if you have http://username.users.king23.net then you’d be interested in username, not in users.king23.net, right? Well, there is a simple solution for that:

<?php
$router->setBaseHost('users.king23.net');

this simple line will cause the unwanted part to be removed. The route from the first example would cause “http://myusername.users.king23.net/foo” to be translated to a call to My_View::index with one array parameter containing array(‘param1′ => “foo”, ‘hparam1′ => “myusername”).

random update… oh, and a new page

yeah i know i know, i haven’t posted in a while,
thats mostly because i haven’t done much stuff thats worth writing about.

however i’ve put a bit of time into a webpage for the king23 framework, and if you want to you can check out a first (very small) version at http://king23.net.
if i manage to find a bit more time i should probably start in writing a bit more docs then the inline docs and the tutorial posts on this blog.

I’ve been toying arround a bit with the idea of adding a bit of tools to integrate with hookbox, but i haven’t had a good idea on what i want to try it out, so that will have to wait a bit.

King23 Pheal CLI

A few people have been asking me for more examples on the usage of pheal lately,
so i hacked together a short example utilizing King23 Tasks to create a simple CLI to the EVE API, atm it doesnt really cover much functionality, but it should be a nice live demonstration on how to use Pheal.

More Information on this are available at its Github page

Edit: it also contains usage of Doctrine, as earlier shown on this Blog :)

King23 routes…

I just made a pretty small change in the way King23 works with its routing,
while it is fully backward compatible, it now allows you to add sub-routers to organise your routes a bit. So you dont end up having a list of thousand routes below eachother (and executionwise it means less iterations, more speed, if you use subrouters, instead of declaring all routes in a flat list).

It also allows you fancy stuff like extending the router class, overloading the usual router methods by own implementations that only run for a specific subroute… use your imagination of what you can do with this =)

A very simple usage example:

<?php
// get instace of the mainrouter
$router = King23_Router::getInstance();

// get a non singleton instance of King23_Router
$subrouter = new King23_Router();

// declare a few routes at the subrouter
$subrouter->addRoute("one/",  "My_View",  "one", array("param1", "param2"));
$subrouter->addRoute("two/",  "My_View",  "two", array("param1", "param2"));
$subrouter->addRoute("/", "My_View", "index");

// add the subrouter with a route to the main router
$router->addRouter("/projects/", $projects);

// add regular routes to the main router
$router->addRoute("/",          "Devedge_Static_View",  "index",    array());

One more thing, this is currently only available in git, not in any release yet.

King23 and Doctrine ORM


Introduction

Hello and welcome to another King23 article.

If you have looked at the current state (v0.0.3) of King23, you might have noticed that while it basically follows the MVC pattern, it does currently not come with any specific database layer to build the model. However, while writing this tutorial i have added a few things to help you to get King23 running with Doctrine.

Currently there are several interesting approaches on how to handle your model, be it using an object or document based database system (MongoDB, CouchDB…), or one of the widely known ORM for PHP (Propel, Doctrine..), however which ideally to pick often depends on the requirements of the application that needs to be build.

Personally i use several of those methods with King23 (and others with other Frameworks),
and sometimes i even use hand written classes (nortern-crusade.com for example has a hand-build model).

Doctrine is one of the more powerfull ORM, comming with an own query language (dql), the ability to talk to several database systems, build in caching, powerfull code generators etc.
If you are familliar with the Symfony framework, you might know that Doctrine replaced the older ORM Propel there.

Either way, there are alot of reasons why you would want to use a ORM like Doctrine, and if you are unsure if this is interesting for you (or not), then use your google-fu to find more information, its beyond the scope of this article to argue about the pro and cons of a ORM.

Requirements

This article assumes that you have a king23 installation, PHP5.2.3+ and Doctrine in version 1.2 (2.0 requires PHP 5.3, and works differently, so if you decide to go for 2.0, you are on your own!)

Lets get started..

prepare our project

obviously the first thing that we do is to use king23 to setup a project for us,
in this example “myapp”:

gareth:/opt/www# king23 King23:create_project myapp
[2010-06-08 19:16:45] King23 (Version: 0.0.2) project creation
[2010-06-08 19:16:45] copying project template to myapp
[2010-06-08 19:16:46] creating symlink myapp/lib/King23 to point to /opt/king23
[2010-06-08 19:16:46] Setting rights in myapp/template_c/
[2010-06-08 19:16:46] Project: myapp created

Obtaining Doctrine

there are several ways of obtaining Doctrine, and its up to you to pick the one that suits you most. The Doctrine project recommends the use of svn / svn:externals to get the source, but if that really suits you depends alot on if you use svn or not. Another way of installing Doctrine would be to simply use the pear installer, but personally i want to keep the application self contained, so no librarys in other pathes wanted.

For this tutorial i have decided to use a svn export, since it will give me a clean library folder without any svn folders. Also im going to use the version tagged as 1.2.2.
Probably you want to use a different way (for example a svn checkout instead of export, so its easier for you to update, or you do want the tests, the sandbox or the docs left out – either way, check the doctrine documentation for more information).

gareth:/opt/www/# cd myapp/lib
gareth:/opt/www/myapp/lib# svn export http://svn.doctrine-project.org/tags/1.2.2/ Doctrine

Now i have a Doctrine distribution in my library folder.

Configuration

The next step is to configure doctrine, so we can use the cli task that (now) comes with King23. The Project template should have put a doctrine.php in your conf folder, configuring is as easy as editing that one, and then open the config.php, go to the bottom and make sure the doctrine.php is included.

The CLI

Doctrine comes with a command line interface, that will do stuff like (re)build your model, work with migrations etc (check out the Doctrine Manual for more information). If you have done everything right, then you should now be able to run:

king23 King23:doctrine

And you should be rewarded with an output like this:

[2010-06-13 11:19:17] King23 Doctrine CLI wrapper
Doctrine Command Line Interface

king23 King23:doctrine compile
king23 King23:doctrine dql
king23 King23:doctrine generate-migrations-models
king23 King23:doctrine rebuild-db
king23 King23:doctrine generate-migrations-db
king23 King23:doctrine create-tables
king23 King23:doctrine dump-data
king23 King23:doctrine generate-migration
king23 King23:doctrine generate-models-db
king23 King23:doctrine load-data
king23 King23:doctrine create-db
king23 King23:doctrine generate-sql
king23 King23:doctrine drop-db
king23 King23:doctrine build-all-reload
king23 King23:doctrine generate-migrations-diff
king23 King23:doctrine generate-models-yaml
king23 King23:doctrine generate-yaml-models
king23 King23:doctrine generate-yaml-db
king23 King23:doctrine build-all-load
king23 King23:doctrine build-all
king23 King23:doctrine migrate

to learn more about doctrine / the doctrine cli, check out the doctrine website.

Links

King23: an introduction to tasks

Introduction

this Article is meant to give you a short overview on how to extend the king23 command
line tool within your application
it assumes that you have read
http://devedge.wordpress.com/2010/05/29/king23-getting-started/

To demonstrate a few things that can be done with the King23 tasks,
we will fetch some data from this blog, and display the headlines in the command line.

The Task

If you run the king23 command line tool, it will allways check the current path
for a subdirectory named “tasks”, and if that one exists add it to the King23 autoloader.
it will then make a list of all files that end with “_Task.php”, assuming that everything
before _Task.php is the name of the task module.

if you used the King23:create_project task, then you allready have a task module named “EXAMPLE”
in your tasks folder (EXAMPLE_Task.php)

A task module is a class with the same name as the file
(in the case of the existing module, the classname is EXAMPLE_Task.php).
task modules should allways be derived from King23_CLI_Task, since that one provides
basic functionality like the info task, and access to the documentation array of the module,
however it is possible to make task modules that are not derived.

For our tutorial, we are going too create an own module named MyApp,
so the filename is tasks/MyApp_Task.php

our task module extends King23_CLI_Task

class MyApp_Task extends King23_CLI_Task

The next thing we do is that we overload King23_CLI_Tasks protected member $tasks, and fill it
with informations on our own tasks

    protected $tasks = array(
        "info" => "General Informative Task", // this is a buildin Task to King23_CLI_Task and available in all Tasks
        "fetch_data" => "fetch the data from the url that needs to be given as a parameter",  // describing our task
    );

The info task needs to know about the name of the module,
so we overload the protected $name member aswell:

    protected $name = "MyApp"; // this is used by the info task

now the next part is where the fun happens,
all actual tasks are methods on a task module object, and take an array as parameter,
this array gets filled with all parameters that follow after a method call.

king23 MyApp:imaginarytask one two three

would call a method named “imaginarytask”, handing over an array containing the elements “one”, “two”, and “three”.

since we want to fetch from an url which is given as a parameter,
probably the first thing we want todo is check if the right amount of parameters is given,
and if not print out an error and end the run.

since we extend King23_CLI_Task, we have an instance of King23_CLI as a member of the current object,
which allows us a conveniant way of printing out different types of messages:

  • header($message)
    for printing out a header (bold/brighter)
  • message($message)
    for pretty much all sorts of messages
  • warning($message)
    for warnings
  • error($message)
    for errors
  • positive($message)
    success/ok message

all those will print out what ever we tell it to print out, but each of them will color the line a bit different.

Also, each of them will prefix the output with a current timestamp.

after we ensured that the amount of parameters is correct, we call
the method “execFetch($params[0])” to make the actuall fetch.
i wont describe that method in detail, its just a quick (and dirty)
fetch of a rss file, reading all titles and returning those as an array.
this is not a good way todo it, i ignore all error handling, but it will
do for the example. The implementation of said method is in the
complete script, which you can find at the bottom of this article.

we will print a header and then iterate over the titles,
and output them one by one:

    public function fetch_data(array $params)
    {
      if(count($params) != 1)
      {
         $this->cli->error("wrong amount of parameters given, this task takes exactly one.");
         return;
      }

      $data = $this->execFetch($params[0]);
      $this->cli->header("The titles for " . $params[0]);
      foreach($data as $title)
        $this->cli->message($title);

      return;
    }

this pretty much concludes this small tutorial

the complete script

<?php
class MyApp_Task extends King23_CLI_Task
{
    /**
     * this member should list all tasks that are available through this task module
     * and give a short documentation for the help at commandline
     * @var array
     */
    protected $tasks = array(
      "info" => "General Informative Task", // this is a buildin Task to King23_CLI_Task and available in all Tasks
      "fetch_data" => "fetch the data from the url, takes an url as parameter",  // describing our task
    );

    /**
     * Name of the module
     */
    protected $name = "MyApp"; // this is used by the info task

    public function fetch_data(array $params)
    {
      if(count($params) != 1)
      {
         $this->cli->error("wrong amount of parameters given, this task takes exactly one.");
         return;
      }

      $data = $this->execFetch($params[0]);
      $this->cli->header("The titles for " . $params[0]);
      foreach($data as $title)
        $this->cli->message($title);

    }

  private function execFetch($url)
  {
    $data = join('', file($url));
    $xml = new SimpleXMLElement($data);
    foreach($xml->channel->item as $item)
      $titles[] = $item->title;
    return $titles;
  }
}

King23: Getting started

Introduction

this Article is meant to give a quick how-to-start with King23,
it will lead through the basic installation, and the creation of a first project

Requirements

Software

King23 might run with other setups aswell, but this is the setup it was written for,
so i assume that you are using something like this.

  • PHP 5.2+
  • Apache + mod_rewrite
  • Linux with access to the shell(!)
  • a GIT client

Knowledge

To actually use King23 you will need to know about a few things,
most of them are not exactly rocket science, and there are alot of good
tutorials about them available on the internet, its not covered in this article,
so use google :)

  • PHP
  • Using the Linux shell
  • Configure Apache
  • Using your favorite text editor

Installing King23

First of all we are going to clone the King23 git, then we will setup the commandline
script of King23 to be in the path. Lets assume you want to install it in a subfolder of
your home directory called “www”, and then add it to your path for the current running shell.

first we move ourselves to our home, and create the www directory:

cd
mkdir www
cd www

Now we clone the git from github:

git clone git://github.com/ppetermann/king23.git

This will create a folder named “king23″ containing the complete King23 distribution.

Now the next part is to get the king23 command line script residing in ~/www/king23/bin/
in our path. offcourse you can omit that step and allways call it from there, but it is
much more compfortable to be able to run it directly.

In this example we simply add it to our current PATH variable:

export PATH=$PATH:/home/USERNAME/www/king23/bin/

other ways would be putting it in our bashrc / profile either by extending
the PATH variable there or by writing an alias, another way is to make a symlink
to the script from a folder that is allready in the path

if you have setup the binary to your path (and i assume you did so),
then putting [b]king23[/b] to your shell should output something like this:

[2010-05-29 10:04:23] King23 CLI (Version: 0.0.2)
[2010-05-29 10:04:23] Syntax: king23 <taskmodule>:<task>
[2010-05-29 10:04:23]
[2010-05-29 10:04:23] Available Modules:
[2010-05-29 10:04:23] King23

Congratulations, you have now installed the framework itself.

Creating an King23 Project

With having the cli script running creating the actual project
is quite simple. As you might have seen the king23 script provides by default
a module called King23. If you run the script stating the module and omiting
a task OR using info as task you will get a bit more information on
what the King23 Module can do for you:

king23 King23

output:

[2010-05-29 10:15:12] King23 called without task, assuming 'info'
[2010-05-29 10:15:12] King23 Version:
[2010-05-29 10:15:12] 0.0.2
[2010-05-29 10:15:12] Description:
[2010-05-29 10:15:12] King23 is lightweight MVC Framework
[2010-05-29 10:15:12] Authors:
[2010-05-29 10:15:12] Peter Petermann <ppeterman80@googlemail.com>
[2010-05-29 10:15:12]
[2010-05-29 10:15:12] Module King23
[2010-05-29 10:15:12] -----------------------
[2010-05-29 10:15:12] Task: info
[2010-05-29 10:15:12] Description:
[2010-05-29 10:15:12] General Informative Task
[2010-05-29 10:15:12]
[2010-05-29 10:15:12] Task: list_modules
[2010-05-29 10:15:12] Description:
[2010-05-29 10:15:12] show a list of all currently available modules
[2010-05-29 10:15:12]
[2010-05-29 10:15:12] Task: create_project
[2010-05-29 10:15:12] Description:
[2010-05-29 10:15:12] create a new project, requires project name as parameter

As you can see the King23 module does not provide much atm, but it provides
us with the task that we are looking for: create_project, and as you can see
in the description create_project takes one parameter (the project name).

Lets assume we want to call our project “myapp”, the our command line call would be:

king23 King23:create_project myapp

output:

[2010-05-29 10:19:21] King23 (Version: 0.0.2) project creation
[2010-05-29 10:19:21] copying project template to myapp
[2010-05-29 10:19:21] creating symlink myapp/lib/King23 to point to /home/USERNAME/www/king23
[2010-05-29 10:19:21] Setting rights in myapp/template_c/
[2010-05-29 10:19:21] Project: myapp created

this should leave you with a working king23 application template
having the directories:

  • conf/ the projects configuration files
  • public/ the projects web root, this should be the documentroot for your apache vhost(!)
  • lib/
    • lib/King23 a symlink to your King23 installation
    • lib/SithTemplate a copy of Piotr Legnicas awesome template system
  • tasks/ a folder in which project specific tasks extending the commandline script can be added
  • templates the templates used by the application
  • templates_c a place where SithTemplate can store compiled templates (for more information on that check SithTemplates docs)
  • views a folder where the view scripts are stored.

If you now configure your apache to use /home/USERNAME/www/myapp/public/ as the DocumentRoot,
and then post your browser to the application (example: http://localhost/) you should see the
welcome screen of your first King23 application.

Next steps

Web

you probably now want to have a look at conf/routes.php, the scripts in the views/ folder, and the templates.

Docs

If you check in the lib/SithTemplate folder you can find documentation about the template system there,
running phpdocumentor or doxygen should create an api documentation for King23 too (might be available online
in future)

Tasks

if you want to run stuff from the command line, make sure to check tasks/ for the example
that provides you with

king23 EXAMPLE:example

in the myapp folder

the end

i hope this gives you a quick start with King23, a more comprehensive tutorial on how to actually use it will come – soon.