moderntribe/square1-request

访问请求环境信息的实用工具

4.2.0 2022-08-17 21:54 UTC

README

Tribe Libs 提供了一个请求辅助对象,以便可以轻松访问常见的请求(或服务器)相关值,例如头信息、输入值和 URL/path 信息。

用法

您可以通过在构造函数中直接注入来使此对象可用于您的类

class My_Cool_Class {

    protected $request;

    public function __construct( Request $request ) {
        $this->request = $request;
    }

}

注入后,请求对象将自动包含与当前请求相关的各种值。例如,要访问 Content-Type 头信息,您可以使用

$content_type = $this->request->header('Content-Type');

请求对象也通过外观提供,以便在您无法控制构造函数的类(例如控制器)中使用,以便像通常那样注入类。

方法

query()

@return \WP_Query

获取当前的 \WP_Query 全局对象。请注意,这始终在调用时获取 global $wp_query,以便提供对象的最新版本,因此它可以在钩子中使用,就像 global $wp_query 一样。

$query = $this->request->query();
$posts = $query->found_posts; 

headers()

@return array

获取此请求的所有头信息。

$headers = $this->request->headers();

echo $headers['Content-Type'];

header( $key )

@param  string $key
@return string

通过键获取头信息值。

$content_type = $this->request->header('Content-Type');

input( $key )

@param  string $key
@return mixed 

通过键从请求中获取输入。自动检测方法(GET、POST、JSON body)并返回正确方法值中的值。

$foobar = $this->request->input('foobar');

all()

@return array

从请求中获取所有输入值。自动检测方法并从中拉取值。如果方法不是 GET,并且请求还有查询参数,则返回方法和输入参数。

$all_input = $this->request->all();

only( $keys )

@param  array $keys
@return array

仅返回与提供的键匹配的输入值。返回一个只包含那些存在(包括空值)的键的数组。不会返回不存在键的值。

$keys = [ 'foo', 'bar', 'bash' ];

$values = $this->request->only( $keys );

except( $keys )

@param  array $keys
@return array

返回除提供的键之外的所有输入值。如果没有其他值存在,除了提供的键之外,则返回一个空数组。

$keys = [ 'foo', 'bar' ];

$values = $this->request->except( $keys );

has( $key )

@param  string $key
@return bool

确定是否在请求中存在与提供的键匹配的输入。如果输入键存在(即使它是空的),则返回 true

$has_foobar = $this->request->has('foobar');

if ( $has_foobar ) {
    // do thing.
}

filled( $key )

@param  string $key
@return bool

确定与提供的键匹配的输入是否存在且非空。如果值是 bool 或 0,则返回 true,但对于任何空字符串或 null 值则返回 false

$foobar_filled = $this->request->filled('foobar');

if ( $foobar_filled ) {
    // do thing.
}

path( $include_params = false )

@param  bool $include_params
@return string

获取当前的请求路径。如果 $include_params 设置为 true,则还包括任何查询参数。

// URL is http://foobar.com/page/here?foo=bar

$path = $this->request->path();
echo $path;

// /page/here

$path_with_params = $this->request->path( true );
echo $path_with_params;

// /page/here?foo=bar

url()

@return string

获取当前的请求 URL。不包含路径或任何查询参数。

// URL is http://foobar.com/page/here?foo=bar

$url = $this->request->url();
echo $url;

// http://foobar.com

full_url()

@return string

获取完整的当前请求 URL。包括路径和任何查询参数。

// is http://foobar.com/page/here?foo=bar

$full_url = $this->request->full_url();
echo $full_url;

// http://foobar.com/page/here?foo=bar

is( $path )

@param  string $path
@return bool

确定当前请求路径是否与给定的模式匹配。可以使用通配符 (*)。

// URL is http://foobar.com/page/here?foo=bar

$is_page = $this->request->is('page/here');

// true

$is_page = $this->request->is('page/*');

// true

$is_page = $this->request->is('page');

// false