Kirby Toolkit 101

As you might already know, Kirby CMS is based on a PHP library called Kirby Toolkit

PHP is sometimes so messed up, that you necessarily start to write your own wrappers and helpers, to make your daily work with PHP easier. The Toolkit is a collection of classes and functions, which I came up with in the last years and which have become a core element of my work.

It's a 1-file, open-source library, which can be easily included in any existing project. Since it is already included in the Kirby CMS core, you can start using all its classes and functions right away. If you want to use it for any other project, you can download the source from Github.

Philosophy

The code of the library is quite unorthodox. It uses static methods all over the place to create short memorizable method names and group methods. Either you like it or you don't. But the good thing is, that you don't have to use it, if you don't like it :)

Here are some of the principles the library follows.

- keep it simple stupid
- help to write less code
- make things easier to memorize
- provide better consistency
- provide built-in utf-8 support
- keep it focused on core tasks

Toolkit Tidbits

Handling Requests

PHP has the famous $_GET and $_POST variables, which contain the submitted values from POST and GET request – for example from forms. Working with them and checking for submitted values can be quite painful:

$value = (isset($_POST['key'])) ? trim($_POST['key']) : 'default value';

I think we've all seen this kind of code.

With Kirby, you can save a lot of that hassle by simply using the get() function, which works for POST and GET requests and is way more comfortable to use.

$value = get('key', 'default value');

If you don't pass a default value, false will be returned if nothing could be found for the passed key:

$value = get('key');

get() will also take care of trimming and of stripping slashes if necessary.


Redirection

If you want to create a simple redirect, you normally need to send a location header and if you want to do it correctly, you should also send a http status header:

header('HTTP/1.1 301 Moved Permanently');
header('Location: http://mywebsite.com');

With Kirby you can just write…

go('http://mywebsite.com');

Working with arrays

a::show

If you are debugging, you often need to inspect the content of an array or object. There's var_dump or print_r, but their output isn't really nice. a::show() helps you by producing nice, readable output of any array or object:

$array = array('design', 'tags', 'typography');

a::show($array);

/* output:

Array
(
    [0] => design
    [1] => tags
    [2] => typography
)

*/

a::get

How often do you find yourself writing something like this?

$value = (isset($array['key'])) ? $array['key'] : 'default value';

Instead a::get will try to find a value for a key in an array for you and return either that value or your default value if nothing has been found.

$value = a::get($array, 'key', 'default value');

If you don't pass a default value and nothing could be found for that key,
false will be returned.


a::first and a::last

Do you remeber, which was the function name for that array function that returns the first element of an array or that function that returns the last element? array_pop, array_push, array_shift, array_unshift? Maybe it's just me, but those function names kill me.

With Kirby you can do:

$array = array('design', 'tags', 'typography');

echo a::first($array);
// output: design

echo a::last($array);
// output: typography

This also works with associative arrays of course.


a::sort

Sorting a multi-dimensional array is a nightmare – not anymore!

$array = array(
  array('username' => 'homer'),
  array('username' => 'marge'),
  array('username' => 'bart'),
  array('username' => 'lisa'),
  array('username' => 'maggie')
);

$sorted = a::sort($array, 'username', 'asc');

a::show($sorted);

/* output:

Array
(
    [0] => Array
        (
            [username] => bart
        )

    [1] => Array
        (
            [username] => homer
        )

    [2] => Array
        (
            [username] => lisa
        )

    [3] => Array
        (
            [username] => maggie
        )

    [4] => Array
        (
            [username] => marge
        )

)

*/

Working with strings

str::lower and str::upper

Converting a string to lowercase or uppercase shouldn't be hard, right? Unfortunately PHP's native strtolower and strtoupper functions are not able to handle UTF-8 encoded strings correctly. That's why Kirby has its own lowercase and uppercase functions:

$sometext = 'This is a übercool Example of üppercase and Løwercase';

echo str::lower($sometext);
// output: this is a übercool example of üppercase and løwercase

echo str::upper($sometext);
// output: THIS IS A ÜBERCOOL EXAMPLE OF ÜPPERCASE AND LØWERCASE

str::length

The same problem with UTF-8 exsits for strlen – PHP's native function to count the number of characters in a string. With an UTF-8 encoded string the result wil be wrong. So Kirby has…

$sometext = 'This is a übercool lengthy string';

