api/Core/Controller.php

119 lines
3.2 KiB
PHP
Raw Normal View History

2019-03-30 12:19:46 +00:00
<?php
namespace Core;
use mysql_xdevapi\Exception;
/**
* Base controller
*
* PHP version 7.0
*/
abstract class Controller
{
/**
* Parameters from the matched route
* @var array
*/
protected $route_params = [];
2019-08-15 13:05:13 +00:00
protected $querys = [];
public $body ;
protected $input;
protected $debug = false;
protected $query_string;
2020-07-11 18:16:35 +00:00
protected $params = [];
2019-03-30 12:19:46 +00:00
/**
* Class constructor
*
* @param array $route_params Parameters from the route
*
* @return void
*/
public function __construct($route_params)
{
switch($_SERVER['CONTENT_TYPE']){
case 'application/json':
$this->body = file_get_contents('php://input');
$this->input = json_decode($this->body);
break;
}
2019-08-28 16:26:38 +00:00
preg_match("/^.{0,}\?(.{0,})$/i", $_SERVER['REQUEST_URI'], $matches);
if(sizeof($matches) > 0){
$pieces = explode("&", $matches['1']);
foreach ($pieces as $key => $value) {
$piece = explode("=", $value);
$this->querys[$piece[0]] = $piece[1];
2019-08-28 16:26:38 +00:00
}
2019-08-28 16:26:38 +00:00
}
2019-03-30 12:19:46 +00:00
$this->route_params = $route_params;
2020-07-12 07:59:34 +00:00
if(isset($route_params['id'])){
$this->params = explode('/',$route_params['id']);
}
2019-03-30 12:19:46 +00:00
}
/**
* Magic method called when a non-existent or inaccessible method is
* called on an object of this class. Used to execute before and after
* filter methods on action methods. Action methods need to be named
* with an "Action" suffix, e.g. indexAction, showAction etc.
*
* @param string $name Method name
* @param array $args Arguments passed to the method
*
* @return void
*/
public function __call($name, $args)
{
$method = $name . 'Action';
if (method_exists($this, $method)) {
if ($this->before() !== false) {
call_user_func_array([$this, $method], $args);
2019-03-30 12:19:46 +00:00
$this->after();
}
} else {
throw new \Exception("Method $method not found in controller " . get_class($this));
}
}
/**
* Before filter - called before an action method.
*
* @return void
*/
protected function before()
{
}
/**
* After filter - called after an action method.
*
* @return void
*/
protected function after(){
}
public function JsonResp($code,$data,$msg){
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:OPTIONS, GET, POST'); // 允许optiongetpost请求
header('Access-Control-Allow-Headers:x-requested-with'); // 允许x-requested-with请求头
header('Access-Control-Allow-Headers:x-ijt'); // 允许x-requested-with请求头
2019-08-23 09:16:40 +00:00
header('Content-Type: application/json'); // 允许x-requested-with请求头
2019-03-30 12:19:46 +00:00
$ret["code"] = $code;
$ret["msg"] = $msg;
$ret["data"] = $data;
$dat = json_encode ( $ret );
$this->_rsp($dat);
}
protected function _rsp($dat){
if (is_string($dat)){
print $dat;
}else{
throw new Exception("internal err",201);
}
}
protected function Crash($code,$msg){
}
}