1 Friendica Storage Backend Addon development
2 ===========================================
6 Storage backends can be added via addons.
7 A storage backend is implemented as a class, and the plugin register the class to make it avaiable to the system.
9 ## The Storage Backend Class
11 The class must live in `Friendica\Addon\youraddonname` namespace, where `youraddonname` the folder name of your addon.
13 The class must implement `Friendica\Model\Storage\IWritableStorage` interface. All method in the interface must be implemented:
15 namespace Friendica\Model\IWritableStorage;
18 interface IWritableStorage
20 public function get(string $reference);
21 public function put(string $data, string $reference = '');
22 public function delete(string $reference);
23 public function getOptions();
24 public function saveOptions(array $data);
25 public function __toString();
26 public static function getName();
30 - `get(string $reference)` returns data pointed by `$reference`
31 - `put(string $data, string $reference)` saves data in `$data` to position `$reference`, or a new position if `$reference` is empty.
32 - `delete(string $reference)` delete data pointed by `$reference`
34 Each storage backend can have options the admin can set in admin page.
36 - `getOptions()` returns an array with details about each option to build the interface.
37 - `saveOptions(array $data)` get `$data` from admin page, validate it and save it.
39 The array returned by `getOptions()` is defined as:
42 'option1name' => [ ..info.. ],
43 'option2name' => [ ..info.. ],
47 An empty array can be returned if backend doesn't have any options.
49 The info array for each option is defined as:
54 define the field used in form, and the type of data.
55 one of 'checkbox', 'combobox', 'custom', 'datetime', 'input', 'intcheckbox', 'password', 'radio', 'richtext', 'select', 'select_raw', 'textarea'
59 Translatable label of the field. This label will be shown in admin page
63 Current value of the option
67 Translatable description for the field. Will be shown in admin page
71 Optional. Depends on which 'type' this option is:
73 - 'select': array `[ value => label ]` of choices
74 - 'intcheckbox': value of input element
75 - 'select_raw': prebuild html string of `<option >` tags
77 Each label should be translatable
82 See doxygen documentation of `IWritableStorage` interface for details about each method.
84 ## Register a storage backend class
86 Each backend must be registered in the system when the plugin is installed, to be aviable.
88 `DI::facStorage()->register(string $class)` is used to register the backend class.
90 When the plugin is uninstalled, registered backends must be unregistered using
91 `DI::facStorage()->unregister(string $class)`.
93 You have to register a new hook in your addon, listening on `storage_instance(App $a, array $data)`.
94 In case `$data['name']` is your storage class name, you have to instance a new instance of your `Friendica\Model\Storage\IStorage` class.
95 Set the instance of your class as `$data['storage']` to pass it back to the backend.
97 This is necessary because it isn't always clear, if you need further construction arguments.
101 **Currently testing is limited to core Friendica only, this shows theoretically how tests should work in the future**
103 Each new Storage class should be added to the test-environment at [Storage Tests](https://github.com/friendica/friendica/tree/develop/tests/src/Model/Storage/).
105 Add a new test class which's naming convention is `StorageClassTest`, which extend the `StorageTest` in the same directory.
107 Override the two necessary instances:
110 use Friendica\Model\Storage\IWritableStorage;
112 abstract class StorageTest
114 // returns an instance of your newly created storage class
115 abstract protected function getInstance();
117 // Assertion for the option array you return for your new StorageClass
118 abstract protected function assertOption(IWritableStorage $storage);
122 ## Exception handling
124 There are two intended types of exceptions for storages
126 ### `ReferenceStorageExecption`
128 This storage exception should be used in case the caller tries to use an invalid references.
129 This could happen in case the caller tries to delete or update an unknown reference.
130 The implementation of the storage backend must not ignore invalid references.
132 Avoid throwing the common `StorageExecption` instead of the `ReferenceStorageException` at this particular situation!
134 ### `StorageException`
136 This is the common exception in case unexpected errors happen using the storage backend.
137 If there's a predecessor to this exception (e.g. you caught an exception and are throwing this execption), you should add the predecessor for transparency reasons.
142 use Friendica\Model\Storage\IWritableStorage;
144 class ExampleStorage implements IWritableStorage
146 public function get(string $reference) : string
149 throw new Exception('a real bad exception');
150 } catch (Exception $exception) {
151 throw new \Friendica\Model\Storage\StorageException(sprintf('The Example Storage throws an exception for reference %s', $reference), 500, $exception);
159 Here an hypotetical addon which register a useless storage backend.
160 Let's call it `samplestorage`.
162 This backend will discard all data we try to save and will return always the same image when we ask for some data.
163 The image returned can be set by the administrator in admin page.
165 First, the backend class.
166 The file will be `addon/samplestorage/SampleStorageBackend.php`:
170 namespace Friendica\Addon\samplestorage;
172 use Friendica\Model\Storage\IWritableStorage;
174 use Friendica\Core\Config\IConfig;
175 use Friendica\Core\L10n;
177 class SampleStorageBackend implements IWritableStorage
179 const NAME = 'Sample Storage';
187 * SampleStorageBackend constructor.
188 * @param IConfig $config The configuration of Friendica
190 * You can add here every dynamic class as dependency you like and add them to a private field
191 * Friendica automatically creates these classes and passes them as argument to the constructor
193 public function __construct(IConfig $config, L10n $l10n)
195 $this->config = $config;
199 public function get(string $reference)
201 // we return always the same image data. Which file we load is defined by
203 $filename = $this->config->get('storage', 'samplestorage', 'sample.jpg');
204 return file_get_contents($filename);
207 public function put(string $data, string $reference = '')
209 if ($reference === '') {
210 $reference = 'sample';
212 // we don't save $data !
216 public function delete(string $reference)
218 // we pretend to delete the data
222 public function getOptions()
224 $filename = $this->config->get('storage', 'samplestorage', 'sample.jpg');
227 'input', // will use a simple text input
228 $this->l10n->t('The file to return'), // the label
229 $filename, // the current value
230 $this->l10n->t('Enter the path to a file'), // the help text
231 // no extra data for 'input' type..
236 public function saveOptions(array $data)
238 // the keys in $data are the same keys we defined in getOptions()
239 $newfilename = trim($data['filename']);
241 // this function should always validate the data.
242 // in this example we check if file exists
243 if (!file_exists($newfilename)) {
244 // in case of error we return an array with
245 // ['optionname' => 'error message']
246 return ['filename' => 'The file doesn\'t exists'];
249 $this->config->set('storage', 'samplestorage', $newfilename);
251 // no errors, return empty array
255 public function __toString()
260 public static function getName()
267 Now the plugin main file. Here we register and unregister the backend class.
269 The file is `addon/samplestorage/samplestorage.php`
274 * Name: Sample Storage Addon
275 * Description: A sample addon which implements an unusefull storage backend
277 * Author: Alice <https://alice.social/~alice>
280 use Friendica\Addon\samplestorage\SampleStorageBackend;
283 function samplestorage_install()
285 // on addon install, we register our class with name "Sample Storage".
286 // note: we use `::class` property, which returns full class name as string
287 // this save us the problem of correctly escape backslashes in class name
288 DI::storageManager()->register(SampleStorageBackend::class);
291 function samplestorage_unistall()
293 // when the plugin is uninstalled, we unregister the backend.
294 DI::storageManager()->unregister(SampleStorageBackend::class);
297 function samplestorage_storage_instance(\Friendica\App $a, array $data)
299 if ($data['name'] === SampleStorageBackend::getName()) {
300 // instance a new sample storage instance and pass it back to the core for usage
301 $data['storage'] = new SampleStorageBackend(DI::config(), DI::l10n(), DI::cache());
306 **Theoretically - until tests for Addons are enabled too - create a test class with the name `addon/tests/SampleStorageTest.php`:
309 use Friendica\Model\Storage\IWritableStorage;
310 use Friendica\Test\src\Model\Storage\StorageTest;
312 class SampleStorageTest extends StorageTest
314 // returns an instance of your newly created storage class
315 protected function getInstance()
317 // create a new SampleStorageBackend instance with all it's dependencies
318 // Have a look at DatabaseStorageTest or FilesystemStorageTest for further insights
319 return new SampleStorageBackend();
322 // Assertion for the option array you return for your new StorageClass
323 protected function assertOption(IWritableStorage $storage)
325 $this->assertEquals([
328 'The file to return',
330 'Enter the path to a file'
332 ], $storage->getOptions());