有什么用
可以帮助我们构建复杂的,可扩的运用。比如自动加载插件,自动生成文档等
代码示例
该示例为一个通用API入口
HttpApi.php
namespace twinkleservicehttp;
class HttpApi
{
private $class;
public function __construct($class)
{
$this->class = $class;
}
public function parseRequest($method,$params = [])
{
$class = new ReflectionClass($this->class);
$instance = $class->newInstanceArgs($params);
$method = $class->getMethod($method);
$args = [];
foreach ($method->getParameters() as $param) {
$name = $param->getName();
if (isset($params[$name])) {
$args[$name] = $params[$name];
} else {
try {
$args[$name] = $param->getDefaultValue();
} catch (Exception $e) {
throw new RequestException(
'请求参数不合未能',
500
);
}
}
}
return [$instance,$method,$args];
}
}NotFoundService.php
namespace appservices;
use appaseService;
class NotFoundService extends Service
{
public function error()
{
return $this->format(['status' => 1, 'msg' => '请求不合法,请确认service和method是否存在']);
}
}使用范例
$params = $_REQUEST; $serviceName= isset($params['service']) ? $params['service'] : 'NotFound'; $methodName= isset($params['method']) ? $params['method'] : 'error'; $class = '\app\services\' . Str::ucWords($serviceName) . 'Service'; list($instance, $method, $args) = (new HttpApi($class))->parseRequest($methodName, $params); echo json_encode(($method->invokeArgs($instance, $args)));
| 欢迎光临 一起源码网 (https://www.171739.xyz/) | Powered by Discuz! X3.3 |