// Simple run application in entry point
BApp::i()->run();

URLs

// get base URL of the application
$url = BApp::i()->baseUrl();

// get page URLs for links and redirection
$url = BApp::i()->href('my/url');
// $url = 'https://127.0.0.1/fulleron/index.php/my/url';

// get assets URLs for images, stylesheets, javascripts, etc
$url = BApp::i()->src('@Module_Name/js/my_script.js');
// $url = 'https://127.0.0.1/fulleron/local/Module/Name/js/my_script.js';

Data Registry

// set variable data in registry
BApp::i()->set($key, $val);

// set constant data in registry
BApp::i()->set($key, $val, true);

Shortcuts

// get current BModule object (from template or bootstrap)
$module = BApp::i()->m();

//

If you extend classes from BClass they will automatically receive capability to be overridden or augmented by Buckyball. This is achieved using method i(), which allows calling singleton or creating new instances.

class Your_Class_Name extends BClass
{
    /**
     * Remember current class for use in events, in case this class will be overridden, optional
     *
     * @var string
     */
    static protected $_origClass = __CLASS__;

    /**
     * Shortcut to help with IDE autocompletion, optional
     *
     * @return Your_Class_Name
     */
    public static function i($new=false, array $args=array())
    {
        return BClassRegistry::i()->instance(__CLASS__, $args, !$new);
    }

    public function yourMethod()
    {

    }
}

To get a singleton simply call without arguments:

Your_Class_Name::i()->yourMethod();

To create a new instance:

$obj = Your_Class_Name::i(true, $args);

Overriding Classes

Warning! It is not recommended to override classes in public modules, because it can create double override conflicts. Try to use event hooks as much as possible.

override:
    class:
        - [ Orig_Class_Name, Custom_Class_Name ]

Alternatively:

BClassRegistry::i()->overrideClass($origClass, $customClass);

Augmenting Classes

Add a method to a class

// $callback should be inline, function or static class.
// the arguments are object instance and arguments passed from the call
BClassRegistry::i()->addMethod('My_Class', 'myNewMethod', function($self, $arg1, $arg2) {
    return $self->doSomething($arg1, $arg2);
});

$result = My_Class::i()->myNewMethod('foo', 'bar');
Warning! The following features are EXPERIMENTAL and there are known issues. The main is that PHP doesn't allow overriding $this variable, so the augmentation will not affect calls from inside the class.
// override a class method
BClassRegistry::i()->overrideMethod('My_Class', 'myMethod', $callback);

// augment a class method - receive result from a method and change it before returning to original caller
$callback = function($result, $origObject, $arg1, $arg2) {
    // augment $result of previous object method call
    $result['additional_info'] = 'foo';
    return $result;
}
BClassRegistry::i()->augmentMethod('My_Class', 'myMethod', $callback);

// augment a class instance property
BClassRegistry::i()->augmentProperty('SomeClass', 'foo', 'set', 'override', 'MyClass::newSetter');
BClassRegistry::i()->augmentProperty('SomeClass', 'foo', 'get', 'after', 'MyClass::newGetter');

class MyClass {
    static public function newSetter($object, $property, $value)
    {
        $object->$property = myCustomProcess($value);
    }

    static public function newGetter($object, $property, $prevResult)
    {
        return $prevResult+5;
    }
}

Autoloading

Sometimes you might need to load a 3rd party library, which has its own folder and class structure. Simply create a folder lib/ under your module, put library files there and add this to module manifest:

autoload: lib

Alternatively:

BClassAutoload::i(true, array('root_dir' => $rootDir));
// creating a custom config instance
$config = BConfig::i(true, $initData);

// clear config
$config->unsetConfig();

Setting

$toSave = true; // in case we want this configuration to be saved in admin / settings page

// Adding bulk configuration
$config = array(
    'modules' => array(
        'My_Module' => array(
            'api_key' => 'nUNa178bJKgf'
        )
    )
);

BConfig::i()->add($config, $toSave);

// Adding / Setting a specific key
$path = 'modules/My_Module/api_key'; // path to configuration key
$value = 'nUNa178bJKgf'; // value can be string, number, boolean or array

BConfig::i()->set($path, $value, $toSave);

Getting

$config = BConfig::i()->get('path/to/config');

Loading from a file

BConfig::i()->addFile($fileName, $toSave);

Saving to a file

$fileName = BConfig::i()->get('fs/config_dir') . '/my_config.yml';
$config = BConfig::i()->get('custom/section'); // get custom section from config
$format = 'yml'; // optional, will be inferred from file extension. Allowed: yml, php, json

BConfig::i()->writeFile($fileName, $config, $format);

Trigger events

BEvents::i()->fire($eventName, $eventArguments);

// Fire all events that match regex expression
BEvents::i()->fireRegex($eventPattern, $eventArguments);

Observe events

observe:
    - [ EventName1, Callback1 ]
    - [ EventName2, Callback2, { arg1: val1, arg2: val2 } ]
BEvents::i()->on($eventName, $callback, $observerArguments);

// observe an event only once
BEvents::i()->once($eventName, $callback, $observerArguments);

Manage observers

BEvents::i()->off($eventName, $alias);

Open / Close

// open a session
BSession::i()->open();

// close a session - remove lock from session to allow other requests
BSession::i()->close();

Data

// get session data
BSession::i()->get($key);

// set session data
BSession::i()->set($key, $data);

// alternatively:
$data =& BSession::i()->dataToUpdate();
$data[$key] = $data;

Messages

// add messages to session in a controller
try {
    //... do something here
    BSession::i()->addMessage('Operation successful', 'success', 'frontend');
} catch (Exception $e) {
    //... process exception
    BSession::i()->addMessage('Operation failed', 'error', 'frontend');
}

// Output buffered messages in template
$messages = BSession::i()->messages('frontend'); // returns array of messages

Security

Session IP Protection
BConfig::i()->set('cookie/session_check_ip', true);
CSRF Protection
// TODO: Not sure where this doc is supposed to be: controller/response? layout/view/head?

// set CSRF protection using referrer browser request header
BConfig::i()->set('web/csrf_check_method', 'referrer');

// set CSRF protection using token. All forms submitted should have X-CSRF-TOKEN field
BConfig::i()->set('web/csrf_check_method', 'token');

// output raw CSRF token
echo BSession::i()->csrfToken();

// add to head
BLayout::i()->view('head')->meta('csrf-token', BSession::i()->csrfToken());

Custom Handlers

// add a new handler
BSession::i()->addHandler($handlerName, $className);

// set this handler as default
BConfig::i()->set('cookie/session_handler', $handlerName);

Currently only APC custom session handler is implemented in core, and is used automatically if APC enabled

comments powered by Disqus