学习要趁早,点滴记录,学习就是进步!
请联系本文作者或者关注公众号:菜鸟奋斗 或Q群:702101215
随笔背景:在很多时候,很多入门不久的朋友都会问我:我是从其他语言转到程序开发的,有没有一些基础性的资料给我们学习学习呢,你的框架感觉一下太大了,希望有个循序渐进的教程或者视频来学习就好了。对于学习有困难不知道如何提升自己可以加扣:1225462853进行交流得到帮助,获取学习资料.
PK1928-yii2.0框架深入解析(实战篇)
下载地址:http://pan.baidu.com/s/1jI05TPW
你可以使用 formatter
application component 来格式化数据。 默认 fomatter
由 yii\i18n\Formatter 来实现,这个组件提供了一系列关于日期/时间,数字,货币等的格式化方法。 使用方法如下:
$formatter = \Yii::$app->formatter; // output: January 1, 2014 echo $formatter->asDate('2014-01-01', 'long'); // output: 12.50% echo $formatter->asPercent(0.125, 2); // output: <a href="mailto:[email protected]">[email protected]</a> echo $formatter->asEmail('[email protected]'); // output: Yes echo $formatter->asBoolean(true); // it also handles display of null values: // output: (Not set) echo $formatter->asDate(null);
页面缓存指的是在服务器端缓存整个页面的内容。 随后当同一个页面被请求时,内容将从缓存中取出,而不是重新生成。
页面缓存由 yii\filters\PageCache 类提供支持,该类是一个过滤器。 它可以像这样在控制器类中使用:
public function behaviors() { return [ [ 'class' => 'yii\filters\PageCache', 'only' => ['index'], 'duration' => 60, 'variations' => [ \Yii::$app->language, ], 'dependency' => [ 'class' => 'yii\caching\DbDependency', 'sql' => 'SELECT COUNT(*) FROM post', ], ], ]; }
上述代码表示页面缓存只在 index
操作时启用,页面内容最多被缓存 60 秒, 会随着当前应用的语言更改而变化。 如果文章总数发生变化则缓存的页面会失效。
如你所见,页面缓存和片段缓存极其相似。 它们都支持 duration
,dependencies
,variations
和 enabled
配置选项。 它们的主要区别是页面缓存是由过滤器实现,而片段缓存则是一个小部件。
当处理一个 RESTful API 请求时, 一个应用程序通常需要如下步骤 来处理响应格式:
- 确定可能影响响应格式的各种因素, 例如媒介类型, 语言, 版本, 等等。 这个过程也被称为 content negotiation。
- 资源对象转换为数组, 如在 Resources 部分中所描述的。 通过 yii\rest\Serializer 来完成。
- 通过内容协商步骤将数组转换成字符串。 response formatters 通过 response 应用程序 组件来注册完成。
内容协商
Yii 提供了通过 yii\filters\ContentNegotiator 过滤器支持内容协商。RESTful API 基于 控制器类 yii\rest\Controller 在 contentNegotiator
下配备这个过滤器。 文件管理器提供了涉及的响应格式和语言。 例如, 如果一个 RESTful API 请求中包含以下 header,
$ curl -i -H "Accept: application/json; q=1.0, */*; q=0.1" "http://localhost/users" HTTP/1.1 200 OK Date: Sun, 02 Mar 2014 05:31:43 GMT Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y X-Powered-By: PHP/5.4.20 X-Pagination-Total-Count: 1000 X-Pagination-Page-Count: 50 X-Pagination-Current-Page: 1 X-Pagination-Per-Page: 20 Link: <http://localhost/users?page=1>; rel=self, <http://localhost/users?page=2>; rel=next, <http://localhost/users?page=50>; rel=last Transfer-Encoding: chunked Content-Type: application/json; charset=UTF-8 [ { "id": 1, ... }, { "id": 2, ... }, ... ]
幕后,执行一个 RESTful API 控制器动作之前,yii\filters\ContentNegotiator filter 将检查 Accept
HTTP header 在请求时和配置 response format 为 'json'
。 之后的动作被执行并返回得到的资源对象或集合, yii\rest\Serializer 将结果转换成一个数组。最后,yii\web\JsonResponseFormatter 该数组将序列化为JSON字符串,并将其包括在响应主体。
默认, RESTful APIs 同时支持JSON和XML格式。为了支持新的格式,你应该 在 contentNegotiator
过滤器中配置 formats 属性, 类似如下 API 控制器类:
use yii\web\Response; public function behaviors() { $behaviors = parent::behaviors(); $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_HTML; return $behaviors; }