ServiceModel 服务模块虚类
⚠️ ServiceModel 为抽象类,无法通过 new 方式实例化,仅通过 控制器 或其它 模块 的
getModel
方法获得,Azalea 中所有服务模块必须继承此类
Azalea\ServiceModel 继承于 Azalea\Model 模块类
服务路径定义
服务路径定义有 3 种方式:
- 默认:在默认情况下,服务路径将根据 配置项
['service']['url']
并加上 模块名 而成,如配置路径为"http://127.0.0.1:1108"
,模块名为"test"
,那么服务路径为"http://127.0.0.1:1108/test"
; - 定义
service
成员属性:定义该属性后,服务路径为配置路径加上service
属性值,如
protected $service = 'foo';
// 那么服务路径将变成 "http://127.0.0.1:1108/foo"
- 定义
serviceUrl
成员属性:定义该属性后,服务路径将直接使用该值,此方式常用于外部服务,如
protected $serviceUrl = 'http://upyun.com/upload';
当调用服务方法 (get
, post
, put
, delete
) 时,如果传入的第一个参数 $url
为 完整 URL (包含 http://
或 https://
),则直接使用该值;否则,将与 服务路径 (serviceUrl) 连接组成最终的服务请求 URL
常量
ServiceMode::METHOD_GET
- GET 请求方法
ServiceMode::METHOD_POST
- POST 请求方法
ServiceMode::METHOD_PUT
- PUT 请求方法
ServiceMode::METHOD_DELETE
- DELETE 请求方法
ServiceModel::get
GET 服务请求
mixed ServiceModel::get ( string $url [, array $fields = null] ) throws E500Exception
参数
$url - 服务路径
$fields - query 字段数组,将使用http_build_query
方法转换成字符串连接到$url
路径后返回值
调用结果异常
抛出 E500Exception 异常范例
$result = $this->get('foo?foo=bar', ['hello' => 'world', 'a' => 1]);
// 将产生类似 foo?foo=bar&hello=world&a=1 这样的 GET 请求
ServiceModel::post
POST 服务请求
mixed ServiceModel::post ( string $url [, array $fields = null] ) throws E500Exception
参数
$url - 服务路径
$fields - form 字段数组返回值
调用结果异常
抛出 E500Exception 异常范例
$result = $this->post('foo?foo=bar', ['hello' => 'world', 'a' => 1]);
ServiceModel::put
PUT 服务请求
同 ServiceModel::post
ServiceModel::delete
DELETE 服务请求
同 ServiceModel::post
ServiceMode::request
请求服务
mixed ServiceModel::request ( int $method, string $url [, array $fields = null [, array $headers = null [, bool $rawContent = false ]]] ) throws E500Exception
参数
$method - 请求方法 <small>(建议使用类常量)</small>
$url - 服务路径
$fields - form 字段数组
$headers - 自定义附加请求头
$rawContent - 是否返回完整响应内容,默认只返回"result"
部分返回值
调用结果异常
抛出 E500Exception 异常范例
// POST 调用 foo?foo=bar,传入 form 数组和自定义请求头,并按响应原文返回
$result = $this->request(self::METHOD_POST, 'foo?foo=bar', ['hello' => 'world', 'a' => 1], ['user' => 1], true);