Session
云策文档标注
概述
Session 类是 WordPress 中用于处理持久 HTTP 请求的会话处理器,允许设置默认参数并合并请求选项。它提供基础 URL、头部、数据和选项的配置,支持多种 HTTP 方法请求。
关键要点
- Session 类用于管理 HTTP 会话,支持设置默认 URL、headers、data 和 options,并自动合并到单个请求中。
- 提供多种 HTTP 请求方法,如 GET、POST、PUT、DELETE、PATCH、HEAD,以及 request() 和 request_multiple() 主接口。
- 通过 __construct 构造函数初始化会话,可设置基础参数,并自动创建共享 cookie jar。
- 使用魔术方法(__get、__set、__isset、__unset)动态访问和修改 options 属性。
- merge_request() 方法负责合并默认数据与请求数据,确保请求配置的一致性。
- 包含错误处理机制,如参数类型验证和异常抛出,确保代码健壮性。
代码示例
// 创建 Session 实例
$session = new Session('https://api.example.com', ['User-Agent' => 'MyApp'], ['key' => 'value'], ['timeout' => 30]);
// 发送 GET 请求
$response = $session->get('/endpoint', ['Accept' => 'application/json']);
// 发送 POST 请求
$response = $session->post('/submit', ['Content-Type' => 'application/json'], ['data' => 'test']);
// 动态设置选项
$session->useragent = 'CustomAgent';
$value = $session->useragent; // 获取选项值注意事项
- PATCH 请求要求必须提供 headers 参数,建议包含 ETag 以符合 RFC 5789 规范。
- Session 类不应被反序列化,__wakeup 方法会抛出 LogicException 异常。
- 在合并选项时,type 选项会被自动移除,因为它属于每个请求的独立设置。
- 使用 request_multiple() 发送多个请求时,需确保 $requests 参数为数组或可迭代对象。
原文内容
Session handler for persistent requests and default parameters
Description
Allows various options to be set as default values, and merges both the options and URL properties together. A base URL can be set for all requests, with all subrequests resolved from this. Base options can be set (including a shared cookie jar), then overridden for individual requests.
Methods
| Name | Description |
|---|---|
| Session::__construct | Create a new session |
| Session::__get | Get a property’s value |
| Session::__isset | Remove a property’s value |
| Session::__set | Set a property’s value |
| Session::__unset | Remove a property’s value |
| Session::__wakeup | – |
| Session::delete | Send a DELETE request |
| Session::get | Send a GET request |
| Session::head | Send a HEAD request |
| Session::merge_request | Merge a request’s data with the default data |
| Session::patch | Send a PATCH request |
| Session::post | Send a POST request |
| Session::put | Send a PUT request |
| Session::request | Main interface for HTTP requests |
| Session::request_multiple | Send multiple HTTP requests simultaneously |
Source
class Session {
/**
* Base URL for requests
*
* URLs will be made absolute using this as the base
*
* @var string|null
*/
public $url = null;
/**
* Base headers for requests
*
* @var array
*/
public $headers = [];
/**
* Base data for requests
*
* If both the base data and the per-request data are arrays, the data will
* be merged before sending the request.
*
* @var array
*/
public $data = [];
/**
* Base options for requests
*
* The base options are merged with the per-request data for each request.
* The only default option is a shared cookie jar between requests.
*
* Values here can also be set directly via properties on the Session
* object, e.g. `$session->useragent = 'X';`
*
* @var array
*/
public $options = [];
/**
* Create a new session
*
* @param string|Stringable|null $url Base URL for requests
* @param array $headers Default headers for requests
* @param array $data Default data for requests
* @param array $options Default options for requests
*
* @throws WpOrgRequestsExceptionInvalidArgument When the passed $url argument is not a string, Stringable or null.
* @throws WpOrgRequestsExceptionInvalidArgument When the passed $headers argument is not an array.
* @throws WpOrgRequestsExceptionInvalidArgument When the passed $data argument is not an array.
* @throws WpOrgRequestsExceptionInvalidArgument When the passed $options argument is not an array.
*/
public function __construct($url = null, $headers = [], $data = [], $options = []) {
if ($url !== null && InputValidator::is_string_or_stringable($url) === false) {
throw InvalidArgument::create(1, '$url', 'string|Stringable|null', gettype($url));
}
if (is_array($headers) === false) {
throw InvalidArgument::create(2, '$headers', 'array', gettype($headers));
}
if (is_array($data) === false) {
throw InvalidArgument::create(3, '$data', 'array', gettype($data));
}
if (is_array($options) === false) {
throw InvalidArgument::create(4, '$options', 'array', gettype($options));
}
$this->url = $url;
$this->headers = $headers;
$this->data = $data;
$this->options = $options;
if (empty($this->options['cookies'])) {
$this->options['cookies'] = new Jar();
}
}
/**
* Get a property's value
*
* @param string $name Property name.
* @return mixed|null Property value, null if none found
*/
public function __get($name) {
if (isset($this->options[$name])) {
return $this->options[$name];
}
return null;
}
/**
* Set a property's value
*
* @param string $name Property name.
* @param mixed $value Property value
*/
public function __set($name, $value) {
$this->options[$name] = $value;
}
/**
* Remove a property's value
*
* @param string $name Property name.
*/
public function __isset($name) {
return isset($this->options[$name]);
}
/**
* Remove a property's value
*
* @param string $name Property name.
*/
public function __unset($name) {
unset($this->options[$name]);
}
/**#@+
* @see WpOrgRequestsSession::request()
* @param string $url
* @param array $headers
* @param array $options
* @return WpOrgRequestsResponse
*/
/**
* Send a GET request
*/
public function get($url, $headers = [], $options = []) {
return $this->request($url, $headers, null, Requests::GET, $options);
}
/**
* Send a HEAD request
*/
public function head($url, $headers = [], $options = []) {
return $this->request($url, $headers, null, Requests::HEAD, $options);
}
/**
* Send a DELETE request
*/
public function delete($url, $headers = [], $options = []) {
return $this->request($url, $headers, null, Requests::DELETE, $options);
}
/**#@-*/
/**#@+
* @see WpOrgRequestsSession::request()
* @param string $url
* @param array $headers
* @param array $data
* @param array $options
* @return WpOrgRequestsResponse
*/
/**
* Send a POST request
*/
public function post($url, $headers = [], $data = [], $options = []) {
return $this->request($url, $headers, $data, Requests::POST, $options);
}
/**
* Send a PUT request
*/
public function put($url, $headers = [], $data = [], $options = []) {
return $this->request($url, $headers, $data, Requests::PUT, $options);
}
/**
* Send a PATCH request
*
* Note: Unlike <a href="https://developer.wordpress.org/reference/classes/WpOrgRequestsSession/post/">WpOrgRequestsSession::post()</a> and <a href="https://developer.wordpress.org/reference/classes/WpOrgRequestsSession/put/">WpOrgRequestsSession::put()</a>,
* `$headers` is required, as the specification recommends that should send an ETag
*
* @link https://tools.ietf.org/html/rfc5789
*/
public function patch($url, $headers, $data = [], $options = []) {
return $this->request($url, $headers, $data, Requests::PATCH, $options);
}
/**#@-*/
/**
* Main interface for HTTP requests
*
* This method initiates a request and sends it via a transport before
* parsing.
*
* @see WpOrgRequestsRequests::request()
*
* @param string $url URL to request
* @param array $headers Extra headers to send with the request
* @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
* @param string $type HTTP request type (use WpOrgRequestsRequests constants)
* @param array $options Options for the request (see <a href="https://developer.wordpress.org/reference/classes/WpOrgRequestsRequests/request/">WpOrgRequestsRequests::request()</a>)
* @return WpOrgRequestsResponse
*
* @throws WpOrgRequestsException On invalid URLs (`nonhttp`)
*/
public function request($url, $headers = [], $data = [], $type = Requests::GET, $options = []) {
$request = $this->merge_request(compact('url', 'headers', 'data', 'options'));
return Requests::request($request['url'], $request['headers'], $request['data'], $type, $request['options']);
}
/**
* Send multiple HTTP requests simultaneously
*
* @see WpOrgRequestsRequests::request_multiple()
*
* @param array $requests Requests data (see <a href="https://developer.wordpress.org/reference/classes/WpOrgRequestsRequests/request_multiple/">WpOrgRequestsRequests::request_multiple()</a>)
* @param array $options Global and default options (see <a href="https://developer.wordpress.org/reference/classes/WpOrgRequestsRequests/request/">WpOrgRequestsRequests::request()</a>)
* @return array Responses (either WpOrgRequestsResponse or a WpOrgRequestsException object)
*
* @throws WpOrgRequestsExceptionInvalidArgument When the passed $requests argument is not an array or iterable object with array access.
* @throws WpOrgRequestsExceptionInvalidArgument When the passed $options argument is not an array.
*/
public function request_multiple($requests, $options = []) {
if (InputValidator::has_array_access($requests) === false || InputValidator::is_iterable($requests) === false) {
throw InvalidArgument::create(1, '$requests', 'array|ArrayAccess&Traversable;', gettype($requests));
}
if (is_array($options) === false) {
throw InvalidArgument::create(2, '$options', 'array', gettype($options));
}
foreach ($requests as $key => $request) {
$requests[$key] = $this->merge_request($request, false);
}
$options = array_merge($this->options, $options);
// Disallow forcing the type, as that's a per request setting
unset($options['type']);
return Requests::request_multiple($requests, $options);
}
public function __wakeup() {
throw new LogicException( __CLASS__ . ' should never be unserialized' );
}
/**
* Merge a request's data with the default data
*
* @param array $request Request data (same form as <a href="https://developer.wordpress.org/reference/classes/WpOrgRequestsSession/request_multiple/">WpOrgRequestsSession::request_multiple()</a>)
* @param boolean $merge_options Should we merge options as well?
* @return array Request data
*/
protected function merge_request($request, $merge_options = true) {
if ($this->url !== null) {
$request['url'] = Iri::absolutize($this->url, $request['url']);
$request['url'] = $request['url']->uri;
}
if (empty($request['headers'])) {
$request['headers'] = [];
}
$request['headers'] = array_merge($this->headers, $request['headers']);
if (empty($request['data'])) {
if (is_array($this->data)) {
$request['data'] = $this->data;
}
} elseif (is_array($request['data']) && is_array($this->data)) {
$request['data'] = array_merge($this->data, $request['data']);
}
if ($merge_options === true) {
$request['options'] = array_merge($this->options, $request['options']);
// Disallow forcing the type, as that's a per request setting
unset($request['options']['type']);
}
return $request;
}
}