echo str::length($sometext);
// output: 33

str::short

To shorten a text is one of the tasks you need all the time. Think of a list of blog articles, with a short excerpt and a "read more" button, or to make sure that user generated content does not break your templates or stuff like that. When shortening strings you most probably want to append an ellipsis to show that it has been shortened, but only if the string is really too long. str::short does exactly that for you…

$sometext = 'This is a übercool lengthy string';

echo str::short($sometext, 10);
// output: This is a…

str::split

Splitting strings by a particular character is easy, right? Yep, it is, but it can be even easier. Take a look at the following string.

$tags = ', design, tags, typography, fun, , ';

You could use explode(',', $tags) to get all tags, but it wouldn't work well because of spaces and additional commas. str::split will help you to get some nice results without all the mess:

$string = ', design, tags, typography, fun, , ';
$tags   = str::split($string);

a::show($tags);

/*

Array
(
    [0] => design
    [1] => tags
    [2] => typography
    [3] => fun
)

*/

Of course it's possible to change the splitting character(s):

$string = '/ design / tags / typography / fun / / ';
$tags   = str::split($string, '/');

…and you can even specify the minimum length of included string:

$string = '/ design / tags / typography / fun / / ';
$tags   = str::split($string, '/', 4);

a::show($tags);

/* output:

Array
(
    [0] => design
    [1] => tags
    [2] => typography
)

*/

Config

c::set and c::get

If you need some app-wide configuration variables you can either use constants or you can go for Kirby's config variables. They are accessible everywhere and can be set and overwritten everywhere as well.

c::set('myconfigvar', 'this is my awesome config value');

function foo() {

  echo c::get('myconfigvar');
  // result: 'this is my awesome config value'

}

If you want to check, which config variables have been defined so far, do this:

a::show(c::get());
// output: your entire config

Session

s::start

If you want to avoid errors because you start a session twice accidentally, use s::start() instead of session_start()

session_start();

s::start();
// no problem :)

s::set and s::get

Sometimes it's really cool to just have to write less:

// start a session
s::start();

s::set('myvar', 'my value');

// later…
echo s::get('myvar');
// result: my value

s::get can also be used with a default value, so if the session variable has not been found, the default value will be returned:

echo s::get('myvar', 'my default value');

Cookies

cookie::set and cookie::get

To make setting and getting values from cookies easier, you can use:

cookie::set('mycookie', 'my cookie value');

// later…
cookie::get('mycookie');
// result: my cookie value

… again, you can define a default value if the cookie could not be found:

echo cookie::get('mycookie', 'my default value');

cookie::remove

To remove a cookie, use

cookie::remove('mycookie');

Files

f::write

f::write offers a fool-proof way of creating files. You can even pass an array and that will automatically be converted to json before.

$content = 'This is some nice content for my file';
$file    = '/some/path/to/my/file.txt';

f::write($file, $content);

f::read

Reading a file is very simple with PHP file_get_contents, but with f::read() you get a more consistent and shorter function and you can even use the second argument to instantly parse the result:

$file = '/some/path/to/my/file.txt';

echo f::read($file);
// result: content of file.text

$file = '/some/path/to/my/file.json';

echo f::read($file, 'json');
// result: the parsed json string as array

Directories

dir::read

Sometimes it's great to be able to get all files in a directory. Kirby CMS is entirely based on that. With dir::read you will get an array with filenames in a passed directory:

$files = dir::read('/path/to/my/dir');

a::show($files);
// result: an array with all filenames

dir::make and dir::remove

dir::make will create a directory if it does not exist yet and
with dir::remove you can delete an entire directory with all its contents.

dir::make('/path/to/my/new/dir');

dir::remove('/path/to/my/new/dir');

Validation

v::email

Check for a valid email address…

$email = 'bastian@getkirby.com';

if(v::email($email)) {
  echo 'this is a valid email address';
}

v::url

Check for a valid URL…

$url = 'http://someurl.com';

if(v::url($url)) {
  echo 'this is a valid url';
}

v::date

Check any parsable date…

$date = '11.04.2012';

if(v::date($date)) {
  echo 'this is a valid date';
}

More…

The Kirby Toolkit has way more features. Please read the docs to learn more about them.
There's also a tutorial how to use the built-in database class.

If you like the Toolkit, but you want to add your own features, feel free to fork it on Github.