Вікі-код для 3. Власні API методи

Версія 5.1 додана 2024/05/12 20:38 автором Ashterix

Показати останніх авторів
1 {{box cssClass="floatinginfobox" title="**Зміст**"}}
2 {{toc/}}
3 {{/box}}
4
5 Ви можете легко додавати власні API методи до RPC сервера.
6
7 Для цього вам достатньо в будь-якому місці вашого додатку зробити будь-який клас який має стати API Сервісом, цей клас має реалізувати інтерфейс (% class="box code" %)Ufo\JsonRpcBundle\ApiMethod\Interfaces\IRpcService(%%). Цей інтерфейс не навʼязує класу жодної логіки, він необхідний лише для того, щоб Symfony зрозумів, що має його сприймати як сервіс, що доступний для RPC сервера.
8
9 Реалізуйте в вашому класі будь-який публічний метод і він автоматично буде доступний як API Сервіс.
10
11 (% id="cke_bm_318406S" style="display:none" %) (%%)Після виконання попередніх вказівок у вас вже будуть доступні нові методи в API. За замовченням назви методів складаються з (% class="box code" %)<className>.<methodName>(%%).
12
13 = Іменування класів =
14
15 В разі потреби, ви можете створити кілька класів, що будуть доступні як API Сервіси. 
16 Враховуючи їх неймінги ​**<className>.<methodName>**​, рекомендую підходити до вибору назви методу як до простої вказівки що він робить, а до назви класу як до неймспейсу API методу.
17
18 (% class="box successmessage" %)
19 (((
20 == **Гарна практика** ==
21
22 Класс **//Messenger//** містить методи **//sendEmail()//**//,** sendSms()**//,// //класс// **CartResolver** //містить методи **//addProduct()//**//,** getProducts()**//, //**calculateDiscount()**//
23
24 в API будуть доступні методи
25
26 * //**CartResolver.addProduct**//
27 * //**CartResolver.getProducts**//
28 * //**CartResolver.calculateDiscount**//
29 * **//Messenger.sendEmail//**
30 * **//Messenger.sendSms//**
31
32 Навіть просто поглянувши на назви методів зрозуміло що може робити ваш сервер.
33
34 Такий підхід надає можливість використовувати одноіменні методи в різних класах:
35
36 * //**ProductService.create**//
37 * //**ProductService.getName**//
38 * //**UserService.create**//
39 * //**UserService.getName**//
40 )))
41
42 = Простий старт =
43
44 Наступний приклад має продемонструвати легкість додавання ваших методів до API.
45
46 (% class="row" %)
47 (((
48 (% class="col-xs-12 col-sm-6" %)
49 (((
50 (% class="box" %)
51 (((
52 == Код ==
53
54 (% class="code" %)
55 (((
56 (% class="linenoswrapper" %)
57 (((
58 (% class="linenos" %)
59 (((
60 1
61 2
62 3
63 4
64 5
65 6
66 7
67 8
68 9
69 10
70 11
71 12
72 13
73 14
74 15
75 16
76 17
77 18
78 19
79 20
80 21
81 22
82 23
83 24
84 25
85 26
86 27
87 28
88 29
89 )))
90
91 (((
92 (% style="color:#bc7a00" %)<?php(%%)
93 (% style="color:#008000; font-weight:bold" %)**namespace**(%%) App\Api\Procedures;
94 \\(% style="color:#008000; font-weight:bold" %)**use**(%%) Ufo\JsonRpcBundle\ApiMethod\Interfaces\IRpcService;
95 \\(% style="color:#008000; font-weight:bold" %)**class**(%%) (% style="color:#0000ff; font-weight:bold" %)**ExampleApi**(%%) (% style="color:#008000; font-weight:bold" %)**implements**(%%) IRpcService
96 {
97 (% style="color:#008000; font-weight:bold" %)**public**(%%) (% style="color:#008000; font-weight:bold" %)**function**(%%) (% style="color:#0000ff" %)~_~_construct(%%)(
98 (% style="color:#408080; font-style:italic" %)//~/~/ connecting some dependencies to retrieve data//(%%)
99 ) {}
100
101 (% style="color:#008000; font-weight:bold" %)**public**(%%) (% style="color:#008000; font-weight:bold" %)**function**(%%) (% style="color:#0000ff" %)getUserNameByUuid(%%)(
102 string (% style="color:#19177c" %)$userId(%%)
103 )(% style="color:#666666" %):(%%) string
104 {
105 (% style="color:#408080; font-style:italic" %)//~/~/ some logic get user info by id//(%%)
106 (% style="color:#008000; font-weight:bold" %)**return**(%%) (% style="color:#ba2121" %)'some result'(%%);
107 }
108
109 (% style="color:#008000; font-weight:bold" %)**public**(%%) (% style="color:#008000; font-weight:bold" %)**function**(%%) (% style="color:#0000ff" %)sendEmail(%%)(
110 string (% style="color:#19177c" %)$email(%%),
111 string (% style="color:#19177c" %)$text(%%),
112 string (% style="color:#19177c" %)$subject(%%) (% style="color:#666666" %)=(%%) (% style="color:#ba2121" %)'Message without subject'(%%)
113 )(% style="color:#666666" %):(%%) bool
114 {
115 (% style="color:#408080; font-style:italic" %)//~/~/ some logic send email//(%%)
116 (% style="color:#008000; font-weight:bold" %)**return**(%%) (% style="color:#008000; font-weight:bold" %)**true**(%%);
117 }
118 }
119 )))
120 )))
121 )))
122 )))
123
124 Праворуч приклад документації, що сервер згенерує по цьому класу.
125
126 Основна інформація щодо назв параметрів, їх типів та опціональності отримується завдяки (% class="box code" %)ReflectionClass(%%), важливим є порядок аргументів методу, їх typehint.
127 )))
128
129 (% class="col-xs-12 col-sm-6" %)
130 (((
131 (% class="box" %)
132 (((
133 == Документація ==
134
135 (% class="code" %)
136 (((
137 (% class="linenoswrapper" %)
138 (((
139 (% class="linenos" %)
140 (((
141 1
142 2
143 3
144 4
145 5
146 6
147 7
148 8
149 9
150 10
151 11
152 12
153 13
154 14
155 15
156 16
157 17
158 18
159 19
160 20
161 21
162 22
163 23
164 24
165 25
166 26
167 27
168 28
169 29
170 30
171 31
172 32
173 33
174 34
175 35
176 36
177 37
178 38
179 39
180 40
181 41
182 42
183 43
184 44
185 45
186 )))
187
188 (((
189 {
190 (% style="color:#008000; font-weight:bold" %)**"methods"**(%%): {
191 (% style="color:#008000; font-weight:bold" %)**"ExampleApi.getUserNameByUuid"**(%%): {
192 (% style="color:#008000; font-weight:bold" %)**"name"**(%%): (% style="color:#ba2121" %)"ExampleApi.getUserNameByUuid"(%%),
193 (% style="color:#008000; font-weight:bold" %)**"description"**(%%): (% style="color:#ba2121" %)""(%%),
194 (% style="color:#008000; font-weight:bold" %)**"parameters"**(%%): {
195 (% style="color:#008000; font-weight:bold" %)**"userId"**(%%): {
196 (% style="color:#008000; font-weight:bold" %)**"type"**(%%): (% style="color:#ba2121" %)"string"(%%),
197 (% style="color:#008000; font-weight:bold" %)**"name"**(%%): (% style="color:#ba2121" %)"userId"(%%),
198 (% style="color:#008000; font-weight:bold" %)**"description"**(%%): (% style="color:#ba2121" %)""(%%),
199 (% style="color:#008000; font-weight:bold" %)**"optional"**(%%): (% style="color:#008000; font-weight:bold" %)**false**(%%)
200 }
201 },
202 (% style="color:#008000; font-weight:bold" %)**"returns"**(%%): (% style="color:#ba2121" %)"string"(%%),
203 (% style="color:#008000; font-weight:bold" %)**"responseFormat"**(%%): (% style="color:#ba2121" %)"string"(%%)
204 },
205 (% style="color:#008000; font-weight:bold" %)**"ExampleApi.sendEmail"**(%%): {
206 (% style="color:#008000; font-weight:bold" %)**"name"**(%%): (% style="color:#ba2121" %)"ExampleApi.sendEmail"(%%),
207 (% style="color:#008000; font-weight:bold" %)**"description"**(%%): (% style="color:#ba2121" %)""(%%),
208 (% style="color:#008000; font-weight:bold" %)**"parameters"**(%%): {
209 (% style="color:#008000; font-weight:bold" %)**"email"**(%%): {
210 (% style="color:#008000; font-weight:bold" %)**"type"**(%%): (% style="color:#ba2121" %)"string"(%%),
211 (% style="color:#008000; font-weight:bold" %)**"name"**(%%): (% style="color:#ba2121" %)"email"(%%),
212 (% style="color:#008000; font-weight:bold" %)**"description"**(%%): (% style="color:#ba2121" %)""(%%),
213 (% style="color:#008000; font-weight:bold" %)**"optional"**(%%): (% style="color:#008000; font-weight:bold" %)**false**(%%)
214 },
215 (% style="color:#008000; font-weight:bold" %)**"text"**(%%): {
216 (% style="color:#008000; font-weight:bold" %)**"type"**(%%): (% style="color:#ba2121" %)"string"(%%),
217 (% style="color:#008000; font-weight:bold" %)**"name"**(%%): (% style="color:#ba2121" %)"text"(%%),
218 (% style="color:#008000; font-weight:bold" %)**"description"**(%%): (% style="color:#ba2121" %)""(%%),
219 (% style="color:#008000; font-weight:bold" %)**"optional"**(%%): (% style="color:#008000; font-weight:bold" %)**false**(%%)
220 },
221 (% style="color:#008000; font-weight:bold" %)**"subject"**(%%): {
222 (% style="color:#008000; font-weight:bold" %)**"type"**(%%): (% style="color:#ba2121" %)"string"(%%),
223 (% style="color:#008000; font-weight:bold" %)**"name"**(%%): (% style="color:#ba2121" %)"subject"(%%),
224 (% style="color:#008000; font-weight:bold" %)**"description"**(%%): (% style="color:#ba2121" %)""(%%),
225 (% style="color:#008000; font-weight:bold" %)**"optional"**(%%): (% style="color:#008000; font-weight:bold" %)**true**(%%),
226 (% style="color:#008000; font-weight:bold" %)**"default"**(%%): (% style="color:#ba2121" %)"Message without subject"(%%)
227 }
228 },
229 (% style="color:#008000; font-weight:bold" %)**"returns"**(%%): (% style="color:#ba2121" %)"boolean"(%%),
230 (% style="color:#008000; font-weight:bold" %)**"responseFormat"**(%%): (% style="color:#ba2121" %)"boolean"(%%)
231 }
232 }
233 }
234 )))
235 )))
236 )))
237 )))
238 )))
239 )))
240
241 Тепер можемо зробити POST запити на обидва нових метода API і подивитися на результат.
242
243 == **POST запити** ==
244
245 (% class="row" %)
246 (((
247 (% class="col-xs-12 col-sm-6" %)
248 (((
249 (% class="box" %)
250 (((
251 Request
252
253 (% class="code" %)
254 (((
255 (% class="linenoswrapper" %)
256 (((
257 (% class="linenos" %)
258 (((
259 1
260 2
261 3
262 4
263 5
264 6
265 7
266 )))
267
268 (((
269 {
270 (% style="color:#008000; font-weight:bold" %)**"id"**(%%): (% style="color:#ba2121" %)"example_request"(%%),
271 (% style="color:#008000; font-weight:bold" %)**"method"**(%%): (% style="color:#ba2121" %)"ExampleApi.getUserNameByUuid"(%%),
272 (% style="color:#008000; font-weight:bold" %)**"params"**(%%): {
273 (% style="color:#008000; font-weight:bold" %)**"userId"**(%%): (% style="color:#ba2121" %)"1111"(%%)
274 }
275 }
276 )))
277 )))
278 )))
279 )))
280 )))
281
282 (% class="col-xs-12 col-sm-6" %)
283 (((
284 (% class="box" %)
285 (((
286 Response
287
288 (% class="code" %)
289 (((
290 (% class="linenoswrapper" %)
291 (((
292 (% class="linenos" %)
293 (((
294 1
295 2
296 3
297 4
298 5
299 )))
300
301 (((
302 {
303 (% style="color:#008000; font-weight:bold" %)**"id"**(%%): (% style="color:#ba2121" %)"example_request"(%%),
304 (% style="color:#008000; font-weight:bold" %)**"result"**(%%): (% style="color:#ba2121" %)"some result"(%%),
305 (% style="color:#008000; font-weight:bold" %)**"jsonrpc"**(%%): (% style="color:#ba2121" %)"2.0"(%%)
306 }
307 )))
308 )))
309 )))
310 )))
311
312
313
314 )))
315 )))
316
317 (% class="row" %)
318 (((
319 (% class="col-xs-12 col-sm-6" %)
320 (((
321 (% class="box" %)
322 (((
323 Request
324
325 (% class="code" %)
326 (((
327 (% class="linenoswrapper" %)
328 (((
329 (% class="linenos" %)
330 (((
331 1
332 2
333 3
334 4
335 5
336 6
337 7
338 8
339 9
340 )))
341
342 (((
343 {
344 (% style="color:#008000; font-weight:bold" %)**"id"**(%%): (% style="color:#ba2121" %)"example_request"(%%),
345 (% style="color:#008000; font-weight:bold" %)**"method"**(%%): (% style="color:#ba2121" %)"ExampleApi.sendEmail"(%%),
346 (% style="color:#008000; font-weight:bold" %)**"params"**(%%): {
347 (% style="color:#008000; font-weight:bold" %)**"email"**(%%): (% style="color:#ba2121" %)"user@example.com"(%%),
348 (% style="color:#008000; font-weight:bold" %)**"subject"**(%%): (% style="color:#ba2121" %)"This is test mail"(%%),
349 (% style="color:#008000; font-weight:bold" %)**"text"**(%%): (% style="color:#ba2121" %)"Hi! This is test send mail by API"(%%)
350 }
351 }
352 )))
353 )))
354 )))
355 )))
356 )))
357
358 (% class="col-xs-12 col-sm-6" %)
359 (((
360 (% class="box" %)
361 (((
362 Response
363
364 (% class="code" %)
365 (((
366 (% class="linenoswrapper" %)
367 (((
368 (% class="linenos" %)
369 (((
370 1
371 2
372 3
373 4
374 5
375 )))
376
377 (((
378 {
379 (% style="color:#008000; font-weight:bold" %)**"id"**(%%): (% style="color:#ba2121" %)"example_request"(%%),
380 (% style="color:#008000; font-weight:bold" %)**"result"**(%%): (% style="color:#008000; font-weight:bold" %)**true**(%%),
381 (% style="color:#008000; font-weight:bold" %)**"jsonrpc"**(%%): (% style="color:#ba2121" %)"2.0"(%%)
382 }
383 )))
384 )))
385 )))
386 )))
387 )))
388 )))
389
390 (% class="box warningmessage" %)
391 (((
392 Для спрощення сприйняття документації, всі подальші приклади буду надавати на одному методі (//**sendEmail**//)
393 )))
394
395 = Опис методів та параметрів =
396
397 Документатор спирається на всі наявні дані, що належать методу та його аргументам (назви, типи вхідних і вихідних даних, докблоки). Тож, опис методів і параметрів можна збагатити за рахунок докблоків.
398
399 Додамо опис методу і параметрів.
400
401 (% class="row" %)
402 (((
403 (% class="col-xs-12 col-sm-6" %)
404 (((
405 (% class="box" %)
406 (((
407 == Код ==
408
409 (% class="code" %)
410 (((
411 (% class="linenoswrapper" %)
412 (((
413 (% class="linenos" %)
414 (((
415 1
416 2
417 3
418 4
419 5
420 6
421 7
422 8
423 9
424 10
425 11
426 12
427 13
428 14
429 15
430 16
431 17
432 18
433 19
434 20
435 21
436 )))
437
438 (((
439 (% style="color:#bc7a00" %)<?php(%%)
440 (% style="color:#408080; font-style:italic" %)//~/~/ ...//
441
442 (% style="color:#ba2121; font-style:italic" %)///~*~*
443 ~* A method for sending an email message
444 ~* @param string $email The email address
445 ~* @param string $text Message body
446 ~* @param string $subject Optional message subject parameter
447 ~* @return bool
448 *///(%%)
449 (% style="color:#008000; font-weight:bold" %)**public**(%%) (% style="color:#008000; font-weight:bold" %)**function**(%%) (% style="color:#0000ff" %)sendEmail(%%)(
450 string (% style="color:#19177c" %)$email(%%),
451 string (% style="color:#19177c" %)$text(%%),
452 string (% style="color:#19177c" %)$subject(%%) (% style="color:#666666" %)=(%%) (% style="color:#ba2121" %)'Message without subject'(%%)
453 )(% style="color:#666666" %):(%%) bool
454 {
455 (% style="color:#408080; font-style:italic" %)//~/~/ some logic send email//(%%)
456 (% style="color:#008000; font-weight:bold" %)**return**(%%) (% style="color:#008000; font-weight:bold" %)**true**(%%);
457 }
458 \\(% style="color:#408080; font-style:italic" %)//~/~/ ...//
459 )))
460 )))
461 )))
462 )))
463
464 Зверніть увагу на документацію, тепер в ній відображається додаткова інформація про метод і його параметри.
465
466
467 )))
468
469 (% class="col-xs-12 col-sm-6" %)
470 (((
471 (% class="box" %)
472 (((
473 == Документація ==
474
475 (% class="code" %)
476 (((
477 (% class="linenoswrapper" %)
478 (((
479 (% class="linenos" %)
480 (((
481 1
482 2
483 3
484 4
485 5
486 6
487 7
488 8
489 9
490 10
491 11
492 12
493 13
494 14
495 15
496 16
497 17
498 18
499 19
500 20
501 21
502 22
503 23
504 24
505 25
506 26
507 27
508 28
509 29
510 30
511 31
512 )))
513
514 (((
515 {
516 (% style="color:#008000; font-weight:bold" %)**"methods"**(%%): {
517 (% style="color:#008000; font-weight:bold" %)**"ExampleApi.sendEmail"**(%%): {
518 (% style="color:#008000; font-weight:bold" %)**"name"**(%%): (% style="color:#ba2121" %)"ExampleApi.sendEmail"(%%),
519 (% style="color:#008000; font-weight:bold" %)**"description"**(%%): (% style="color:#ba2121" %)"A method for sending an email message"(%%),
520 (% style="color:#008000; font-weight:bold" %)**"parameters"**(%%): {
521 (% style="color:#008000; font-weight:bold" %)**"email"**(%%): {
522 (% style="color:#008000; font-weight:bold" %)**"type"**(%%): (% style="color:#ba2121" %)"string"(%%),
523 (% style="color:#008000; font-weight:bold" %)**"name"**(%%): (% style="color:#ba2121" %)"email"(%%),
524 (% style="color:#008000; font-weight:bold" %)**"description"**(%%): (% style="color:#ba2121" %)"The email address"(%%),
525 (% style="color:#008000; font-weight:bold" %)**"optional"**(%%): (% style="color:#008000; font-weight:bold" %)**false**(%%)
526 },
527 (% style="color:#008000; font-weight:bold" %)**"text"**(%%): {
528 (% style="color:#008000; font-weight:bold" %)**"type"**(%%): (% style="color:#ba2121" %)"string"(%%),
529 (% style="color:#008000; font-weight:bold" %)**"name"**(%%): (% style="color:#ba2121" %)"text"(%%),
530 (% style="color:#008000; font-weight:bold" %)**"description"**(%%): (% style="color:#ba2121" %)"Message body"(%%),
531 (% style="color:#008000; font-weight:bold" %)**"optional"**(%%): (% style="color:#008000; font-weight:bold" %)**false**(%%)
532 },
533 (% style="color:#008000; font-weight:bold" %)**"subject"**(%%): {
534 (% style="color:#008000; font-weight:bold" %)**"type"**(%%): (% style="color:#ba2121" %)"string"(%%),
535 (% style="color:#008000; font-weight:bold" %)**"name"**(%%): (% style="color:#ba2121" %)"subject"(%%),
536 (% style="color:#008000; font-weight:bold" %)**"description"**(%%): (% style="color:#ba2121" %)"Optional message subject parameter"(%%),
537 (% style="color:#008000; font-weight:bold" %)**"optional"**(%%): (% style="color:#008000; font-weight:bold" %)**true**(%%),
538 (% style="color:#008000; font-weight:bold" %)**"default"**(%%): (% style="color:#ba2121" %)"Message without subject"(%%)
539 }
540 },
541 (% style="color:#008000; font-weight:bold" %)**"returns"**(%%): (% style="color:#ba2121" %)"boolean"(%%),
542 (% style="color:#008000; font-weight:bold" %)**"responseFormat"**(%%): (% style="color:#ba2121" %)"boolean"(%%)
543 }
544 }
545 }
546 )))
547 )))
548 )))
549 )))
550 )))
551 )))
552
553 = RPC attributes =
554
555 Для більш гнучкого налаштування ваших методів API JsonRpcBundle використовує такий інструмент як [[php атрибути>>url:https://www.php.net/manual/en/language.attributes.overview.php]].
556
557 За допомогою спеціалізованих атрибутів ви можете:
558
559 * налаштувати псевдоніми для методів;
560 * вказати формат відповіді для методів (якщо відповідь у вигляді масива, обʼєкта або колекції обʼєктів);
561 * налаштувати валідацію вхідних параметрів;
562 * налаштувати кешування відповідей.
563
564 Докладніше про ці атрибути:
565
566 (% class="xtree" data-checkboxes="false" data-contextmenu="false" data-draganddrop="false" data-edges="true" data-finder="false" data-icons="true" data-responsive="true" data-url="/bin/get/docs/JsonRpcBundle/add_rpc_service/WebHome?outputSyntax=plain&sheet=XWiki.DocumentTree&root=document%3A" %)
567 (((
568
569 )))
570
571 (% class="wikigeneratedid" id="H41F44143543243443E43D45643C438API43C43544243E434456432" %)
572