-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1710 lines (1431 loc) · 61.5 KB
/
Copy pathindex.html
File metadata and controls
1710 lines (1431 loc) · 61.5 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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CandyJs js DOC</title>
<meta name="keywords" content="CandyJs MVC Framework Restful API">
<meta name="description" content="一个面向对象的高效 node.js MVC and REST 框架">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" >
<style>
blockquote {font-size: 14px;}
blockquote.bg-danger {
border-left-color: #cc3322;
}
blockquote.bg-info {
border-left-color: #1b809e;
}
footer {
background-color: #222;
color: #fff;
padding: 20px 0;
}
</style>
</head>
<body>
<header>
<nav class="navbar navbar-inverse">
<div class="container">
<a target="_blank" class="navbar-brand" href="https://github.com/candyframework/candyjs">CandyJs</a>
</div>
</nav>
</header>
<div style="margin-top: 60px" class="container">
<div class="row">
<div class="col-md-9">
<h1>
一个面向对象的高效 MVC and REST 框架
</h1>
<p>
<code>CandyJs</code>是一个健壮可扩展的 Web 框架,它提供了一套优雅的编写代码的规范,使得编写 Web 应用变得得心应手。
</p>
<p>
<code>CandyJs</code>实现了一套<code>动态路由</code>规范,您不需要提前注册所需要的路由,只需要输入网址<code>CandyJs</code>会自己找到路由对应的组件。
</p>
<p>
<code>CandyJs</code>实现了正则路由的合并,多个正则路由我们会将其合成一个大路由,避免了路由逐个匹配带来的巨大性能损失
</p>
<h1 class="page-header"><a href="./index_en.html">英文</a></h1>
<h1 class="page-header">入门</h1>
<h4><b>通过 cli 工具安装 candyjs</b></h4>
<pre><code>
$ npm install -g @candyjs/cli
$
$ # 运行命令 按照提示进行操作
$ candyjs-cli
</code></pre>
<blockquote class="bg-info">
<p>cli 工具目前只能用于创建项目。其他功能未实现</p>
</blockquote>
<h1 class="page-header" id="firstrun"><b>第一次运行程序</b></h1>
<p>执行命令后,进入项目目录安装依赖</p>
<p>上述工具会生成一个 MVC 模式 Hello word 程序,如果只想要写一些接口程序,请看<a href="#restful">这里</a></p>
<p>项目目录结构如下</p>
<pre><code>
PROJECT_NAME
|
|- index.js
|
|- app
| |
| |-- controllers 普通控制器目录
| |
| |-- index
| | |
| | |-- IndexController.js
| |
| -- views
| |
| |-- index
| | |
| | |-- index.html
</code></pre>
<p>进入 PROJECT_NAME 目录,启动程序</p>
<pre><code>$ npm install && npm run start</code></pre>
<p>访问程序</p>
<pre><code><a href="http://localhost:2333" target="_blank">http://localhost:2333</a></code></pre>
<h1 class="page-header" id="appstruct">应用结构</h1>
<h4><b>一个比较完整的应用目录结构如下</b></h4>
<pre><code>
PROJECT_NAME
|
|- index.js
|
|- node_modules
|
|- public 目录 一般存放静态文件
|
|- app 项目目录
| |
| |-- controllers
| |
| |-- user
| | |
| | |-- IndexController.js - host:port/user/index 可以访问到该类
| | |-- OtherController.js - host:port/user/other 可以访问到该类
| |
| |-- goods
| | |
| | |-- IndexController.js - host:port/goods/index 可以访问到该类
| | |-- OtherController.js - host:port/goods/other 可以访问到该类
| |
| -- views 普通控制器模板目录
| |
| |-- user 用户组模板 对应上面用户组
| | |
| | |-- index.html
| | |-- other.html
| |
| |-- goods 商品组模板
| | |
| | |-- index.html
| | |-- other.html
| |
| -- modules 模块
| |
| |-- newYearActivity
| | |
| | |-- controllers 模块控制器目录 其下无子目录
| | | |
| | | |-- IndexController.js
| | |
| | |-- views 模块模板目录
| | | |
| | | |-- index.html
| | |
| | |-- 其他目录
| |
| -- runtime 缓存目录
|
</pre></code>
<h4><b>入口脚本<code>index.js</code></b></h4>
<p>
入口脚本是应用启动流程中的第一环,一个应用只有一个入口脚本。
入口脚本包含启动代码,程序启动后就会监听客户端的连接
</p>
<p>
入口脚本主要完成以下工作
<ul>
<li>加载应用配置</li>
<li>启动应用</li>
<li>注册各种需要组件</li>
</ul>
</p>
<pre><code>
var CandyJs = require('candyjs');
var App = require('candyjs/web/Application');
var app = new App({
'id': 1,
// 定义调试应用
'debug': true,
// 定义应用路径
'appPath': __dirname + '/app',
// 注册模块
'modules': {
'bbs': 'app/modules/bbs'
},
// 配置日志
'log': {
'targets': {
'file': {
'classPath': 'candy/log/file/Log'
}
}
}
});
new CandyJs(app).listen(2333, function(){
console.log('listen on 2333');
});
</pre></code>
<h4><b>应用</b></h4>
<p>
<code>CandyJs</code>包含两种应用:<code>Web 应用</code>和<code>Rest 应用</code>
</p>
<h4><b>应用属性</b></h4>
<p>在入口文件中可以传入各种参数,这些参数最终会被赋值到应用对象上</p>
<h6><b>必要属性</b></h6>
<ul>
<li>
<p><code>candy/web/Application.id</code> 该属性用来标识唯一应用</p>
</li>
<li>
<p><code>candy/web/Application.appPath</code> 该属性用于指明应用所在的目录</p>
</li>
</ul>
<h6><b>重要属性</b></h6>
<ul>
<li>
<p><code>candy/web/Application.routesMap</code> 用来自定义路由处理程序</p>
<pre><code>
// account 路由使用 app/controllers/user/IndexController 做处理 并传入了一个参数 property
'account': {
'classPath': 'app/controllers/user/IndexController',
'property': 'value'
}
</code></pre>
</li>
<li>
<p><code>candy/web/Application.modules</code> 用来注册应用模块</p>
<pre><code>
// 注册一个 bbs 模块
'modules': {
'bbs': 'app/modules/bbs'
}
</code></pre>
</li>
<li>
<p><code>candy/web/Application.encoding</code> 项目编码方式</p>
</li>
<li>
<p><code>candy/web/Application.debug</code> 是否开启调试</p>
</li>
</ul>
<h4><b>自定义属性</b></h4>
<p>其他在入口文件中传入的参数都会作为自定义参数传入应用对象</p>
<h1 class="page-header" id="controller"><b>应用控制器</b></h1>
<p>控制器是<code>MVC</code>模式中的一部分,是继承<code>candy/core/AbstractController</code>类的对象,负责处理请求和生成响应</p>
<p>业务逻辑一般都应该出现在控制器中,包括但不限于处理用户传递的数据,计算数据等</p>
<h4><b>动作</b></h4>
<p>控制器由<code>动作</code>组成,它是执行终端用户请求的最基础的单元,一个控制器有且只有一个入口动作叫做<code>run</code>,入口动作在控制器被创建后会自动运行</p>
<pre><code>
'use strict';
var Controller = require('candyjs/web/Controller');
class IndexController extends Controller {
// 入口动作
run(req, res) {
res.end('hello');
}
}
module.exports = IndexController;
</pre></code>
<h1 class="page-header" id="filter"><b>动作切面与过滤器</b></h1>
<p>动作切面是一种特殊的行为类,用于过滤用户的请求</p>
<p><code>candyjs</code>提供的切面可以从<code>core/ActionAspect</code>找到,该类主要用于在控制器的动作执行前进行一些预处理操作</p>
<p><code>ActionAspect</code>类有两个重要的方法:<code>beforeAction(actionEvent)</code>或<code>afterAction(actionEvent)</code>方法,方法仅有一个参数<code>actionEvent</code>,该参数有一个<code>valid</code>属性,当前一个 ActionAspect 子类设置了 <code>actionEvent.valid = false;</code>,那么后面的切面类不再执行</p>
<h4><b>切面的使用</b></h4>
<h6><b>1. 编写切面类</b></h6>
<p>使用切面,首先必须编写切面类,切面类需要从<code>candyjs/core/ActionAspect</code>类继承</p>
<p>切面类可以根据具体需求选择实现<code>beforeAction()</code>或<code>afterAction()</code>方法</p>
<p>在没有异步操作的情况下,<code>beforeAction()</code>会在控制器的动作执行前运行,<code>afterAction()</code>会在控制器的动作执行后运行</p>
<p>下面的切面类代码简单实现了一个为接口请求添加跨域头的功能,并实现了<code>beforeAction()</code>方法</p>
<pre><code>
// app/filters/Cors.js
const ActionAspect = require('candyjs/core/ActionAspect');
module.exports = class Cors extends ActionAspect {
constructor() {
super();
this.cors = {
// 允许访问该资源的 origin
'Access-Control-Allow-Origin': '*',
// 允许使用的请求方法
'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS',
// 允许请求中使用的头信息
'Access-Control-Allow-Headers': '',
// 响应的有效时间为 秒
'Access-Control-Max-Age': 86400,
// 如果出现在预检请求的响应中 表示实际请求是否可以使用 credentials
'Access-Control-Allow-Credentials': true
};
}
/**
* 实现前置方法,用于添加 http header 头
*/
beforeAction(actionEvent) {
let request = actionEvent.request;
let response = actionEvent.response;
let headers = this.generateHeaders(request);
for(let k in headers) {
response.setHeader(k, headers[k]);
}
if('OPTIONS' === request.method) {
actionEvent.valid = false;
response.writeHead(200, 'OK');
response.write('');
response.end();
}
}
generateHeaders(request) {
let ret = {};
// oirigin
if(undefined !== request.headers['origin'] && undefined !== this.cors['Access-Control-Allow-Origin']) {
if(this.cors['Access-Control-Allow-Origin'].indexOf(request.headers['origin']) >= 0) {
ret['Access-Control-Allow-Origin'] = request.headers['origin'];
}
// allow origin 为 * 和 credentials 不能同时出现
if('*' === this.cors['Access-Control-Allow-Origin']) {
if(this.cors['Access-Control-Allow-Credentials']) {
throw new Error('Allowing credentials for wildcard origins is insecure');
} else {
ret['Access-Control-Allow-Origin'] = '*';
}
}
}
// 客户端请求方法
if(undefined !== request.headers['access-control-request-method']) {
ret['Access-Control-Allow-Methods'] = this.cors['Access-Control-Allow-Methods'];
}
// 允许的 header
if(undefined !== this.cors['Access-Control-Allow-Headers']) {
ret['Access-Control-Allow-Headers'] = this.cors['Access-Control-Allow-Headers'];
}
// 认证
if(undefined !== this.cors['Access-Control-Allow-Credentials']) {
ret['Access-Control-Allow-Credentials'] = this.cors['Access-Control-Allow-Credentials'] ? 'true' : 'false';
}
if('OPTIONS' === request.method && undefined !== this.cors['Access-Control-Max-Age']) {
ret['Access-Control-Max-Age'] = this.cors['Access-Control-Max-Age'];
}
return ret;
}
}
</pre></code>
<h6><b>2. 使用切面</b></h6>
<p>使用切面很简单,只需要在控制器中添加<code>behaviors()</code>方法即可</p>
<pre><code>
class IndexController extends Controller {
// 'cors' 是为切面类指定的别名
// 'app/filters/Cors' 表示切面的类路径 这里表示 app/filters/Cors.js 类
behaviors() {
return [
['cors', 'app/filters/Cors']
];
}
run() {
// 此控制器动作执行前会先运行 behaviors() 方法指定的切面
}
}
</pre></code>
<blockquote class="bg-info">
<p>在 4.18 版本之前,<code>ActionAspect</code>类名为<code>ActionFilter</code></p>
<p>相较于使用切面过滤用户的请求,更好的做法是使用过滤器</p>
</blockquote>
<blockquote class="bg-danger">
<p>切面不支持异步操作,如果业务逻辑中包含异步逻辑(比如异步读取数据库),那么就不能保证切面执行完成再执行控制器逻辑</p>
<p>所以,需要处理异步业务场景时,应该使用过滤器</p>
</blockquote>
<h1 class="page-header"><b>过滤器</b></h1>
<p>过滤器是实现了<code>core/IFilter</code>接口的类,或者任何具有<code>doFilter(req, res, chain)</code>函数的类</p>
<p>过滤器的使用和切面类似,但是过滤器的配置是由<code>filters()</code>函数返回的</p>
<pre><code>
const Controller = require('candyjs/web/Controller');
class IndexController extends Controller {
// 'app/filters/MyFilter' 表示过滤器的类路径
filters() {
return [
'app/filters/MyFilter'
];
}
run() {}
}
// app/filters/MyFilter
module.exports = class MyFilter {
doFilter(req, res, filterChain) {
// todo something
// 需要手动调用下一个过滤器
filterChain.doFilter(req, res);
}
}
</pre></code>
<blockquote class="bg-info">
<p>切面和过滤器都可以在控制器执行之前过滤用户的请求,但是切面只支持同步操作,而过滤器支持异步操作</p>
</blockquote>
<h1 class="page-header" id="router"><b>MVC 路由</b></h1>
<p>路由是<code>MVC</code>模式中的一部分,实现控制器寻址</p>
<p><code>MVC</code>模式中,每一个路由会对应到一个控制器文件</p>
<h4><b>路由与控制器</b></h4>
<p>一般一个路由对应一个控制器 路由有如下两种格式</p>
<ol>
<li><p><code>route_prefix[/controllerId]</code></p></li>
<li><p><code>moduleId[/controllerId]</code></p></li>
</ol>
<blockquote class="bg-info">
<code>[/controllerId]</code>可以省略,如果省略,那么默认值为<code>index</code>,即默认控制器为<code>IndexControlelr</code>
</blockquote>
<ul>
<li>
<p>直接访问域名 <a>http://localhost/</a></p>
<p>会默认映射到 <code>app/controllers/index/IndexControlelr</code> 控制器</p>
</li>
<li>
<p>访问 <a>http://localhost/user</a></p>
<p>首先会查找是否存在 <code>user</code> 模块</p>
<p>如果存在,会映射到 <code>app/modules/user/controllers/IndexController</code></p>
<p>如果不存在,则会映射到 <code>app/controllers/user/IndexController</code></p>
</li>
<li>
<p>访问 <a>http://localhost/user/profile</a></p>
<p>首先会查找是否存在 <code>user</code> 模块</p>
<p>如果存在,会映射到 <code>app/modules/user/controllers/ProfileController</code></p>
<p>如果不存在,则会映射到 <code>app/controllers/user/ProfileController</code></p>
</li>
<li>
<p>访问 <a>http://localhost/user/profile/settings</a></p>
<p>首先会查找是否存在 <code>user</code> 模块</p>
<p>如果存在,会映射到 <code>app/modules/user/controllers/SettingsController</code></p>
<p>如果不存在,则会映射到 <code>app/controllers/user/profile/SettingsController</code></p>
</li>
</ul>
<p>控制器查找顺序 优先查找模块下的控制器<code>模块控制器 --> 普通控制器</code></p>
<h4><b>自定义路由配置</b></h4>
<p><code>CandyJs</code>中可以自定义路由的处理程序,这里通过<code>routesMap</code>来实现</p>
<pre><code>
var App = require('candyjs/web/Application');
var app = new App({
id: 'myapp',
routesMap: {
// 比如访问 http://www.somedomain.com/account
// 这时候 account 路由将使用 app/controllers/user/IndexController 做处理
// 并将 IndexController 的 foo 成员变量赋值为 123
'account': {
'classPath': 'app/controllers/user/IndexController',
'foo': '123'
}
}
});
</pre></code>
<h4><b>路由拦截</b></h4>
<p>很多时候,网站会需要进行维护,这时候需要关闭网站,<code>candyjs</code>提供了路由拦截功能,使得网站维护变得简单</p>
<pre><code>
var App = require('candyjs/web/Application');
var app = new App({
id: 'myapp',
// 这条配置使得所有请求都会被转发到 app/Intercept 去处理
'interceptAll': 'app/Intercept',
});
// Intercept.js
class Intercept {
run(req, res) {
res.end('intercepted');
}
}
module.exports = Intercept;
</pre></code>
<h1 class="page-header" id="model"><b>模型</b></h1>
<p>模型是<code>MVC</code>模式中的一部分,是代表业务数据和规则的对象</p>
<p>模型并不能直接操作数据库,它只提供数据存储和校验,数据库操作需要借助数据库操作类实现</p>
<blockquote class="bg-info">
<p>数据库操作 <a target="_blank" href="https://github.com/candyframework/candyjs-db-mysql2">从这里了解详情</a></p>
<p>模型示例 <a target="_blank" href="https://github.com/candyframework/candyjs-examples/tree/master/model">从这里了解详情</a></p>
</blockquote>
<h4><b>使用模型</b></h4>
<p>使用模型需要以下几个步骤</p>
<ol>
<li>定义模型</li>
<li>填充数据</li>
<li>校验数据</li>
</ol>
<h6><b>1. 定义模型</b></h6>
<p>在<code>CandyJs</code>中,模型由<code>属性( attributes )</code>和<code>规则( rules )</code>组成</p>
<p>属性是一个 JSON 对象,其中的键名一般与数据库定义的字段一一对应,规则是一个数组,配置了对属性的验证规则</p>
<p>每一个验证规则由三部分组成:规则验证器(由 rule 字段指定,支持对象实例、类配置以及别名路径格式)、需要验证的属性列表(由 attributes 字段指定)、错误时的提示信息(由 messages 字段指定)</p>
<p>如下是一个用户信息模型</p>
<pre><code>
const Model = require('candyjs/model/Model');
module.exports = class UserModel extends Model {
constructor() {
super();
// 模型属性
this.attributes = {
user_name: '',
password: '',
confirming: '',
email: ''
};
// 表单与模型字段不一致时 使用此配置来做字段映射
// 如 模型使用 user_name 而前端表单使用 name
this.attributesMap = {
user_name: 'name'
};
}
// 模型规则
rules() {
return [
{
rule: 'candy/model/RequiredValidator',
attributes: ['user_name', 'password', 'email'],
messages: ['用户名不能为空', '密码不能为空', '邮箱不能为空']
},
{
rule: 'candy/model/EqualValidator',
attributes: ['password', 'confirming'],
messages: ['两次密码不一致']
},
{
rule: 'candy/model/EmailValidator',
attributes: ['email'],
messages: ['邮箱格式不正确']
}
];
}
}
</code></pre>
<h6><b>2. 填充数据</b></h6>
<p>当有了定义好的模型后,接下来就是为模型填充数据,数据一般由用户通过前台页面以表单形式发送到后台,这里以控制器处理为例</p>
<pre><code>
const UserModel = require('../../models/UserModel');
module.exports = class PostController {
run(req, res) {
let model = new UserModel();
// 数据填充
model.fill(req);
// todo ...
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end('');
}
}
</code></pre>
<blockquote class="bg-info">
<p>数据填充时,有可能前台表单的字段名称和模型中的属性名称不一致,这时候数据将会填充失败。</p>
<p>可以在模型定义时增加<code>attributesMap</code>字段,就如上面定义模型的例子那样:<code>this.attributesMap = { user_name: 'name' };</code></p>
<p>模型使用的是 user_name,而前台表单使用的是 name,通过此种映射方式实现字段不一致时的对应</p>
</blockquote>
<h6><b>3. 校验数据</b></h6>
<p>模型提供了<code>validate()</code>方法,调用该方法,模型会执行<code>rules()</code>配置的校验规则对属性进行校验,并返回一个布尔值代表成功或者失败</p>
<p>如果验证失败,可以通过<code>getErrors()</code>获取错误信息,该方法返回一个数组,包含了所有的错误信息</p>
<pre><code>
const UserModel = require('../../models/UserModel');
module.exports = class PostController {
run(req, res) {
let model = new UserModel();
// 数据填充
model.fill(req);
// 执行校验
let valid = model.validate();
let errors = model.getErrors();
let data = JSON.stringify({
status_code: valid ? 0 : 1,
messages: errors
});
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end(data);
}
}
</code></pre>
<h4><b>系统内置验证器</b></h4>
<p><code>CandyJs</code>内置了几个常用的验证器,如上述示例中<code>rule: 'candy/model/EmailValidator'</code>,它表示被验证的属性必须是一个邮箱格式</p>
<p>内置验证器如下</p>
<ul>
<li><code>BooleanValidator</code></li>
<li><code>EmailValidator</code></li>
<li><code>EqualValidator</code></li>
<li><code>RequiredValidator</code></li>
<li><code>StringValidator</code></li>
</ul>
<h4><b>自定义验证器</b></h4>
<p>由于业务的不同,系统内置验证器无法满足所有需求,这时候就可以使用自定义验证器</p>
<p>自定义验证器比较简单,只需要从系统的<code>Vakudatir</code>继承,并实现其中的<code>validate()</code>方法即可</p>
<blockquote class="bg-info">
<p>需要注意的是,<code>validate()</code>方法的返回值是字符串,代表了验证失败的错误信息。如果没有错误,需要返回空字符</p>
</blockquote>
<pre><code>
// 定义一个验证数字范围的验证器
const Validator = require('candyjs/model/Validator');
class MyNumberValidator extends Validator {
constructor() {
super();
this.max = 100;
this.min = 1;
}
validate(attributeName, attributeValue) {
let info = this.getMessage(attributeName);
if(attributeValue < this.min || attributeValue > this.max) {
return '' === info ? 'number is invalid' : info;
}
return '';
}
}
</code></pre>
<h4><b>使用自定义验证器</b></h4>
<pre><code>
const Model = require('candyjs/model/Model');
class UserModel extends Model {
constructor() {
super();
...
}
rules() {
return [
{
rule: new MyNumberValidator(),
attributes: ['age'],
messages: ['年龄不合法']
}
];
}
}
</code></pre>
<h1 class="page-header" id="view"><b>视图</b></h1>
<p>视图是<code>MVC</code>模式中的一部分 它用于给终端用户展示页面</p>
<h4><b>模板引擎</b></h4>
<blockquote class="bg-info">
<code>CandyJs</code>提供了<code>@candyjs/template-hbs</code>来负责模板渲染,<a target="_blank" href="https://github.com/candyframework/candyjs-template-hbs">查看详情</a>
</blockquote>
<h4><b>其他方式使用模板引擎</b></h4>
<p>得益于<code>CandyJs</code>灵活的架构设计,使得模板引擎使用非常便捷,这里有如下几种方式:</p>
<ul>
<li>全局配置方式</li>
<li>局部注入方式</li>
<li>嵌入式</li>
</ul>
<p>下面将使用<code>Handlebars</code>对以上方式进行逐个讲解</p>
<h6><b>全局配置方式</b></h6>
<pre><code>
// 全局配置方式是使用 candyjs 的别名系统实现的
// 这里的代码可以从源代码 examples 目录中找到
// 1. 在 app/libs 目录中建立一个模板引擎文件 CandyTemplate.js
const fs = require('fs');
const Handlebars = require('handlebars');
// 加载系统视图类
const View = require('candyjs/web/View');
class CandyTemplate extends View {
constructor(context) {
super(context);
this.handlebars = Handlebars.create();
}
// 模板引擎必须实现这个方法,因为它是渲染模板的入口
renderFile(file, parameters) {
fs.readFile(file, 'UTF-8', (err, template) => {
let compiled = this.handlebars.compile(template);
this.context.response.end( compiled(parameters) );
});
}
}
module.exports = CandyTemplate;
// 2. 经过第 1 步,我们的模板引擎就开发完了,是不是很简单
// 接下来在入口注册我们编写的模板引擎
const App = require('candyjs/web/Application');
const app = new App({
'id': 'template_test',
// 配置模板引擎
'defaultView': 'app/libs/CandyTemplate',
'appPath': __dirname + '/app'
});
new CandyJs(app).listen(2333, function(){
console.log('listen on 2333');
});
// 3. 准备模板 html
<html>
<body>
<ul>
{{#each list}}
<li><a href="/user?uid={{ id }}">{{ name }}</a></li>
{{/each}}
</ul>
</body>
</html>
// 4. 在控制器中使用模板引擎渲染页面
const Controller = require('candyjs/web/Controller');
const User = require('somepath/models/User');
class IndexController extends Controller {
run(req, res) {
this.fetchList(res);
}
async fetchList(res) {
const user = new User();
// 这里 data 是一个用户数组 [{id: xxx, name: xxx}]
let data = await user.getUserList();
// 可以获取到模板引擎实例
// 具体使用方式请参考 handlebars 模板引擎官方文档
// const handlebars = this.getView().handlebars;
// handlebars.todo
// 这里的 render 将使用我们制定的模板引擎渲染页面
this.render('index', {
list: data
});
}
}
</code></pre>
<h6><b>局部注入方式</b></h6>
<pre><code>
// 1. 局部注入方式第 1 步也需要编写我们的模板引擎,参考全局配置方式
// 2. 在控制器中动态注入模板引擎
const Controller = require('candyjs/web/Controller');
const User = require('somepath/models/User');
const CandyTemplate = require('somepath/CandyTemplate');
class IndexController extends Controller {
run(req, res) {
this.fetchList(res);
}
async fetchList(res) {
const user = new User();
let data = await user.getUserList();
// 动态注入模板引擎
this.setView(new CandyTemplate(this.context));
this.render('index', {
list: data
});
}
}
module.exports = IndexController;
</code></pre>
<h6><b>嵌入式</b></h6>
<pre><code>
// 这种方式比较灵活,不需要编写模板引擎
const Controller = require('candyjs/web/Controller');
const Handlebars = require('handlebars');
const User = require('somepath/models/User');
class IndexController extends Controller {
run(req, res) {
this.fetchList(res);
}
async fetchList(res) {
const user = new User();
let data = await user.getUserList();
this.getView().getViewContent('index', (err, str) => {
// 直接使用模板引擎对内容进行编译并输出
let compiled = Handlebars.compile(str);
res.end( compiled({ list: data }) );
});
}
}
module.exports = IndexController;
</code></pre>
<h4><b>控制器层的视图 API</b></h4>
<p>
如果用户的控制器从<code>candy/web/Controller</code>继承而来
那么可以在控制器中使用<code>getView()</code>方法来获取视图类实例
</p>
<p>视图类提供了如下<code>API</code>供用户使用</p>
<ul>
<li><code>findViewFile(view)</code> 用于获取一个视图文件的绝对路径</li>
<li><code>getViewContent(view, callback)</code> 用于读取一个视图文件的内容</li>
</ul>
<pre><code>
'use strict';
var Candy = require('candyjs/Candy');
var Controller = Candy.include('candy/web/Controller');
class IndexController extends Controller {
run(req, res) {
this.getView().getViewContent('index', (err, str) => {
res.end(str);
});
}
}
module.exports = IndexController;
</code></pre>
<h1 class="page-header" id="module"><b>模块</b></h1>
<p>
模块是独立的软件单元,体量较小,<code>由模型、视图、控制器</code>和其他组件组成。
</p>
<p>
终端用户可以访问在应用主体中已注册的模块的控制器,<code>CandyJs</code>在解析路由时优先查找模块中有没有满足条件的控制器
</p>
<p>如果项目中某个功能相对独立,与项目关联不大,随时准备删除或加入进来,那么可以考虑将其放入模块系统</p>
<blockquote class="bg-info">
注意 和普通项目目录不同的是 模块中的<code>控制器和视图</code>没有子目录
</blockquote>
<h4><b>创建模块</b></h4>
<p>在应用目录的<code>modules</code>目录中建立单独目录创建模块 如下</p>
<pre><code>
modules 模块目录
|
|-- newyearactive 新年活动页面
| |
| |-- controllers 模块控制器目录
| | |
| | |-- IndexController.js
| |
| |-- views 模块视图目录
| | |
| | |-- index.html
| |
| |-- 其他目录
</code></pre>
<h4><b>注册模块</b></h4>
<p>创建完成的模块还不能被系统识别 需要手动注册一下</p>
<pre><code>
var CandyJs = require('candyjs');
var App = require('candyjs/web/Application');
new CandyJs(new App({
...
// 注册模块
// 这样路由为 /newyearactive 时会优先匹配到该模块
'modules': {
'newyearactive': 'app/modules/newyearactive'
},
...
})).listen(2333, function(){
console.log('listen on 2333');
});
</code></pre>
<h1 class="page-header" id="component"><b>组件 & 行为</b></h1>
<h4><b>组件</b></h4>
<p>组件是实现<code>行为 (behavior) 事件 (event)</code>的基类,如果一个类从<code>candy/core/Component</code>或其子类继承而来,那么这个类就拥有组件的特性</p>
<p>
组件是<code>candy/core/Component</code>或其子类的实例
</p>
<p>
<code>CandyJs</code>中<code>candy/web/Controller</code>类继承自<code>candy/core/Component</code>,所以控制器具有组件的特性
</p>
<p>行为类一般与组件类同时使用</p>
<h4><b>行为</b></h4>
<p>
行为是<code>candy/core/Behavior</code>类或其子类的实例,具有如下作用
</p>
<ul>
<li>一个行为类可以用于在不改变原组件代码的情况下增强其功能</li>
<li>行为类能够监听组件的事件并作出响应,这对于拦截框架的核心事件,并对其做出处理提供了方便</li>
</ul>
<h4><b>事件</b></h4>
<p><code>CandyJs</code>中实现了一个观察者模式</p>
<pre><code>
'use strict';
var Candy = require('candyjs/Candy');
var Controller = Candy.include('candy/web/Controller');
class IndexController extends Controller {
constructor(context) {
super(context);
this.on('myevent', function() {
console.log('myevent fired');
});
}
run(req, res) {
this.trigger('myevent');
res.end('hello');
}
}
module.exports = IndexController;
</code></pre>
<h4><b>行为的使用</b></h4>
<blockquote class="bg-danger">
从 4.4.0 开始,我们对行为进行了重构,去除了作用不大的方法注入,保留了事件监听
</blockquote>
<h6><b>定义行为</b></h6>
<p>要定义行为,可以通过继承<code>candy/core/Behavior</code>或其子类来建立一个类</p>
<pre><code>
'use strict';
var Candy = require('candyjs/Candy');
var Behavior = Candy.include('candy/core/Behavior');
// 行为类
class MyBehavior extends Behavior {
constructor() {
super();
}