Table of Contents
Selectors are inspired from Javascript frameworks which uses CSS selectors to select object in the DOM.
Atomik Selectors allow you to select any kind of data or object.
You've already encountered selectors when you discovered accessors.
Selectors are available through the Atomik::get() method.
Namespaces are used to differentiate selectors. A namespace is only a word followed by “:” at the beggining of the selector.
Example 9.1. Using the flash selector
Atomik::flash('my message', 'label');
$messages = A('flash:label');
Plugins can provide their own selector namespace. For example, the Db plugin brings the “db” namespace which allow you to do sql queries.
Example 9.2. Using the selector provided by the Db plugin
// selecting a value from the global store
$value = A('key1/key2/key3');
// selecting all posts
$allPosts = A('db:SELECT * FROM posts');
// selecting the first post
$firstPost = A('db:SELECT * FROM posts WHERE id = ?', array(1));
See the Db plugin documentation for more information.
To register a namespace use Atomik::registerSelector() which takes
as first parameter the namespace prefix and as second a callback. When used, the callback will
be called with as arguments the same one used with Atomik::get().
However, the namespace prefix will be stripped off the first parameter, which is the "query" string.
Example 9.3. Registering a selector
function my_selector($string) {
return strtoupper($string);
}
Atomik::registerSelector('up', 'my_selector');
echo A('up:hello world'); // HELLO WORLD
The Atomik class has a lot of methods to do many things. They are easy to remember because you only need to do Atomik::something(). Since version 2.2, it is possible to add custom methods to the class. This feature works best with PHP 5.3 but can work (with limitations) with previous versions.
Registering a method is as simple as calling Atomik::registerMethod().
It takes as first argument the method name and as second a callback.
Example 9.4. Registering a method
function my_callback() {
echo 'call from myMethod()';
}
Atomik::registerMethod('myMethod', 'my_callback');
If you use PHP 5.3 you can use anonymous functions:
Atomik::registerMethod('myMethod', function() {
echo 'call from myMethod()';
});
Calling a registered method is like calling any other method of the Atomik class.
However this only works with PHP 5.3. With previous versions you'll need to use
Atomik::call().
Example 9.6. Calling a method using Atomik::call()
Atomik::call('myMethod');
Atomik::call('myMethod', $arg1, $arg2); // with arguments