]> git.mxchange.org Git - friendica.git/blob - doc/AddonStorageBackend.md
72e146779326829a77c40b69d11857f944bc9162
[friendica.git] / doc / AddonStorageBackend.md
1 Friendica Storage Backend Addon development
2 ===========================================
3
4 * [Home](help)
5
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.
8
9 ## The Storage Backend Class
10
11 The class must live in `Friendica\Addon\youraddonname` namespace, where `youraddonname` the folder name of your addon.
12
13 The class must implement `Friendica\Model\Storage\ISelectableStorage` interface. All method in the interface must be implemented:
14
15 namespace Friendica\Model\ISelectableStorage;
16
17 ```php
18 interface ISelectableStorage
19 {
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();
27 }
28 ```
29
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`
33
34 Each storage backend can have options the admin can set in admin page.
35
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.
38
39 The array returned by `getOptions()` is defined as:
40
41         [
42                 'option1name' => [ ..info.. ],
43                 'option2name' => [ ..info.. ],
44                 ...
45         ]
46
47 An empty array can be returned if backend doesn't have any options.
48
49 The info array for each option is defined as:
50
51         [
52                 'type',
53
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'
56
57                 'label',
58
59 Translatable label of the field. This label will be shown in admin page
60
61                 value,
62
63 Current value of the option
64
65                 'help text',
66
67 Translatable description for the field. Will be shown in admin page
68
69                 extra data
70
71 Optional. Depends on which 'type' this option is:
72
73 - 'select': array `[ value => label ]` of choices
74 - 'intcheckbox': value of input element
75 - 'select_raw': prebuild html string of `<option >` tags
76
77 Each label should be translatable
78
79         ];
80
81
82 See doxygen documentation of `ISelectableStorage` interface for details about each method.
83
84 ## Register a storage backend class
85
86 Each backend must be registered in the system when the plugin is installed, to be aviable.
87
88 `DI::facStorage()->register(string $class)` is used to register the backend class.
89
90 When the plugin is uninstalled, registered backends must be unregistered using
91 `DI::facStorage()->unregister(string $class)`.
92
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.
96
97 This is necessary because it isn't always clear, if you need further construction arguments.
98
99 ## Adding tests
100
101 **Currently testing is limited to core Friendica only, this shows theoretically how tests should work in the future**
102
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/).
104
105 Add a new test class which's naming convention is `StorageClassTest`, which extend the `StorageTest` in the same directory.
106
107 Override the two necessary instances:
108 ```php
109 use Friendica\Model\Storage\ISelectableStorage;
110
111 abstract class StorageTest 
112 {
113         // returns an instance of your newly created storage class
114         abstract protected function getInstance();
115
116         // Assertion for the option array you return for your new StorageClass
117         abstract protected function assertOption(ISelectableStorage $storage);
118
119 ```
120
121 ## Exception handling
122
123 There are two intended types of exceptions for storages
124
125 ### `StorageException`
126
127 This is the common exception in case unexpected errors happen using the storage backend.
128 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.
129
130 Example:
131
132 ```php
133 use Friendica\Model\Storage\ISelectableStorage;
134
135 class ExampleStorage implements ISelectableStorage 
136 {
137         public function get(string $reference) : string
138         {
139                 try {
140                         throw new Exception('a real bad exception');
141                 } catch (Exception $exception) {
142                         throw new \Friendica\Model\Storage\StorageException(sprintf('The Example Storage throws an exception for reference %s', $reference), 500, $exception);
143                 }
144         }
145
146 ```
147
148 ### `ReferenceStorageExecption`
149
150 This storage exception should be used in case the caller tries to use an invalid references.
151 This could happen in case the caller tries to delete or update an unknown reference.
152 The implementation of the storage backend must not ignore invalid references.
153
154 Avoid throwing the common `StorageExecption` instead of the `ReferenceStorageException` at this particular situation!
155
156 ## Example
157
158 Here an hypotetical addon which register a useless storage backend.
159 Let's call it `samplestorage`.
160
161 This backend will discard all data we try to save and will return always the same image when we ask for some data.
162 The image returned can be set by the administrator in admin page.
163
164 First, the backend class.
165 The file will be `addon/samplestorage/SampleStorageBackend.php`:
166
167 ```php
168 <?php
169 namespace Friendica\Addon\samplestorage;
170
171 use Friendica\Model\Storage\ISelectableStorage;
172
173 use Friendica\Core\Config\IConfig;
174 use Friendica\Core\L10n;
175
176 class SampleStorageBackend implements ISelectableStorage
177 {
178         const NAME = 'Sample Storage';
179
180         /** @var IConfig */
181         private $config;
182         /** @var L10n */
183         private $l10n;
184
185         /**
186           * SampleStorageBackend constructor.
187           * @param IConfig $config The configuration of Friendica
188           *                                                                       
189           * You can add here every dynamic class as dependency you like and add them to a private field
190           * Friendica automatically creates these classes and passes them as argument to the constructor                                                                           
191           */
192         public function __construct(IConfig $config, L10n $l10n) 
193         {
194                 $this->config = $config;
195                 $this->l10n   = $l10n;
196         }
197
198         public function get(string $reference)
199         {
200                 // we return always the same image data. Which file we load is defined by
201                 // a config key
202                 $filename = $this->config->get('storage', 'samplestorage', 'sample.jpg');
203                 return file_get_contents($filename);
204         }
205         
206         public function put(string $data, string $reference = '')
207         {
208                 if ($reference === '') {
209                         $reference = 'sample';
210                 }
211                 // we don't save $data !
212                 return $reference;
213         }
214         
215         public function delete(string $reference)
216         {
217                 // we pretend to delete the data
218                 return true;
219         }
220         
221         public function getOptions()
222         {
223                 $filename = $this->config->get('storage', 'samplestorage', 'sample.jpg');
224                 return [
225                         'filename' => [
226                                 'input',        // will use a simple text input
227                                 $this->l10n->t('The file to return'),   // the label
228                                 $filename,      // the current value
229                                 $this->l10n->t('Enter the path to a file'), // the help text
230                                 // no extra data for 'input' type..
231                         ],
232                 ];
233         }
234         
235         public function saveOptions(array $data)
236         {
237                 // the keys in $data are the same keys we defined in getOptions()
238                 $newfilename = trim($data['filename']);
239                 
240                 // this function should always validate the data.
241                 // in this example we check if file exists
242                 if (!file_exists($newfilename)) {
243                         // in case of error we return an array with
244                         // ['optionname' => 'error message']
245                         return ['filename' => 'The file doesn\'t exists'];
246                 }
247                 
248                 $this->config->set('storage', 'samplestorage', $newfilename);
249                 
250                 // no errors, return empty array
251                 return [];
252         }
253
254         public function __toString()
255         {
256                 return self::NAME;
257         }
258
259         public static function getName()
260         {
261                 return self::NAME;
262         }
263 }
264 ```
265
266 Now the plugin main file. Here we register and unregister the backend class.
267
268 The file is `addon/samplestorage/samplestorage.php`
269
270 ```php
271 <?php
272 /**
273  * Name: Sample Storage Addon
274  * Description: A sample addon which implements an unusefull storage backend
275  * Version: 1.0.0
276  * Author: Alice <https://alice.social/~alice>
277  */
278
279 use Friendica\Addon\samplestorage\SampleStorageBackend;
280 use Friendica\DI;
281
282 function samplestorage_install()
283 {
284         // on addon install, we register our class with name "Sample Storage".
285         // note: we use `::class` property, which returns full class name as string
286         // this save us the problem of correctly escape backslashes in class name
287         DI::storageManager()->register(SampleStorageBackend::class);
288 }
289
290 function samplestorage_unistall()
291 {
292         // when the plugin is uninstalled, we unregister the backend.
293         DI::storageManager()->unregister(SampleStorageBackend::class);
294 }
295
296 function samplestorage_storage_instance(\Friendica\App $a, array $data)
297 {
298     if ($data['name'] === SampleStorageBackend::getName()) {
299     // instance a new sample storage instance and pass it back to the core for usage
300         $data['storage'] = new SampleStorageBackend(DI::config(), DI::l10n(), DI::cache());
301     }
302 }
303 ```
304
305 **Theoretically - until tests for Addons are enabled too - create a test class with the name `addon/tests/SampleStorageTest.php`:
306
307 ```php
308 use Friendica\Model\Storage\ISelectableStorage;
309 use Friendica\Test\src\Model\Storage\StorageTest;
310
311 class SampleStorageTest extends StorageTest 
312 {
313         // returns an instance of your newly created storage class
314         protected function getInstance()
315         {
316                 // create a new SampleStorageBackend instance with all it's dependencies
317                 // Have a look at DatabaseStorageTest or FilesystemStorageTest for further insights
318                 return new SampleStorageBackend();
319         }
320
321         // Assertion for the option array you return for your new StorageClass
322         protected function assertOption(ISelectableStorage $storage)
323         {
324                 $this->assertEquals([
325                         'filename' => [
326                                 'input',
327                                 'The file to return',
328                                 'sample.jpg',
329                                 'Enter the path to a file'
330                         ],
331                 ], $storage->getOptions());
332         }
333
334 ```