Class yii\httpclient\Client

Inheritanceyii\httpclient\Client » yii\base\Component
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-httpclient/blob/master/src/Client.php

Client provide high level interface for HTTP requests execution.

Public Properties

Hide inherited properties

Property Type Description Defined By
$baseUrl string Base request URL. yii\httpclient\Client
$contentLoggingMaxSize integer Maximum symbols count of the request content, which should be taken to compose a log and profile messages. yii\httpclient\Client
$formatters array The formatters for converting data into the content of the specified format. yii\httpclient\Client
$parsers array The parsers for converting content of the specified format into the data. yii\httpclient\Client
$requestConfig array Request object configuration. yii\httpclient\Client
$responseConfig array Response config configuration. yii\httpclient\Client
$transport yii\httpclient\Transport HTTP message transport instance. yii\httpclient\Client

Public Methods

Hide inherited methods

Method Description Defined By
afterSend() This method is invoked right after request is sent. yii\httpclient\Client
batchSend() Performs multiple HTTP requests in parallel. yii\httpclient\Client
beforeSend() This method is invoked right before request is sent. yii\httpclient\Client
createRequest() yii\httpclient\Client
createRequestLogToken() Composes the log/profiling message token for the given HTTP request parameters. yii\httpclient\Client
createResponse() Creates a response instance. yii\httpclient\Client
delete() Creates 'DELETE' request. yii\httpclient\Client
get() Creates 'GET' request. yii\httpclient\Client
getFormatter() Returns HTTP message formatter instance for the specified format. yii\httpclient\Client
getParser() Returns HTTP message parser instance for the specified format. yii\httpclient\Client
getTransport() yii\httpclient\Client
head() Creates 'HEAD' request. yii\httpclient\Client
options() Creates 'OPTIONS' request. yii\httpclient\Client
patch() Creates 'PATCH' request. yii\httpclient\Client
post() Creates 'POST' request. yii\httpclient\Client
put() Creates 'PUT' request. yii\httpclient\Client
send() Performs given request. yii\httpclient\Client
setTransport() Sets the HTTP message transport. It can be specified in one of the following forms: yii\httpclient\Client

Protected Methods

Hide inherited methods

Method Description Defined By
createRequestShortcut() yii\httpclient\Client

Events

Hide inherited events

Event Type Description Defined By
EVENT_AFTER_SEND yii\httpclient\RequestEvent An event raised right after request has been sent. yii\httpclient\Client
EVENT_BEFORE_SEND yii\httpclient\RequestEvent An event raised right before sending request. yii\httpclient\Client

Constants

Hide inherited constants

Constant Value Description Defined By
FORMAT_CURL 'curl' CURL format yii\httpclient\Client
FORMAT_JSON 'json' JSON format yii\httpclient\Client
FORMAT_RAW_URLENCODED 'raw-urlencoded' Urlencoded by PHP_QUERY_RFC3986 query string, like name1=value1&name2=value2 yii\httpclient\Client
FORMAT_URLENCODED 'urlencoded' Urlencoded by RFC1738 query string, like name1=value1&name2=value2 yii\httpclient\Client
FORMAT_XML 'xml' XML format yii\httpclient\Client

Property Details

Hide inherited properties

$baseUrl public property

Base request URL.

public string $baseUrl null
$contentLoggingMaxSize public property

Maximum symbols count of the request content, which should be taken to compose a log and profile messages. Exceeding content will be truncated.

See also createRequestLogToken().

$formatters public property

The formatters for converting data into the content of the specified format. The array keys are the format names, and the array values are the corresponding configurations for creating the formatter objects.

public array $formatters = []
$parsers public property

The parsers for converting content of the specified format into the data. The array keys are the format names, and the array values are the corresponding configurations for creating the parser objects.

public array $parsers = []
$requestConfig public property

Request object configuration.

public array $requestConfig = []
$responseConfig public property

Response config configuration.

public array $responseConfig = []
$transport public property

HTTP message transport instance. Note that the type of this property differs in getter and setter. See getTransport() and setTransport() for details.

Method Details

Hide inherited methods

afterSend() public method (available since version 2.0.1)

This method is invoked right after request is sent.

The method will trigger the EVENT_AFTER_SEND event.

public void afterSend ( $request, $response )
$request yii\httpclient\Request

Request instance.

$response yii\httpclient\Response

Received response instance.

                public function afterSend($request, $response)
{
    $event = new RequestEvent();
    $event->request = $request;
    $event->response = $response;
    $this->trigger(self::EVENT_AFTER_SEND, $event);
}

            
batchSend() public method

Performs multiple HTTP requests in parallel.

This method accepts an array of the yii\httpclient\Request objects and returns an array of the yii\httpclient\Response objects. Keys of the response array correspond the ones from request array.

$client = new Client();
$requests = [
    'news' => $client->get('http://domain.com/news'),
    'friends' => $client->get('http://domain.com/user/friends', ['userId' => 12]),
];
$responses = $client->batchSend($requests);
var_dump($responses['news']->isOk);
var_dump($responses['friends']->isOk);
public yii\httpclient\Response[] batchSend ( array $requests )
$requests yii\httpclient\Request[]

