Yii2 components api/controller
2024-08-24 01:12:50
When we wrote API, those controllers need to implement the following feature:
1. return JSON format data
2. sometimes support JSONP format data also.
3. support stupid low version IE
If we set format with Yii2, the low version IE will download the response content as a file.
Yii::$app->response->format = Response::FORMAT_JSON
So I wrote a component for it, any API controller just need to extend it.
namespace api\components; use Yii;
use yii\web\Response; class Controller extends \yii\web\Controller
{
protected $isLowIE;
protected $callback; public function beforeAction($action)
{
$this->layout = false;
$this->callback = Yii::$app->request->get('callback', false); $this->isLowIE = (boolean)Yii::$app->request->get('ie', false); if (!$this->isLowIE && !$this->callback) {
Yii::$app->response->format = Response::FORMAT_JSON;
} return parent::beforeAction($action);
} /**
* @param \yii\base\Action $action
* @param mixed $result
* @return mixed
*/
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
// your custom code here
if ($this->isLowIE || $this->callback) {
$result = json_encode($result); if ($this->callback) {
$result = $this->callback .'('. $result .')';
}
}
return $result;
}
}
最新文章
- 异常:System.Data.EvaluateException: 未找到列[District].
- 【2016-10-13】【坚持学习】【Day4】【WPF】【ObservableCollection<;T>;】
- 数据库的日志数据库(_log.ldf)文件太大,如何压缩
- 对ASM存储管理的一些初步理解记录
- SQL Server 多条记录的某个字段拼接
- iOS上架(转)
- git add 之后因为没提交正确文件需要撤销
- springmvc(3)--数据类型转换
- PKUSC 模拟赛 day1 上午总结
- 更改mysql数据库latin1_swedish_ci为utf8
- IPTV中的EPG前端优化
- Oracle存储过程的一点使用总结
- win10环境下tensorflow-gpu安装
- VC2010工程依赖不再自动链接
- 为什么 kubernetes 天然适合微服务
- PHP实现表单提交发送邮件
- Eclipse导入文件识别不了jsp怎么办
- Visualizing the Git data model
- win7 vs2012/2013 编译boost 1.55
- 推荐一款jQueryajax插件(Ajaxify jQuery )