-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
433 lines (372 loc) · 13.6 KB
/
index.html
File metadata and controls
433 lines (372 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Building an API with Yii2</title>
<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
<meta name="author" content="Hakim El Hattab">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/black.css" id="theme">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h2>Building a RESTful API with Yii2</h2>
<p> </p>
<p> </p>
<p> </p>
<p>Presented by Damien Buttler</p>
<p>
<small>phpMelb - March 15, 2016</small>
</p>
</section>
<section data-background="#dddddd">
<h2>What is an API?</h2>
</section>
<section>
<h3>What's an API?</h3>
<p>
An API is an Application Programming Interface that is designed to allow other programs to interact with it.
</p>
<p>
To create/update/read/delete data through agnostic interface.
</p>
</section>
<section>
<h3>What is a RESTful API?</h3>
<p>Representational State Transfer</p>
<p>REST is an architectural style consisting of a coordinated set of architectural constraints applied to components, connectors, and data elements, within a distributed hypermedia system.</p>
</section>
<section>
<h3>Basic RESTful request Types</h3>
<table>
<tr><td>Action</td><td>Method</td><td>URL Example</td></tr>
<tr><td>Create record</td><td>POST</td><td>http://domain.com/user</td></tr>
<tr><td>Update record</td><td>PUT</td><td>http://domain.com/user/{id}</td></tr>
<tr><td>List records</td><td>GET</td><td>http://domain.com/user</td></tr>
<tr><td>View record</td><td>GET</td><td>http://domain.com/user/{id}</td></tr>
<tr><td>Delete record</td><td>DELETE</td><td>http://domain.com/user/{id}</td></tr>
</table>
</section>
<section data-background="#dddddd">
<h2>Building the API with Yii2</h2>
</section>
<section>
<h2>Install Yii</h2>
<pre>
<code>
composer global require "fxp/composer-asset-plugin:~1.1.1"
composer create-project --prefer-dist yiisoft/yii2-app-advanced yii-application
./init (and follow prompts)
</code>
</pre>
</section>
<section>
<h2>Configure Database</h2>
<pre>Add file: common/config/db.php
<code>
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=phpmelb',
'username' => 'phpmelb',
'password' => 'phpmelb',
'charset' => 'utf8',
];
</code>
</pre>
</section>
<section>
<pre>
Include config for frontend: frontend/config/main.php and console/config/main.php
<code>
'db' => require(__DIR__ .'/../../common/config/db.php'),
</code>
</pre>
<pre>
Run migration:
<code>
./yii migrate
</code>
</pre>
</section>
<section>
<pre>
Run Gii to create model Class:
<code>
./yii gii/model --tableName=user --modelClass=User
</code>
</pre>
<pre>
Move file from console/models to common/models and change namespace to:
<code>
namespace common\models;
</code>
</pre>
</section>
<section>
<pre>
Configure Gii in frontend/config/main.php
<code>
'modules' => [
'gii' => [
'class' => 'yii\gii\Module',
'allowedIPs' => ['192.168.10.1'],
],
],
</code>
</pre>
<pre>
And run gii from to create the User controller:
<code>
http://phpmelb.api/index.php?r=gii
</code>
</pre>
</section>
<section>
<h3>Configure application as a RESTful API</h3>
<p><small>From guide: http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html</small></p>
<pre>
Edit frontend/controllers/UserController.php
<code>
<?php
namespace frontend\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'common\models\User';
}
</code>
</pre>
</section>
<section>
<pre>
Pretty Urls: Edit frontend/config/main.php
<code>
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'user', 'pluralize' => false],
],
],</code></pre>
<pre>
Allow Json input: Edit frontend/config/main.php
<code>
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],</code></pre>
</section>
<section>
<h3>User creation payload</h3>
<pre>
POST: http://phpmelb.api/user/create
<code>
{
"username": "bob",
"email": "bob@gmail.com",
"password_hash":"mypassword"
}
</code></pre>
</section>
<section>
<h3>User View</h3>
<pre>
View user and its attributes: GET http://phpmelb.api/user/1
<code>
{
"id": 1,
"username": "bob",
"email": "bob@gmail.com",
"password_hash":"mypassword"
}
</code></pre>
<pre>
Restrict field outputs. Add fields method to common/models/User.php
<code>
public function fields()
{
return [
'id',
'username',
'email',
];
}
</code></pre>
</section>
<section>
<h3>Default API Response Headers</h3>
<pre>
<code>
X-Pagination-Current-Page => 1
X-Pagination-Page-Count => 1
X-Pagination-Per-Page => 20
X-Pagination-Total-Count => 2
</code></pre>
</section>
<section>
<h3>Refining result set</h3>
<table>
<tr><td>Limit results per page</td><td>?per-page=3</td></tr>
<tr><td>Show specific page</td><td>?page=2</td></tr>
</table>
</section>
<section>
<h3>Overriding actions and further refining of results</h3>
<pre>
Edit frontend/controllers/UserController.php
<code>
public function actions()
{
$actions = parent::actions();
$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
return $actions;
}
public function prepareDataProvider()
{
$searchModel = new \common\models\UserSearch();
return $searchModel->search(Yii::$app->request->queryParams);
}
</code></pre>
</section>
<section>
<h3>Use Gii CRUD tool to generate User Search file</h3>
<pre>
Modify load params method in common/models/UserSearch.php:
<code>
$this->load($params, '');
</code></pre>
<pre>
And filter by model attributes:
<code>
?username=bob
</code></pre>
<pre>
And filter by pseudo attributes:
<code>
?time_from=2016-01-01 10:00:00&time_to=2016-01-31 23:59:59</code><code>
->andFilterWhere(['between', 'created_at', $this->time_from, $this->time_to]);</code></pre>
</section>
<section data-background="#dddddd">
<h3>Behaviours</h3>
<p>Adding behaviours to the API. Behaviours is a way to allow Yii/PHP to work around the limitation that PHP can only extend one class.</p>
</section>
<section>
<pre>
Add CORS and Auth behaviours. CORS filter must be first.
<code>
public function behaviors()
{
return ArrayHelper::merge([
'corsFilter' => [
'class' => Cors::className(),
],
[
'class' => HttpBearerAuth::className(),
'except' => ['options'],
],
], parent::behaviors());
return $behaviors;
}
</code></pre>
</section>
<section data-background="#dddddd">
<h3>Adding User Auth</h3>
<p>New methods need to be added to both the user controller and model. It would be
easier to refer to the commit on <a href="https://github.com/doublehops/yii-api-vm/commit/1f61861a57f4fb17d7145e0661db4187442b6978">Github</a></p>
</section>
<section>
<p>Adding behaviours to the base model</h3>
<pre>
Add to common/models/BaseModel.php
<code>
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => function() { return date('Y-m-d H:i:s'); },
],
[
'class' => BlameableBehavior::className(),
'createdByAttribute' => 'created_by',
'updatedByAttribute' => 'updated_by',
],
];
}
</code></pre>
</section>
<section data-background="#dddddd">
<h3>Adding an Admin Backend</h3>
</section>
<section>
<p>Adding a standard Yii web admin backend by running the the Gii CRUD tool to build the backend files.</p>
<p>Point browser to backend domain: eg. http://admin.domain.com/index.php?r=user</p>
</section>
<section>
<p>This user list page is automatically generated by Gii</p>
<img src="img/yii2-api-admin.png" />
</section>
<section>
<p>This user update page is automatically generated by Gii</p>
<img src="img/yii2-api-admin-update.png" />
</section>
<section data-background="#dddddd">
<h2>Building a RESTful API with Yii2</h2>
<p> </p>
<p>Presentation: <a href="https://doublehops.com/presentations/yii2-api-presentation/">https://doublehops.com/presentations/yii2-api-presentation/</a></p>
<p>VM and sample code: <a href="https://github.com/doublehops/yii-api-vm">https://github.com/doublehops/yii-api-vm</a></p>
<p> </p>
<p>Presented by Damien Buttler</p>
<p>
<small>phpMelb - March 15, 2016</small>
</p>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// Full list of configuration options available at:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
transition: 'slide', // none/fade/slide/convex/concave/zoom
// Optional reveal.js plugins
dependencies: [
{ src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'plugin/zoom-js/zoom.js', async: true },
{ src: 'plugin/notes/notes.js', async: true }
]
});
</script>
</body>
</html>