123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- <?php
- namespace think\controller;
- use think\App;
- use think\Request;
- use think\Response;
- abstract class Rest
- {
- protected $method;
- protected $type;
-
- protected $restMethodList = 'get|post|put|delete';
- protected $restDefaultMethod = 'get';
- protected $restTypeList = 'html|xml|json|rss';
- protected $restDefaultType = 'html';
- protected $restOutputType = [
- 'xml' => 'application/xml',
- 'json' => 'application/json',
- 'html' => 'text/html',
- ];
-
- public function __construct()
- {
-
- $request = Request::instance();
- $ext = $request->ext();
- if ('' == $ext) {
-
- $this->type = $request->type();
- } elseif (!preg_match('/(' . $this->restTypeList . ')$/i', $ext)) {
-
- $this->type = $this->restDefaultType;
- } else {
- $this->type = $ext;
- }
-
- $method = strtolower($request->method());
- if (!preg_match('/(' . $this->restMethodList . ')$/i', $method)) {
-
- $method = $this->restDefaultMethod;
- }
- $this->method = $method;
- }
-
- public function _empty($method)
- {
- if (method_exists($this, $method . '_' . $this->method . '_' . $this->type)) {
-
- $fun = $method . '_' . $this->method . '_' . $this->type;
- } elseif ($this->method == $this->restDefaultMethod && method_exists($this, $method . '_' . $this->type)) {
- $fun = $method . '_' . $this->type;
- } elseif ($this->type == $this->restDefaultType && method_exists($this, $method . '_' . $this->method)) {
- $fun = $method . '_' . $this->method;
- }
- if (isset($fun)) {
- return App::invokeMethod([$this, $fun]);
- } else {
-
- throw new \Exception('error action :' . $method);
- }
- }
-
- protected function response($data, $type = 'json', $code = 200)
- {
- return Response::create($data, $type)->code($code);
- }
- }
|