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

Версія 4.1 додана 2024/05/10 11:06 автором Ashterix

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