Maslosoft Framework Documentation
Flexible Application Foundation
Local Storage
Local storage allows to get or set value of named key, with namespace prefix, so that it will not conflict with other components.
The values can be set either with JavaScript or with PHP on server side when generating page.
Initializing local 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 LocalStorage($this);
$params = [
$storage
];
$this->jsRef = new JsWidget($this, $params);
...
Setting value in PHP
It is possible to set local storage value from PHP code when initializing widget.
The LocalStorage
class exposes get()
and set()
methods.
Calling set, will inject JavaScript which will set value JavaScript LocalStorage
class, which in turn will set namespaced key to passed value. The value will
be automatically JavaScript encoded.
$storage->set('myKey', 123);
Getting value in PHP
While it is not really possible to obtain local storage value in PHP, the get()
method will return JavaScript reference, which can be passed to widget method or attribute.
Example below will call JavaScript widget instance method myMethod
, with argument
containing result of JavaScript's local storage get
method call.
$ref = $storage->get('myKey');
$this->jsRef->myMethod($ref);
Using from the JavaScript side,
The usage of local storage class is more obvious and straightforward than the PHP counterpart. It
consists of get
and set
methods. The class should already be initialized
by PHP part.
The example below is in CoffeeScript
class MyWidget # @var Maslosoft.Widgets.LocalStorage storage: null constructor: (@storage) -> # Get storage value val = @storage.get 'active' toggle: () => isActive = @storage.get 'active' @storage.set 'active', !isActive