yii2 的 request get post 基本用法 – 通用获取get/post请求

Get Post 基本用法

1、普通的get和pst请求

$request = Yii::$app->request;

$get = $request->get();
// equivalent to: $get = $_GET;

$id = $request->get('id');
// equivalent to: $id = isset($_GET['id']) ? $_GET['id'] : null;

$id = $request->get('id', 1);
// equivalent to: $id = isset($_GET['id']) ? $_GET['id'] : 1;
//添加了默认值

$post = $request->post();
// equivalent to: $post = $_POST;

$name = $request->post('name');
// equivalent to: $name = isset($_POST['name']) ? $_POST['name'] : null;

$name = $request->post('name', '');
// equivalent to: $name = isset($_POST['name']) ? $_POST['name'] : '';
//添加了默认值

2、判断请求属性

$request = Yii::$app->request;

if ($request->isAjax) { // 判断是否为AJAX 请求 }
if ($request->isGet) { // 判断是否为GET 请求 }
if ($request->isPost) { // 判断是否为POST 请求}
if ($request->isPut) { // 判断是否为PUT 请求 }

3、获取请求头信息

$headers = Yii::$app->request->headers;
// 返回header头部所有信息

$accept = $headers->get('Accept');
if ($headers->has('User-Agent')) { // 获取User-Agent }

4、获取用户客户端信息

$userHost = Yii::$app->request->userHost;
$userIP = Yii::$app->request->userIP;

yii2添加行为之Yii->$app->request->request()通用地去获取post|get请求

1、main-local 中添加:

'request' => [
    'as requestmethod' => common\helpers\HttpRequstMethod::class,
],

2、添加 HttpRequstMethod

<?php
namespace common\helpers;

use yii\base\Behavior;
use yii\helpers\ArrayHelper;

/**
 * Class HttpRequstMethod
 *
 * @$_REQUEST = GET + POST
 */
class HttpRequstMethod extends Behavior
{
    private static $_data = [];

    public function request($name = null)
    {
        $request = \Yii::$app->request;
        if (!self::$_data)
        {
            self::$_data = ArrayHelper::merge($request->getBodyParams(),
                $request->getQueryParams());
        }
        return self::$_data[$name] ?? self::$_data;
    }
}

3、添加到 phpstorm_ide_helper.php ,支持输入Yii::$app-> 自动补全列表里有request

@property \common\helpers\HttpRequstMethod $request;

4、到此,任何地方都可以通过如下通用地调用所有请求参数或者某个请求参数了!

Yii::$app->request->request();//获取请求的所有参数

Yii::$app->request->request('id');//获取请求的某个参数

Comments are closed.