Requests to perform.

return yii\httpclient\Response[]

Responses list.

throws yii\httpclient\Exception
throws \yii\base\InvalidConfigException

                public function batchSend(array $requests)
{
    return $this->getTransport()->batchSend($requests);
}

            
beforeSend() public method (available since version 2.0.1)

This method is invoked right before request is sent.

The method will trigger the EVENT_BEFORE_SEND event.

public void beforeSend ( $request )
$request yii\httpclient\Request

Request instance.

                public function beforeSend($request)
{
    $event = new RequestEvent();
    $event->request = $request;
    $this->trigger(self::EVENT_BEFORE_SEND, $event);
}

            
createRequest() public method

public yii\httpclient\Request createRequest ( )
return yii\httpclient\Request

Request instance.

throws \yii\base\InvalidConfigException

                public function createRequest()
{
    $config = $this->requestConfig;
    if (!isset($config['class'])) {
        $config['class'] = Request::className();
    }
    $config['client'] = $this;
    return Yii::createObject($config);
}

            
createRequestLogToken() public method

Composes the log/profiling message token for the given HTTP request parameters.

This method should be used by transports during request sending logging.

public string createRequestLogToken ( $method, $url, $headers, $content )
$method string

Request method name.

$url string

Request URL.

$headers array

Request headers.

$content string

Request content.

return string

Log token.

                public function createRequestLogToken($method, $url, $headers, $content)
{
    $token = strtoupper($method) . ' ' . $url;
    if (!empty($headers)) {
        $token .= "\n" . implode("\n", $headers);
    }
    if ($content !== null) {
        $token .= "\n\n" . StringHelper::truncate($content, $this->contentLoggingMaxSize);
    }
    return $token;
}

            
createRequestShortcut() protected method

protected yii\httpclient\Request createRequestShortcut ( $method, $url, $data, $headers, $options )
$method string
$url array|string
$data array|string
$headers array
$options array
return yii\httpclient\Request

Request instance.

throws \yii\base\InvalidConfigException

                protected function createRequestShortcut($method, $url, $data, $headers, $options)
{
    $request = $this->createRequest()
        ->setMethod($method)
        ->setUrl($url)
        ->addHeaders($headers)
        ->addOptions($options);
    if (is_array($data)) {
        $request->setData($data);
    } else {
        $request->setContent($data);
    }
    return $request;
}

            
createResponse() public method

Creates a response instance.

public yii\httpclient\Response createResponse ( $content null, array $headers = [] )
$content string

Raw content

$headers array

Headers list.

return yii\httpclient\Response

Request instance.

throws \yii\base\InvalidConfigException

                public function createResponse($content = null, array $headers = [])
{
    $config = $this->responseConfig;
    if (!isset($config['class'])) {
        $config['class'] = Response::className();
    }
    $config['client'] = $this;
    $response = Yii::createObject($config);
    $response->setContent($content);
    $response->setHeaders($headers);
    return $response;
}

            
delete() public method

Creates 'DELETE' request.

public yii\httpclient\Request delete ( $url, $data null, $headers = [], $options = [] )
$url array|string

Target URL.

$data array|string

If array - request data, otherwise - request content.

$headers array

Request headers.

$options array

Request options.

return yii\httpclient\Request

Request instance.

                public function delete($url, $data = null, $headers = [], $options = [])
{
    return $this->createRequestShortcut('DELETE', $url, $data, $headers, $options);
}

            
get() public method

Creates 'GET' request.

public yii\httpclient\Request get ( $url, $data null, $headers = [], $options = [] )
$url array|string

Target URL.

$data array|string

If array - request data, otherwise - request content.

$headers array

Request headers.

$options array

Request options.

return yii\httpclient\Request

Request instance.

                public function get($url, $data = null, $headers = [], $options = [])
{
    return $this->createRequestShortcut('GET', $url, $data, $headers, $options);
}

            
getFormatter() public method

Returns HTTP message formatter instance for the specified format.

public yii\httpclient\FormatterInterface getFormatter ( $format )
$format string

Format name.

return yii\httpclient\FormatterInterface

Formatter instance.

throws \yii\base\InvalidParamException

on invalid format name.

throws \yii\base\InvalidConfigException

                public function getFormatter($format)
{
    static $defaultFormatters = [
        self::FORMAT_JSON => 'yii\httpclient\JsonFormatter',
        self::FORMAT_URLENCODED => [
            'class' => 'yii\httpclient\UrlEncodedFormatter',
            'encodingType' => PHP_QUERY_RFC1738
        ],
        self::FORMAT_RAW_URLENCODED => [
            'class' => 'yii\httpclient\UrlEncodedFormatter',
            'encodingType' => PHP_QUERY_RFC3986
        ],
        self::FORMAT_XML => 'yii\httpclient\XmlFormatter',
        self::FORMAT_CURL => 'yii\httpclient\CurlFormatter',
    ];
    if (!isset($this->formatters[$format])) {
        if (!isset($defaultFormatters[$format])) {
            throw new InvalidParamException("Unrecognized format '{$format}'");
        }
        $this->formatters[$format] = $defaultFormatters[$format];
    }
    if (!is_object($this->formatters[$format])) {
        $this->formatters[$format] = Yii::createObject($this->formatters[$format]);
    }
    return $this->formatters[$format];
}

            
getParser() public method

