Maslosoft Framework Logo Maslosoft Framework Documentation
Flexible Application Foundation


Cookie Storage

Local storage allows to get or set value of named key, with namespace prefix, so that it will not conflict with other components in cookie.

Use this storage as a last resort, when other ones did not succeed in their tasks.

The values can be set either with JavaScript or with PHP on server side when generating page or doing AJAX request.

Initializing cookie storage

Local storage initialization is made on PHP side, and should be made together with initialization of JavaScript counterpart of widget. The best option is to pass it as a constructor argument. It can also be set later as widget property or on method call.

Example of initialization

This should be placed in widget's init method, but can also be in other places, just ensure that this code is executed when creating widget.

The first argument is owner widget, which will also be used to reserve namespace for this widget keys. The second $namespace parameter can be used to create additional, local namespace for keys and in most cases can be left empty.

...
$storage = new CookieStorage($this);
$params = [
    $storage
];
$this->jsRef = new JsWidget($this, $params);
...
Setting value in PHP

It is possible to set or get cookie storage value from PHP code when initializing widget.

This will access proper superglobal $_COOKIE array.

The CookieStorage class exposes get() and set() methods.

Calling set will set namespaced key with encoded value. This will be available in JavaScript part when request finishes.

$storage->set('myKey', 123);
Getting value in PHP

The get() method will return value stored in $_COOKIE superglobal array, according to namespace set on initialization.

$value = $storage->get('myKey');
Using from the JavaScript side,

The usage of local storage class is same as in the PHP counterpart. It consists of get and set methods which works by getting and setting cookie value.

The example below is in CoffeeScript

class MyWidget

        # @var Maslosoft.Widgets.CookieStorage
        storage: null

        constructor: (@storage) ->

            # Get storage value
            val = @storage.get 'active'

        toggle: () =>
            isActive = @storage.get 'active'
            @storage.set 'active', !isActive