Returns HTTP message parser instance for the specified format.

public yii\httpclient\ParserInterface getParser ( $format )
$format string

Format name

return yii\httpclient\ParserInterface

Parser instance.

throws \yii\base\InvalidParamException

on invalid format name.

throws \yii\base\InvalidConfigException

                public function getParser($format)
{
    static $defaultParsers = [
        self::FORMAT_JSON => 'yii\httpclient\JsonParser',
        self::FORMAT_URLENCODED => 'yii\httpclient\UrlEncodedParser',
        self::FORMAT_RAW_URLENCODED => 'yii\httpclient\UrlEncodedParser',
        self::FORMAT_XML => 'yii\httpclient\XmlParser',
    ];
    if (!isset($this->parsers[$format])) {
        if (!isset($defaultParsers[$format])) {
            throw new InvalidParamException("Unrecognized format '{$format}'");
        }
        $this->parsers[$format] = $defaultParsers[$format];
    }
    if (!is_object($this->parsers[$format])) {
        $this->parsers[$format] = Yii::createObject($this->parsers[$format]);
    }
    return $this->parsers[$format];
}

            
getTransport() public method

public yii\httpclient\Transport getTransport ( )
return yii\httpclient\Transport

HTTP message transport instance.

throws \yii\base\InvalidConfigException

                public function getTransport()
{
    if (!is_object($this->_transport)) {
        $this->_transport = Yii::createObject($this->_transport);
    }
    return $this->_transport;
}

            
head() public method

Creates 'HEAD' request.

public yii\httpclient\Request head ( $url, $headers = [], $options = [] )
$url array|string

Target URL.

$headers array

Request headers.

$options array

Request options.

return yii\httpclient\Request

Request instance.

                public function head($url, $headers = [], $options = [])
{
    return $this->createRequestShortcut('HEAD', $url, null, $headers, $options);
}

            
options() public method

Creates 'OPTIONS' request.

public yii\httpclient\Request options ( $url, $options = [] )
$url array|string

Target URL.

$options array

Request options.

return yii\httpclient\Request

Request instance.

                public function options($url, $options = [])
{
    return $this->createRequestShortcut('OPTIONS', $url, null, [], $options);
}

            
patch() public method

Creates 'PATCH' request.

public yii\httpclient\Request patch ( $url, $data null, $headers = [], $options = [] )
$url array|string

Target URL.

$data array|string

If array - request data, otherwise - request content.

$headers array

Request headers.

$options array

Request options.

return yii\httpclient\Request

Request instance.

                public function patch($url, $data = null, $headers = [], $options = [])
{
    return $this->createRequestShortcut('PATCH', $url, $data, $headers, $options);
}

            
post() public method

Creates 'POST' request.

public yii\httpclient\Request post ( $url, $data null, $headers = [], $options = [] )
$url array|string

Target URL.

$data array|string

If array - request data, otherwise - request content.

$headers array

Request headers.

$options array

Request options.

return yii\httpclient\Request

Request instance.

                public function post($url, $data = null, $headers = [], $options = [])
{
    return $this->createRequestShortcut('POST', $url, $data, $headers, $options);
}

            
put() public method

Creates 'PUT' request.

public yii\httpclient\Request put ( $url, $data null, $headers = [], $options = [] )
$url array|string

Target URL.

$data array|string

If array - request data, otherwise - request content.

$headers array

Request headers.

$options array

Request options.

return yii\httpclient\Request

Request instance.

                public function put($url, $data = null, $headers = [], $options = [])
{
    return $this->createRequestShortcut('PUT', $url, $data, $headers, $options);
}

            
send() public method

Performs given request.

public yii\httpclient\Response send ( $request )
$request yii\httpclient\Request

Request to be sent.

return yii\httpclient\Response

Response instance.

throws yii\httpclient\Exception

on failure.

throws \yii\base\InvalidConfigException

                public function send($request)
{
    return $this->getTransport()->send($request);
}

            
setTransport() public method

Sets the HTTP message transport. It can be specified in one of the following forms:

  • an instance of Transport: actual transport object to be used
  • a string: representing the class name of the object to be created
  • a configuration array: the array must contain a class element which is treated as the object class, and the rest of the name-value pairs will be used to initialize the corresponding object properties
  • a PHP callable: either an anonymous function or an array representing a class method ([$class or $object, $method]). The callable should return a new instance of the object being created.
public void setTransport ( $transport )
$transport yii\httpclient\Transport|array|string

HTTP message transport

                public function setTransport($transport)
{
    $this->_transport = $transport;
}

            

Event Details

Hide inherited properties

EVENT_AFTER_SEND event of type yii\httpclient\RequestEvent

An event raised right after request has been sent.

EVENT_BEFORE_SEND event of type yii\httpclient\RequestEvent

An event raised right before sending request.