规范代码风格

This commit is contained in:
TOP糯米 2019-06-19 15:28:15 +08:00
parent fa4c6912d6
commit 8ef1bae0e0
43 changed files with 735 additions and 435 deletions

View File

@ -16,8 +16,8 @@ return [
'driver' => 'MySQLi', 'driver' => 'MySQLi',
'host' => '127.0.0.1', 'host' => '127.0.0.1',
'user' => 'root', 'user' => 'root',
'passwd' => 'root', 'passwd' => '',
'dbname' => 'hongzheng', 'dbname' => '',
'prefix' => 'cms_', 'prefix' => 'cms_',
'charset' => 'utf8' 'charset' => 'utf8'
], ],

View File

@ -13,7 +13,7 @@ class Index extends Common {
public function index() { public function index() {
$model = model(Job::class); $model = model(Job::class);
return [ return [
'title' => '测试模型高级操作', 'title' => '测试',
'lists' => $model->select(), 'lists' => $model->select(),
'query' => $model->sql 'query' => $model->sql
]; ];

View File

@ -12,7 +12,8 @@ use top\library\App;
* [] 为可选参数 * [] 为可选参数
* @author topnuomi 2018年11月19日 * @author topnuomi 2018年11月19日
*/ */
class Framework { class Framework
{
// 程序运行方式 // 程序运行方式
private static $type = 1; private static $type = 1;
@ -24,7 +25,8 @@ class Framework {
* 执行 * 执行
* @param string $callable * @param string $callable
*/ */
public static function startApp($callable = '') { public static function startApp($callable = '')
{
header('content-type: text/html; charset=utf-8'); header('content-type: text/html; charset=utf-8');
if (is_callable($callable)) { if (is_callable($callable)) {
@ -48,7 +50,8 @@ class Framework {
* 是否开启DEBUG * 是否开启DEBUG
* @param bool $status * @param bool $status
*/ */
public static function debug($status = false) { public static function debug($status = false)
{
if (!defined('DEBUG')) { if (!defined('DEBUG')) {
define('DEBUG', $status); define('DEBUG', $status);
} }
@ -58,7 +61,8 @@ class Framework {
* 指定框架目录 * 指定框架目录
* @param string $path * @param string $path
*/ */
public static function frameworkPath($path = '') { public static function frameworkPath($path = '')
{
if (!defined('FRAMEWORK_PATH')) { if (!defined('FRAMEWORK_PATH')) {
if (!$path) { if (!$path) {
$path = __DIR__ . '/'; $path = __DIR__ . '/';
@ -71,7 +75,8 @@ class Framework {
* 应用目录 * 应用目录
* @param string $path * @param string $path
*/ */
public static function appPath($path = '') { public static function appPath($path = '')
{
if (!defined('APP_PATH')) { if (!defined('APP_PATH')) {
if (!$path) { if (!$path) {
$path = './application/'; $path = './application/';
@ -80,7 +85,8 @@ class Framework {
} }
} }
public static function appNameSpace($namespace = '') { public static function appNameSpace($namespace = '')
{
if (!defined('APP_NS')) { if (!defined('APP_NS')) {
if (!$namespace) { if (!$namespace) {
$namespace = 'app'; $namespace = 'app';
@ -93,7 +99,8 @@ class Framework {
* 指定Resource目录 * 指定Resource目录
* @param string $path * @param string $path
*/ */
public static function resourcePath($path = '') { public static function resourcePath($path = '')
{
if (!defined('RESOURCE')) { if (!defined('RESOURCE')) {
if (!$path && isset($_SERVER['SCRIPT_NAME'])) { if (!$path && isset($_SERVER['SCRIPT_NAME'])) {
$scriptName = $_SERVER['SCRIPT_NAME']; $scriptName = $_SERVER['SCRIPT_NAME'];
@ -109,7 +116,8 @@ class Framework {
* 指定默认访问位置 * 指定默认访问位置
* @param string $module * @param string $module
*/ */
public static function defaultModule($module) { public static function defaultModule($module)
{
self::$defaultModule = $module; self::$defaultModule = $module;
} }
@ -117,7 +125,8 @@ class Framework {
* 指定程序运行方式 * 指定程序运行方式
* @param int $type * @param int $type
*/ */
public static function runType($type) { public static function runType($type)
{
self::$type = $type; self::$type = $type;
} }
} }

View File

@ -1,6 +1,7 @@
<?php <?php
class Create { class Create
{
private $name; private $name;
@ -14,7 +15,8 @@ class Create {
private $projectPath; private $projectPath;
public function __construct($start, $namespace, $name) { public function __construct($start, $namespace, $name)
{
$this->name = $name; $this->name = $name;
$this->dir = __DIR__ . '/'; $this->dir = __DIR__ . '/';
$this->namespace = $namespace; $this->namespace = $namespace;
@ -25,7 +27,8 @@ class Create {
$this->create(); $this->create();
} }
public function replaceContent($content) { public function replaceContent($content)
{
return str_replace([ return str_replace([
'{namespace}', '{namespace}',
'{name}' '{name}'
@ -35,7 +38,8 @@ class Create {
], $content); ], $content);
} }
public function createStartFile() { public function createStartFile()
{
if ($this->start && !file_exists($this->start)) { if ($this->start && !file_exists($this->start)) {
$content = file_get_contents($this->dir . 'tpl/index.tpl'); $content = file_get_contents($this->dir . 'tpl/index.tpl');
$content = $this->replaceContent($content); $content = $this->replaceContent($content);
@ -47,7 +51,8 @@ class Create {
return true; return true;
} }
public function createConfig() { public function createConfig()
{
$configPath = $this->projectPath . 'config/'; $configPath = $this->projectPath . 'config/';
$configFile = $configPath . 'config.php'; $configFile = $configPath . 'config.php';
$tagsFile = $configPath . 'tags.php'; $tagsFile = $configPath . 'tags.php';
@ -71,7 +76,8 @@ class Create {
return true; return true;
} }
public function createMVC() { public function createMVC()
{
$dirArray = [ $dirArray = [
'controller', 'controller',
'model', 'model',
@ -110,7 +116,8 @@ class Create {
} }
} }
public function createFunctions() { public function createFunctions()
{
$file = $this->projectPath . 'functions.php'; $file = $this->projectPath . 'functions.php';
if (!file_exists($file)) { if (!file_exists($file)) {
if (!file_put_contents($file, "<?php\r\n")) { if (!file_put_contents($file, "<?php\r\n")) {
@ -119,7 +126,8 @@ class Create {
} }
} }
public function createRoute() { public function createRoute()
{
$file = $this->projectPath . '../route.php'; $file = $this->projectPath . '../route.php';
if (!file_exists($file)) { if (!file_exists($file)) {
if (!file_put_contents($file, "<?php \r\nreturn [];")) { if (!file_put_contents($file, "<?php \r\nreturn [];")) {
@ -128,7 +136,8 @@ class Create {
} }
} }
public function create() { public function create()
{
$this->createStartFile(); $this->createStartFile();
$this->createConfig(); $this->createConfig();
$this->createMVC(); $this->createMVC();
@ -141,4 +150,4 @@ class Create {
$namespace = (isset($argv[1]) && $argv[1]) ? $argv[1] : exit('please type namespace~'); $namespace = (isset($argv[1]) && $argv[1]) ? $argv[1] : exit('please type namespace~');
$projectName = (isset($argv[2]) && $argv[2]) ? $argv[2] : exit('please type project name~'); $projectName = (isset($argv[2]) && $argv[2]) ? $argv[2] : exit('please type project name~');
$startFile = (isset($argv[3]) && $argv[3]) ? $argv[3] : false; $startFile = (isset($argv[3]) && $argv[3]) ? $argv[3] : false;
new Create($startFile, $namespace, $projectName); new Create($startFile, $namespace, $projectName);

View File

@ -1,9 +1,9 @@
<?php <?php
return [ return [
'register' => [ 'register' => [
'Twig' => top\library\template\Twig::class, 'Twig' => \top\library\template\driver\Twig::class,
// 'Smarty' => top\library\template\Smarty::class, // 'Smarty' => \top\library\template\driver\Smarty::class,
// 'Top' => top\library\template\Top::class, // 'Top' => \top\library\template\driver\Top::class,
], ],
'decorator' => [], 'decorator' => [],
'session' => [ 'session' => [

View File

@ -4,12 +4,14 @@ namespace app\{name}\controller;
use top\library\Controller; use top\library\Controller;
use app\{name}\model\Demo; use app\{name}\model\Demo;
class Index extends Controller { class Index extends Controller
{
public function index() { public function index()
{
$model = new Demo(); $model = new Demo();
return [ return [
'data' => $model->get(1) 'data' => $model->get(1)
]; ];
} }
} }

View File

@ -2,13 +2,37 @@
use \top\Framework; use \top\Framework;
// 是否开启DEBUG模式
define('DEBUG', true);
// APP目录
define('APP_PATH', '../application/');
// 框架目录
define('FRAMEWORK_PATH', '../framework/');
// 加载框架
require '../framework/Framework.php'; require '../framework/Framework.php';
// 可能你会使用到下面这些配置
// 调试模式缺省值false
// Framework::debug(true);
// 可使用常量DEBUG取得该值
// 项目目录,缺省值:./application/
// Framework::appPath('../application/');
// 可使用常量APP_PATH取得该值
// 项目命名空间缺省值app
// Framework::appNameSpace('app');
// 可使用常量APP_NS取得该值
// 框架目录缺省值Framework.php的绝对路径
// Framework::frameworkPath('../framework');
// 可使用常量FRAMEWORK_PATH取得该值
// 静态资源目录,缺省值:/resource/
// Framework::resourcePath('/resource/');
// 可使用常量RESOURCE取得该值
// 当前入口文件默认模块缺省值home
// Framework::defaultModule('home');
// 路由模式缺省值1pathinfo和兼容模式
// Framework::runType(1);
Framework::appPath('../application/');
// 执行程序
Framework::startApp(); Framework::startApp();

View File

@ -3,13 +3,15 @@ namespace app\{name}\model;
use top\library\Model; use top\library\Model;
class Demo extends Model { class Demo extends Model
{
protected $table = ''; protected $table = '';
protected $pk = ''; protected $pk = '';
protected $map = []; protected $map = [];
public function get($id) { public function get($id)
{
return $id; return $id;
} }
} }

View File

@ -12,13 +12,15 @@ use top\library\cache\FileCache;
* *
* @author topnuomi 2018年11月20日 * @author topnuomi 2018年11月20日
*/ */
class InitDecorator implements DecoratorIfs { class InitDecorator implements DecoratorIfs
{
/** /**
* 注册一些可能会用到的类 * 注册一些可能会用到的类
* @throws \Exception * @throws \Exception
*/ */
public function before() { public function before()
{
$route = Register::get('Router'); $route = Register::get('Router');
$sessionConfig = Register::get('Config')->get('session'); $sessionConfig = Register::get('Config')->get('session');
@ -67,7 +69,8 @@ class InitDecorator implements DecoratorIfs {
/** /**
* @param array $data * @param array $data
*/ */
public function after($data) { public function after($data)
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
} }

View File

@ -10,18 +10,20 @@ use top\library\Register;
* *
* @author topnuomi 2018年11月22日 * @author topnuomi 2018年11月22日
*/ */
class ReturnDecorator implements DecoratorIfs { class ReturnDecorator implements DecoratorIfs
{
public function before() { public function before()
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/** /**
* 布尔或数组则显示视图 * 布尔或数组则显示视图
* @param array $data * @param array $data
* @throws \top\library\exception\BaseException
*/ */
public function after($data) { public function after($data)
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
if (is_bool($data) && $data === true) if (is_bool($data) && $data === true)
$data = []; $data = [];
@ -35,4 +37,4 @@ class ReturnDecorator implements DecoratorIfs {
} }
} }
} }
} }

View File

@ -6,12 +6,13 @@ use top\decorator\ifs\DecoratorIfs;
/** /**
* 辅助控制器的装饰器 * 辅助控制器的装饰器
*
* @author topnuomi 2018年11月22日 * @author topnuomi 2018年11月22日
*/ */
class StringDecorator implements DecoratorIfs { class StringDecorator implements DecoratorIfs
{
public function before() { public function before()
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@ -19,11 +20,12 @@ class StringDecorator implements DecoratorIfs {
* 字符串则直接输出 * 字符串则直接输出
* @param array $data * @param array $data
*/ */
public function after($data) { public function after($data)
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
// 如果是字符串直接echo // 如果是字符串直接echo
if (!is_array($data) && !is_bool($data) && !is_object($data)) { if (!is_array($data) && !is_bool($data) && !is_object($data)) {
echo $data; echo $data;
} }
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
namespace top\decorator\ifs; namespace top\decorator\ifs;
/** /**
@ -6,7 +7,8 @@ namespace top\decorator\ifs;
* *
* @author topnuomi 2018年11月22日 * @author topnuomi 2018年11月22日
*/ */
interface DecoratorIfs { interface DecoratorIfs
{
/** /**
* 前置操作 * 前置操作
@ -15,8 +17,7 @@ interface DecoratorIfs {
/** /**
* 后置操作 * 后置操作
* * @param array $data
* @param array $data
*/ */
public function after($data); public function after($data);
} }

View File

@ -6,10 +6,10 @@ use top\library\Register;
/** /**
* 分页类 * 分页类
*
* @author topnuomi 2018年11月28日 * @author topnuomi 2018年11月28日
*/ */
class Page { class Page
{
// 每页显示记录数 // 每页显示记录数
public $listRow; public $listRow;
@ -25,27 +25,32 @@ class Page {
public $firstRow; public $firstRow;
public function __construct($listRow, $total) { public function __construct($listRow, $total)
{
$this->listRow = $listRow; $this->listRow = $listRow;
$this->total = $total; $this->total = $total;
$this->page = (isset($_GET['p']) && $_GET['p']) ? (int)$_GET['p'] : ((isset($_POST['p']) && $_POST['p']) ? (int)$_POST['p'] : 1); $this->page = (isset($_GET['p']) && $_GET['p']) ? (int)$_GET['p'] : ((isset($_POST['p']) && $_POST['p']) ? (int)$_POST['p'] : 1);
} }
private function firstRow() { private function firstRow()
{
return ($this->page - 1) * $this->listRow; return ($this->page - 1) * $this->listRow;
} }
private function totalPage() { private function totalPage()
{
return ceil($this->total / $this->listRow); return ceil($this->total / $this->listRow);
} }
public function process() { public function process()
{
$this->totalPage = $this->totalPage(); $this->totalPage = $this->totalPage();
$this->firstRow = $this->firstRow(); $this->firstRow = $this->firstRow();
return $this; return $this;
} }
public function html() { public function html()
{
$url = Register::get('Route')->rawUri; $url = Register::get('Route')->rawUri;
// 链接没有匹配&或?,配置了伪静态也就无所谓了 // 链接没有匹配&或?,配置了伪静态也就无所谓了
$html = '<ul>'; $html = '<ul>';
@ -55,4 +60,4 @@ class Page {
$html .= '</ul>'; $html .= '</ul>';
return $html; return $html;
} }
} }

View File

@ -8,14 +8,16 @@ use top\library\Loader;
* 文件上传类 * 文件上传类
* @author TOP糯米 * @author TOP糯米
*/ */
class Upload { class Upload
{
private static $instance; private static $instance;
private static $fileType; private static $fileType;
private static $dirName; private static $dirName;
private $image; private $image;
private $error; private $error;
private function __construct() { private function __construct()
{
} }
/** /**
@ -24,7 +26,8 @@ class Upload {
* @param string $fileType * @param string $fileType
* @return Upload * @return Upload
*/ */
public static function init($dirName, $fileType = '') { public static function init($dirName, $fileType = '')
{
if (!self::$instance) { if (!self::$instance) {
self::$instance = new self(); self::$instance = new self();
} }
@ -37,11 +40,13 @@ class Upload {
* 获取错误信息 * 获取错误信息
* @return string * @return string
*/ */
public function getError() { public function getError()
{
return $this->error; return $this->error;
} }
public function uploadPicture($fileName = '', $width = 0, $height = 0, $waterFile = '') { public function uploadPicture($fileName = '', $width = 0, $height = 0, $waterFile = '')
{
if (!empty($_FILES)) { if (!empty($_FILES)) {
$data = []; $data = [];
$picture = Loader::model('Picture'); $picture = Loader::model('Picture');
@ -90,4 +95,4 @@ class Upload {
$this->error = '请上传文件'; $this->error = '请上传文件';
return false; return false;
} }
} }

View File

@ -6,7 +6,8 @@ namespace top\extend;
* 水印处理类 * 水印处理类
* @author TOP糯米 * @author TOP糯米
*/ */
class Water { class Water
{
/** /**
* 错误信息 * 错误信息
* @var int|string|boolean * @var int|string|boolean
@ -19,14 +20,16 @@ class Water {
*/ */
private $waterPath = ''; private $waterPath = '';
public function __construct() { public function __construct()
{
} }
/** /**
* 获取错误信息 * 获取错误信息
* @return int|string|boolean 错误信息 * @return int|string|boolean 错误信息
*/ */
public function getError() { public function getError()
{
return $this->error; return $this->error;
} }
@ -34,7 +37,8 @@ class Water {
* 指定水印文件 * 指定水印文件
* @param string $file [description] * @param string $file [description]
*/ */
public function waterFile($file = '') { public function waterFile($file = '')
{
$this->waterPath = $file; $this->waterPath = $file;
} }
@ -44,7 +48,8 @@ class Water {
* @param boolean $cover 是否覆盖原始图片 * @param boolean $cover 是否覆盖原始图片
* @return string 文件名 * @return string 文件名
*/ */
private function addWater($file, $cover) { private function addWater($file, $cover)
{
if ($this->waterPath == '') { if ($this->waterPath == '') {
$this->error = '请先调用waterFile方法来指定水印文件'; $this->error = '请先调用waterFile方法来指定水印文件';
return false; return false;
@ -103,7 +108,8 @@ class Water {
* @param boolean $cover 是否覆盖原始图片,默认覆盖 * @param boolean $cover 是否覆盖原始图片,默认覆盖
* @return boolean 成功|失败 * @return boolean 成功|失败
*/ */
public function handler($file = '', $cover = true) { public function handler($file = '', $cover = true)
{
if ($file == '') { if ($file == '') {
$this->error = '请指定要处理的图片文件'; $this->error = '请指定要处理的图片文件';
return false; return false;
@ -116,4 +122,4 @@ class Water {
return false; return false;
} }
} }
} }

View File

@ -5,13 +5,16 @@ namespace top\library;
use top\library\route\Command; use top\library\route\Command;
use top\library\route\Pathinfo; use top\library\route\Pathinfo;
class App { class App
{
/** /**
* 执行
* @param int $type * @param int $type
* @param string $defaultModule * @param string $defaultModule
*/ */
public static function start($type = 1, $defaultModule = 'home') { public static function start($type = 1, $defaultModule = 'home')
{
// 注册框架自动加载 // 注册框架自动加载
require 'Loader.php'; require 'Loader.php';
$loader = new Loader(); $loader = new Loader();
@ -52,4 +55,4 @@ class App {
// 实例化路由 // 实例化路由
(new Router($routeDriver, $defaultModule))->handler(); (new Router($routeDriver, $defaultModule))->handler();
} }
} }

View File

@ -1,12 +1,13 @@
<?php <?php
namespace top\library; namespace top\library;
/** /**
* 配置类 * 配置类
*
* @author topnuomi 2018年11月20日 * @author topnuomi 2018年11月20日
*/ */
class Config { class Config
{
// 已加载的文件 // 已加载的文件
private static $files; private static $files;
@ -16,14 +17,17 @@ class Config {
// 保存配置的变量 // 保存配置的变量
private $config = []; private $config = [];
private function __construct() { private function __construct()
{
} }
private function __clone() { private function __clone()
{
// TODO: Implement __clone() method. // TODO: Implement __clone() method.
} }
public static function instance() { public static function instance()
{
if (!self::$instance) { if (!self::$instance) {
self::$instance = new self(); self::$instance = new self();
} }
@ -33,10 +37,11 @@ class Config {
/** /**
* 添加配置 * 添加配置
* *
* @param string $name * @param string $name
* @param string $value * @param string $value
*/ */
public function set($name, $value) { public function set($name, $value)
{
// 组合为数组 // 组合为数组
$config = [ $config = [
$name => $value $name => $value
@ -52,11 +57,12 @@ class Config {
* @return array|mixed * @return array|mixed
* @throws \Exception * @throws \Exception
*/ */
public function get($name = '') { public function get($name = '')
{
// 加载文件 // 加载文件
$module = Register::get('Router')->module; $module = Register::get('Router')->module;
$file = APP_PATH . $module . '/config/config.php'; $file = APP_PATH . $module . '/config/config.php';
if (! isset(self::$files[$file])) { if (!isset(self::$files[$file])) {
if (file_exists($file)) { if (file_exists($file)) {
$config = require $file; $config = require $file;
// 与原有的配置项合并 // 与原有的配置项合并
@ -66,10 +72,10 @@ class Config {
} }
if (empty($this->config) if (empty($this->config)
|| ! isset($this->config) || !isset($this->config)
|| ! $this->config || !$this->config
|| ! isset($this->config[$name]) || !isset($this->config[$name])
|| ! $this->config[$name] || !$this->config[$name]
) { ) {
return []; return [];
} }
@ -79,10 +85,10 @@ class Config {
/** /**
* 从配置中删除某项 * 从配置中删除某项
* * @param string $name
* @param string $name
*/ */
public function _unset($name) { public function _unset($name)
{
unset($this->config[$name]); unset($this->config[$name]);
} }
} }

View File

@ -4,12 +4,14 @@ namespace top\library;
/** /**
* 基础控制器 * 基础控制器
*
* @author topnuomi 2018年11月23日 * @author topnuomi 2018年11月23日
*/ */
abstract class Controller { abstract class Controller
{
public function __construct() {} public function __construct()
{
}
/** /**
* 输出JSON数据 * 输出JSON数据
@ -19,7 +21,8 @@ abstract class Controller {
* @param array $ext * @param array $ext
* @return false|string * @return false|string
*/ */
protected function json($msg, $code = 1, $data = [], $ext = []) { protected function json($msg, $code = 1, $data = [], $ext = [])
{
$array = [ $array = [
'msg' => $msg, 'msg' => $msg,
'code' => $code, 'code' => $code,
@ -34,7 +37,8 @@ abstract class Controller {
* @param bool $status * @param bool $status
* @return $this * @return $this
*/ */
protected function cache($status = true) { protected function cache($status = true)
{
Register::get('View')->cache($status); Register::get('View')->cache($status);
return $this; return $this;
} }
@ -44,7 +48,8 @@ abstract class Controller {
* @param $name * @param $name
* @param $value * @param $value
*/ */
protected function param($name, $value) { protected function param($name, $value)
{
Register::get('View')->param($name, $value); Register::get('View')->param($name, $value);
} }
@ -55,7 +60,8 @@ abstract class Controller {
* @param bool $cache * @param bool $cache
* @return mixed * @return mixed
*/ */
protected function fetch($file = '', $param = [], $cache = false) { protected function fetch($file = '', $param = [], $cache = false)
{
return Register::get('View')->fetch($file, $param, $cache); return Register::get('View')->fetch($file, $param, $cache);
} }
@ -63,7 +69,8 @@ abstract class Controller {
* 跳转非ajax * 跳转非ajax
* @param $url * @param $url
*/ */
protected function redirect($url) { protected function redirect($url)
{
return redirect($url); return redirect($url);
} }
@ -74,7 +81,8 @@ abstract class Controller {
* @param int $sec * @param int $sec
* @return false|mixed|string * @return false|mixed|string
*/ */
protected function tips($message, $url = '', $sec = 3) { protected function tips($message, $url = '', $sec = 3)
{
if (request()->isAjax()) { if (request()->isAjax()) {
return $this->json($message, '', 'tips', ['url' => $url, 'sec' => $sec]); return $this->json($message, '', 'tips', ['url' => $url, 'sec' => $sec]);
} else { } else {
@ -88,4 +96,4 @@ abstract class Controller {
]); ]);
} }
} }
} }

View File

@ -6,10 +6,10 @@ use top\library\database\ifs\DatabaseIfs;
/** /**
* 数据库操作类 * 数据库操作类
*
* @author topnuomi 2018年11月21日 * @author topnuomi 2018年11月21日
*/ */
class Database { class Database
{
// 数据库驱动 // 数据库驱动
private static $driver; private static $driver;
@ -59,7 +59,8 @@ class Database {
* @param $table * @param $table
* @param $pk * @param $pk
*/ */
private function __construct($table, $pk) { private function __construct($table, $pk)
{
$driver = Register::get('DBDriver'); $driver = Register::get('DBDriver');
$this->config = $config = Register::get('Config')->get('db'); $this->config = $config = Register::get('Config')->get('db');
$this->table = $config['prefix'] . $table; $this->table = $config['prefix'] . $table;
@ -67,7 +68,8 @@ class Database {
$this->setDriver($driver, $this->config); $this->setDriver($driver, $this->config);
} }
private function __clone() { private function __clone()
{
// TODO: Implement __clone() method. // TODO: Implement __clone() method.
} }
@ -77,7 +79,8 @@ class Database {
* @param DatabaseIfs $driver * @param DatabaseIfs $driver
* @param array $config * @param array $config
*/ */
private function setDriver(DatabaseIfs $driver, $config) { private function setDriver(DatabaseIfs $driver, $config)
{
self::$driver = $driver->connect($config); self::$driver = $driver->connect($config);
} }
@ -87,7 +90,8 @@ class Database {
* @param string $pk * @param string $pk
* @return mixed * @return mixed
*/ */
public static function table($table, $pk = '') { public static function table($table, $pk = '')
{
if (!isset(self::$instance[$table])) { if (!isset(self::$instance[$table])) {
self::$instance[$table] = new self($table, $pk); self::$instance[$table] = new self($table, $pk);
} }
@ -99,7 +103,8 @@ class Database {
* @param $effect * @param $effect
* @return \top\library\Database * @return \top\library\Database
*/ */
public function effect($effect) { public function effect($effect)
{
$this->effect = $effect; $this->effect = $effect;
return $this; return $this;
} }
@ -108,7 +113,8 @@ class Database {
* @param $field * @param $field
* @return \top\library\Database * @return \top\library\Database
*/ */
public function distinct($field) { public function distinct($field)
{
$this->distinct = $field; $this->distinct = $field;
return $this; return $this;
} }
@ -118,7 +124,8 @@ class Database {
* @param $field * @param $field
* @return \top\library\Database * @return \top\library\Database
*/ */
public function field($field) { public function field($field)
{
$this->field = $field; $this->field = $field;
return $this; return $this;
} }
@ -127,7 +134,8 @@ class Database {
* 设置条件 * 设置条件
* @return \top\library\Database * @return \top\library\Database
*/ */
public function where() { public function where()
{
$where = func_get_args(); $where = func_get_args();
if (!empty($where)) { if (!empty($where)) {
switch (count($where)) { switch (count($where)) {
@ -156,7 +164,8 @@ class Database {
* 设置排序 * 设置排序
* @return \top\library\Database * @return \top\library\Database
*/ */
public function order() { public function order()
{
$order = func_get_args(); $order = func_get_args();
if (!empty($order)) { if (!empty($order)) {
if (count($order) > 1) { if (count($order) > 1) {
@ -172,7 +181,8 @@ class Database {
* 设置记录范围 * 设置记录范围
* @return \top\library\Database * @return \top\library\Database
*/ */
public function limit() { public function limit()
{
$limit = func_get_args(); $limit = func_get_args();
if (!empty($limit)) { if (!empty($limit)) {
if (count($limit) > 1) { if (count($limit) > 1) {
@ -192,7 +202,8 @@ class Database {
* @param string $name * @param string $name
* @return \top\library\Database * @return \top\library\Database
*/ */
public function join($type, $table, $name) { public function join($type, $table, $name)
{
$this->join[] = [ $this->join[] = [
$type, $type,
$this->config['prefix'] . $table, $this->config['prefix'] . $table,
@ -206,7 +217,8 @@ class Database {
* @param string $on * @param string $on
* @return \top\library\Database * @return \top\library\Database
*/ */
public function on($on) { public function on($on)
{
$this->on[] = $on; $this->on[] = $on;
return $this; return $this;
} }
@ -217,7 +229,8 @@ class Database {
* @param array $data * @param array $data
* @return int|boolean * @return int|boolean
*/ */
public function insert($data) { public function insert($data)
{
$result = self::$driver->insert($this->table, $data); $result = self::$driver->insert($this->table, $data);
return $result; return $result;
} }
@ -227,7 +240,8 @@ class Database {
* @param bool $param * @param bool $param
* @return object * @return object
*/ */
public function find($param = false) { public function find($param = false)
{
if (is_callable($param)) if (is_callable($param))
$param($this); $param($this);
$field = $this->getPk(); $field = $this->getPk();
@ -248,7 +262,8 @@ class Database {
* @param callable|string|bool $param * @param callable|string|bool $param
* @return array|boolean * @return array|boolean
*/ */
public function select($param = false) { public function select($param = false)
{
if (is_callable($param)) if (is_callable($param))
$param($this); $param($this);
$field = $this->getPk(); $field = $this->getPk();
@ -272,7 +287,8 @@ class Database {
* @param callable|string|bool $param * @param callable|string|bool $param
* @return int|boolean * @return int|boolean
*/ */
public function update($data, $param = false) { public function update($data, $param = false)
{
if (is_callable($param)) if (is_callable($param))
$param($this); $param($this);
$field = $this->getPk(); $field = $this->getPk();
@ -293,7 +309,8 @@ class Database {
* @param callable|string|bool $param * @param callable|string|bool $param
* @return int|boolean * @return int|boolean
*/ */
public function delete($param = false) { public function delete($param = false)
{
if (is_callable($param)) { if (is_callable($param)) {
$param($this); $param($this);
} }
@ -318,7 +335,8 @@ class Database {
* @param $type * @param $type
* @return mixed * @return mixed
*/ */
public function common($param, $type) { public function common($param, $type)
{
if (is_callable($param)) { if (is_callable($param)) {
$param($this); $param($this);
} }
@ -340,7 +358,8 @@ class Database {
* @param string $table * @param string $table
* @return mixed * @return mixed
*/ */
public function tableDesc($table = '') { public function tableDesc($table = '')
{
$table = ($table) ? $table : $this->table; $table = ($table) ? $table : $this->table;
if (!isset(self::$tableDesc[$table])) { if (!isset(self::$tableDesc[$table])) {
self::$tableDesc[$table] = self::$driver->tableDesc($table); self::$tableDesc[$table] = self::$driver->tableDesc($table);
@ -355,7 +374,8 @@ class Database {
* @param string $query * @param string $query
* @return resource|bool * @return resource|bool
*/ */
public function query($query) { public function query($query)
{
$result = self::$driver->query($query); $result = self::$driver->query($query);
return $result; return $result;
} }
@ -365,14 +385,16 @@ class Database {
* *
* @return string * @return string
*/ */
public function _sql() { public function _sql()
{
return self::$driver->sql(); return self::$driver->sql();
} }
/** /**
* 重置查询条件 * 重置查询条件
*/ */
private function _reset() { private function _reset()
{
$this->effect = ''; $this->effect = '';
$this->distinct = ''; $this->distinct = '';
$this->field = ''; $this->field = '';
@ -389,7 +411,8 @@ class Database {
* *
* @return string * @return string
*/ */
private function getPk() { private function getPk()
{
if (!$this->pk) { if (!$this->pk) {
$tableInfo = $this->tableDesc(); $tableInfo = $this->tableDesc();
$pk = ''; $pk = '';
@ -403,4 +426,4 @@ class Database {
} }
return $this->pk; return $this->pk;
} }
} }

View File

@ -2,15 +2,26 @@
namespace top\library; namespace top\library;
class Loader { class Loader
{
private $prefixes = []; private $prefixes = [];
public function register() { /**
* 注册自动加载
*/
public function register()
{
spl_autoload_register([$this, 'loadClass']); spl_autoload_register([$this, 'loadClass']);
} }
public function set($name, $path) { /**
* 添加命名空间映射
* @param $name
* @param $path
*/
public function set($name, $path)
{
if (isset($this->prefixes[$name])) { if (isset($this->prefixes[$name])) {
array_push($this->prefixes[$name], $path); array_push($this->prefixes[$name], $path);
} else { } else {
@ -18,7 +29,13 @@ class Loader {
} }
} }
private function loadClass($class) { /**
* 尝试根据前缀和类名加载文件
* @param $class
* @return bool
*/
private function loadClass($class)
{
// 首次,将前缀等于当前类名 // 首次,将前缀等于当前类名
$prefix = $class; $prefix = $class;
// 从最后一个反斜杠开始分割前缀与类名 // 从最后一个反斜杠开始分割前缀与类名
@ -38,7 +55,14 @@ class Loader {
return false; return false;
} }
private function loadFile($prefix, $class) { /**
* 加载文件
* @param $prefix
* @param $class
* @return bool
*/
private function loadFile($prefix, $class)
{
// echo $class . '<br>'; // echo $class . '<br>';
$prefix = trim($prefix, '\\'); $prefix = trim($prefix, '\\');
// 如果存在此前缀 // 如果存在此前缀
@ -58,4 +82,4 @@ class Loader {
} }
return false; return false;
} }
} }

View File

@ -2,13 +2,12 @@
namespace top\library; namespace top\library;
/** /**
* 基础模型 * 基础模型
*
* @author topnuomi 2018年11月23日 * @author topnuomi 2018年11月23日
*/ */
class Model { class Model
{
// 数据库操作实例 // 数据库操作实例
private $db; private $db;
@ -47,7 +46,8 @@ class Model {
* Model constructor. * Model constructor.
* @param string $table * @param string $table
*/ */
public function __construct($table = '') { public function __construct($table = '')
{
if ($table) { if ($table) {
$this->table = $table; $this->table = $table;
} else if (!$this->table) { } else if (!$this->table) {
@ -62,7 +62,8 @@ class Model {
* @param $effect * @param $effect
* @return $this * @return $this
*/ */
public function effect($effect) { public function effect($effect)
{
$this->db->effect($effect); $this->db->effect($effect);
return $this; return $this;
} }
@ -72,7 +73,8 @@ class Model {
* @param $field * @param $field
* @return $this * @return $this
*/ */
public function distinct($field) { public function distinct($field)
{
$this->db->distinct($field); $this->db->distinct($field);
return $this; return $this;
} }
@ -82,7 +84,8 @@ class Model {
* @param $field * @param $field
* @return $this * @return $this
*/ */
public function field($field) { public function field($field)
{
$this->db->field($field); $this->db->field($field);
return $this; return $this;
} }
@ -91,7 +94,8 @@ class Model {
* 查询条件 * 查询条件
* @return $this * @return $this
*/ */
public function where() { public function where()
{
call_user_func_array([ call_user_func_array([
$this->db, $this->db,
'where' 'where'
@ -103,7 +107,8 @@ class Model {
* 排序 * 排序
* @return $this * @return $this
*/ */
public function order() { public function order()
{
call_user_func_array([ call_user_func_array([
$this->db, $this->db,
'order' 'order'
@ -115,7 +120,8 @@ class Model {
* 限制 * 限制
* @return $this * @return $this
*/ */
public function limit() { public function limit()
{
call_user_func_array([ call_user_func_array([
$this->db, $this->db,
'limit' 'limit'
@ -130,7 +136,8 @@ class Model {
* @param $name * @param $name
* @return $this * @return $this
*/ */
public function join($type, $table, $name) { public function join($type, $table, $name)
{
$this->db->join($type, $table, $name); $this->db->join($type, $table, $name);
return $this; return $this;
} }
@ -140,7 +147,8 @@ class Model {
* @param $on * @param $on
* @return $this * @return $this
*/ */
public function on($on) { public function on($on)
{
$this->db->on($on); $this->db->on($on);
return $this; return $this;
} }
@ -150,7 +158,8 @@ class Model {
* @param array $data * @param array $data
* @return bool * @return bool
*/ */
public function insert($data = []) { public function insert($data = [])
{
$this->isInsert = true; $this->isInsert = true;
$data = $this->processData($data); $data = $this->processData($data);
if ($data) { if ($data) {
@ -167,7 +176,8 @@ class Model {
* @param string|bool $param * @param string|bool $param
* @return number|boolean * @return number|boolean
*/ */
public function delete($param = false) { public function delete($param = false)
{
return $this->db->delete($param); return $this->db->delete($param);
} }
@ -177,7 +187,8 @@ class Model {
* @param string|bool $param * @param string|bool $param
* @return bool * @return bool
*/ */
public function update($data, $param = false) { public function update($data, $param = false)
{
$this->isInsert = false; $this->isInsert = false;
$data = $this->processData($data); $data = $this->processData($data);
if ($data) { if ($data) {
@ -195,7 +206,8 @@ class Model {
* @param bool $notRaw * @param bool $notRaw
* @return array * @return array
*/ */
public function find($param = false, $notRaw = true) { public function find($param = false, $notRaw = true)
{
$result = $this->db->find($param); $result = $this->db->find($param);
if ($notRaw) { if ($notRaw) {
if (is_array($result)) { if (is_array($result)) {
@ -211,7 +223,8 @@ class Model {
* @param bool $notRaw * @param bool $notRaw
* @return array * @return array
*/ */
public function select($param = false, $notRaw = true) { public function select($param = false, $notRaw = true)
{
$result = $this->db->select($param); $result = $this->db->select($param);
if ($notRaw) { if ($notRaw) {
if (is_array($result)) { if (is_array($result)) {
@ -226,7 +239,8 @@ class Model {
* @param string $param * @param string $param
* @return mixed * @return mixed
*/ */
public function count($param = '') { public function count($param = '')
{
return $this->db->common($param, 'count'); return $this->db->common($param, 'count');
} }
@ -235,7 +249,8 @@ class Model {
* @param string $param * @param string $param
* @return mixed * @return mixed
*/ */
public function avg($param = '') { public function avg($param = '')
{
return $this->db->common($param, 'avg'); return $this->db->common($param, 'avg');
} }
@ -244,7 +259,8 @@ class Model {
* @param string $param * @param string $param
* @return mixed * @return mixed
*/ */
public function max($param = '') { public function max($param = '')
{
return $this->db->common($param, 'max'); return $this->db->common($param, 'max');
} }
@ -253,7 +269,8 @@ class Model {
* @param string $param * @param string $param
* @return mixed * @return mixed
*/ */
public function min($param = '') { public function min($param = '')
{
return $this->db->common($param, 'min'); return $this->db->common($param, 'min');
} }
@ -262,7 +279,8 @@ class Model {
* @param string $param * @param string $param
* @return mixed * @return mixed
*/ */
public function sum($param = '') { public function sum($param = '')
{
return $this->db->common($param, 'sum'); return $this->db->common($param, 'sum');
} }
@ -271,7 +289,8 @@ class Model {
* @param $query * @param $query
* @return mixed * @return mixed
*/ */
public function query($query) { public function query($query)
{
return $this->db->query($query); return $this->db->query($query);
} }
@ -280,7 +299,8 @@ class Model {
* *
* @return string * @return string
*/ */
public function _sql() { public function _sql()
{
return $this->db->_sql(); return $this->db->_sql();
} }
@ -290,7 +310,8 @@ class Model {
* @param bool $notRaw * @param bool $notRaw
* @return array|bool * @return array|bool
*/ */
public function data($data = [], $notRaw = true) { public function data($data = [], $notRaw = true)
{
$mapData = $this->processMapped($data); $mapData = $this->processMapped($data);
if ($mapData) { // 如果正确处理字段映射并且数据验证通过 if ($mapData) { // 如果正确处理字段映射并且数据验证通过
if (!$notRaw) { if (!$notRaw) {
@ -318,7 +339,8 @@ class Model {
* @param array $data * @param array $data
* @return array|bool * @return array|bool
*/ */
private function processMapped($data = []) { private function processMapped($data = [])
{
$data = (empty($data)) ? $_POST : $data; $data = (empty($data)) ? $_POST : $data;
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
foreach ($this->map as $k => $v) { foreach ($this->map as $k => $v) {
@ -340,7 +362,8 @@ class Model {
* @param $data * @param $data
* @return array|bool * @return array|bool
*/ */
private function processData($data) { private function processData($data)
{
if (is_callable($data)) { if (is_callable($data)) {
// 如果$data是匿名函数则处理$this->data()处理post的数据 // 如果$data是匿名函数则处理$this->data()处理post的数据
$modelData = $this->data(); $modelData = $this->data();
@ -365,7 +388,8 @@ class Model {
* @param array $data * @param array $data
* @return array * @return array
*/ */
private function inHandle($data) { private function inHandle($data)
{
$replace = ($this->isInsert) ? $this->insertHandle : $this->updateHandle; $replace = ($this->isInsert) ? $this->insertHandle : $this->updateHandle;
foreach ($replace as $key => $value) { foreach ($replace as $key => $value) {
$fieldValue = ''; $fieldValue = '';
@ -405,7 +429,8 @@ class Model {
* @param array $data * @param array $data
* @return array * @return array
*/ */
private function outHandle($data) { private function outHandle($data)
{
foreach ($this->outHandle as $key => $value) { foreach ($this->outHandle as $key => $value) {
if (count($data) == count($data, 1)) { if (count($data) == count($data, 1)) {
if (array_key_exists($key, $data)) { if (array_key_exists($key, $data)) {
@ -431,7 +456,8 @@ class Model {
* @param $data * @param $data
* @return bool * @return bool
*/ */
private function validate($data) { private function validate($data)
{
foreach ($this->validate as $key => $value) { foreach ($this->validate as $key => $value) {
if (is_array($value)) { if (is_array($value)) {
if (count($value) == count($value, 1)) { if (count($value) == count($value, 1)) {
@ -459,7 +485,8 @@ class Model {
* @param $data * @param $data
* @return bool * @return bool
*/ */
private function validateCallUserFunction($key, $validate, $data) { private function validateCallUserFunction($key, $validate, $data)
{
$funcName = $validate[0]; $funcName = $validate[0];
$tips = end($validate); $tips = end($validate);
// 将第一个值赋值为将要检查的值 // 将第一个值赋值为将要检查的值
@ -484,7 +511,8 @@ class Model {
* @param $table * @param $table
* @return mixed * @return mixed
*/ */
public function tableDesc($table) { public function tableDesc($table)
{
return $this->db->tableDesc($table); return $this->db->tableDesc($table);
} }
@ -492,7 +520,8 @@ class Model {
* 获取信息 * 获取信息
* @return string * @return string
*/ */
public function getMessage() { public function getMessage()
{
return $this->message; return $this->message;
} }
@ -501,7 +530,8 @@ class Model {
* @param $name * @param $name
* @return array|mixed|null * @return array|mixed|null
*/ */
public function __get($name){ public function __get($name)
{
$data = null; $data = null;
switch ($name) { switch ($name) {
case 'one': case 'one':

View File

@ -4,19 +4,21 @@ namespace top\library;
/** /**
* 注册器 * 注册器
*
* @author topnuomi 2018年11月19日 * @author topnuomi 2018年11月19日
*/ */
class Register { class Register
{
// 存放类的变量 // 存放类的变量
public static $register; public static $register;
private function __construct() { private function __construct()
{
} }
private function __clone() { private function __clone()
{
// TODO: Implement __clone() method. // TODO: Implement __clone() method.
} }
@ -27,7 +29,8 @@ class Register {
* @param string $value * @param string $value
* @return boolean * @return boolean
*/ */
public static function set($name, $value) { public static function set($name, $value)
{
if (!isset(self::$register[$name])) { if (!isset(self::$register[$name])) {
self::$register[$name] = $value(); self::$register[$name] = $value();
} }
@ -41,7 +44,8 @@ class Register {
* @return mixed * @return mixed
* @throws \Exception * @throws \Exception
*/ */
public static function get($name, $param = []) { public static function get($name, $param = [])
{
if (!isset(self::$register[$name])) { if (!isset(self::$register[$name])) {
throw new \Exception($name . '尚未注册'); throw new \Exception($name . '尚未注册');
} }
@ -50,10 +54,10 @@ class Register {
/** /**
* 删除类实例 * 删除类实例
*
* @param string $name * @param string $name
*/ */
public static function _unset($name) { public static function _unset($name)
{
unset(self::$register[$name]); unset(self::$register[$name]);
} }
} }

View File

@ -11,10 +11,10 @@ use top\library\route\ifs\RouteIfs;
/** /**
* 路由类 * 路由类
*
* @author topnuomi 2018年11月19日 * @author topnuomi 2018年11月19日
*/ */
class Router { class Router
{
// 路由实例 // 路由实例
private $route; private $route;
@ -39,7 +39,8 @@ class Router {
* @param $default * @param $default
* @throws RouteException * @throws RouteException
*/ */
public function __construct(RouteIfs $route, $default) { public function __construct(RouteIfs $route, $default)
{
$this->route = $route; $this->route = $route;
$this->route->default = $default; $this->route->default = $default;
$this->route->processing(); $this->route->processing();
@ -64,14 +65,16 @@ class Router {
* 指定装饰器 * 指定装饰器
* @param DecoratorIfs $decorator * @param DecoratorIfs $decorator
*/ */
private function decorator(DecoratorIfs $decorator) { private function decorator(DecoratorIfs $decorator)
{
$this->decorator[] = $decorator; $this->decorator[] = $decorator;
} }
/** /**
* 装饰器前置方法 * 装饰器前置方法
*/ */
private function beforeRoute() { private function beforeRoute()
{
foreach ($this->decorator as $decorator) { foreach ($this->decorator as $decorator) {
$decorator->before(); $decorator->before();
} }
@ -81,7 +84,8 @@ class Router {
* 装饰器后置方法 * 装饰器后置方法
* @param $data * @param $data
*/ */
private function afterRoute($data) { private function afterRoute($data)
{
$this->decorator = array_reverse($this->decorator); $this->decorator = array_reverse($this->decorator);
foreach ($this->decorator as $decorator) { foreach ($this->decorator as $decorator) {
$decorator->after($data); $decorator->after($data);
@ -92,7 +96,8 @@ class Router {
* 执行前进行必要检查 * 执行前进行必要检查
* @throws RouteException * @throws RouteException
*/ */
private function check() { private function check()
{
// 检查模块是否存在 // 检查模块是否存在
if (!is_dir(APP_PATH . $this->module)) { if (!is_dir(APP_PATH . $this->module)) {
throw new RouteException('模块' . $this->module . '不存在'); throw new RouteException('模块' . $this->module . '不存在');
@ -110,7 +115,8 @@ class Router {
/** /**
* 调用方法并执行程序 * 调用方法并执行程序
*/ */
public function handler() { public function handler()
{
$userDecorators = Register::get('Config')->get('decorator'); $userDecorators = Register::get('Config')->get('decorator');
$systemDecorators = [InitDecorator::class, ReturnDecorator::class, StringDecorator::class]; $systemDecorators = [InitDecorator::class, ReturnDecorator::class, StringDecorator::class];
@ -133,4 +139,4 @@ class Router {
$this->afterRoute($data); $this->afterRoute($data);
} }
} }

View File

@ -1,14 +1,15 @@
<?php <?php
namespace top\library; namespace top\library;
use top\library\template\ifs\TemplateIfs; use top\library\template\ifs\TemplateIfs;
/** /**
* 模板类 * 模板类
*
* @author topnuomi 2018年11月22日 * @author topnuomi 2018年11月22日
*/ */
class Template { class Template
{
// 操作的具体实现 // 操作的具体实现
private $template; private $template;
@ -20,24 +21,26 @@ class Template {
/** /**
* *
* @param TemplateIfs $template * @param TemplateIfs $template
*/ */
private function __construct(TemplateIfs $template) { private function __construct(TemplateIfs $template)
{
$this->template = $template->run(); $this->template = $template->run();
} }
private function __clone() { private function __clone()
{
// TODO: Implement __clone() method. // TODO: Implement __clone() method.
} }
/** /**
* 获取实例 * 获取实例
* * @param TemplateIfs $template
* @param TemplateIfs $template
* @return \top\library\Template * @return \top\library\Template
*/ */
public static function instance($template) { public static function instance($template)
if (! self::$instance) { {
if (!self::$instance) {
self::$instance = new self($template); self::$instance = new self($template);
} }
return self::$instance; return self::$instance;
@ -47,7 +50,8 @@ class Template {
* 是否开启页面静态缓存 * 是否开启页面静态缓存
* @param $status * @param $status
*/ */
public function cache($status) { public function cache($status)
{
$this->template->cache($status); $this->template->cache($status);
} }
@ -56,7 +60,8 @@ class Template {
* @param $name * @param $name
* @param $value * @param $value
*/ */
public function param($name, $value) { public function param($name, $value)
{
$this->param[$name] = $value; $this->param[$name] = $value;
} }
@ -67,8 +72,9 @@ class Template {
* @param $cache * @param $cache
* @return mixed * @return mixed
*/ */
public function fetch($file, $param, $cache) { public function fetch($file, $param, $cache)
{
$param = array_merge($param, $this->param); $param = array_merge($param, $this->param);
return $this->template->fetch($file, $param, $cache); return $this->template->fetch($file, $param, $cache);
} }
} }

View File

@ -4,10 +4,10 @@ namespace top\library;
/** /**
* 基础视图类 * 基础视图类
*
* @author topnuomi 2018年11月22日 * @author topnuomi 2018年11月22日
*/ */
class View { class View
{
private static $instance; private static $instance;
@ -18,10 +18,12 @@ class View {
private $template; private $template;
/** /**
* 获取实例
* @return View * @return View
* @throws \Exception * @throws \Exception
*/ */
public static function instance() { public static function instance()
{
if (!self::$instance) { if (!self::$instance) {
self::$instance = new self(); self::$instance = new self();
} }
@ -32,13 +34,15 @@ class View {
* View constructor. * View constructor.
* @throws \Exception * @throws \Exception
*/ */
private function __construct() { private function __construct()
{
$this->config = Register::get('Config')->get('view'); $this->config = Register::get('Config')->get('view');
$driver = Register::get($this->config['engine']); $driver = Register::get($this->config['engine']);
$this->template = Template::instance($driver); $this->template = Template::instance($driver);
} }
private function __clone() { private function __clone()
{
// TODO: Implement __clone() method. // TODO: Implement __clone() method.
} }
@ -47,7 +51,8 @@ class View {
* @param $name * @param $name
* @param $value * @param $value
*/ */
public function param($name, $value) { public function param($name, $value)
{
$this->template->param($name, $value); $this->template->param($name, $value);
} }
@ -55,7 +60,8 @@ class View {
* 页面静态缓存,直接调用默认为开启 * 页面静态缓存,直接调用默认为开启
* @param bool $status * @param bool $status
*/ */
public function cache($status = true) { public function cache($status = true)
{
$this->template->cache($status); $this->template->cache($status);
} }
@ -67,11 +73,12 @@ class View {
* @return mixed * @return mixed
* @throws \Exception * @throws \Exception
*/ */
public function fetch($file = '', $param = [], $cache = false) { public function fetch($file = '', $param = [], $cache = false)
{
if (!$file) { if (!$file) {
$route = Register::get('Router'); $route = Register::get('Router');
$file = $route->ctrl . '/' . $route->action; $file = $route->ctrl . '/' . $route->action;
} }
return $this->template->fetch($file, $param, $cache); return $this->template->fetch($file, $param, $cache);
} }
} }

View File

@ -1,36 +1,42 @@
<?php <?php
namespace top\library\cache; namespace top\library\cache;
use top\library\cache\ifs\CacheIfs; use top\library\cache\ifs\CacheIfs;
class File implements CacheIfs { class File implements CacheIfs
{
private static $instance; private static $instance;
public static function instance() { public static function instance()
if (! self::$instance) { {
if (!self::$instance) {
self::$instance = new self(); self::$instance = new self();
} }
return self::$instance; return self::$instance;
} }
private function __construct() {} private function __construct()
{
}
private function __clone() { private function __clone()
{
} }
/** /**
* * 设置缓存
* {@inheritdoc} * {@inheritdoc}
*
* @see \top\library\cache\CacheIfs::set() * @see \top\library\cache\CacheIfs::set()
*/ */
public function set($name = '', $value = '') { public function set($name = '', $value = '')
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
$dirArray = explode('/', $name); $dirArray = explode('/', $name);
unset($dirArray[count($dirArray) - 1]); unset($dirArray[count($dirArray) - 1]);
$dir = implode('/', $dirArray); $dir = implode('/', $dirArray);
if (! is_dir($dir)) { if (!is_dir($dir)) {
mkdir($dir, 775, true); mkdir($dir, 775, true);
} }
if (file_put_contents($name, $value) !== false) { if (file_put_contents($name, $value) !== false) {
@ -40,26 +46,33 @@ class File implements CacheIfs {
} }
/** /**
* * 获取缓存
* {@inheritdoc} * {@inheritdoc}
*
* @see \top\library\cache\CacheIfs::get() * @see \top\library\cache\CacheIfs::get()
*/ */
public function get($name = '') { public function get($name = '')
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
/** /**
* * 删除缓存
* {@inheritdoc} * {@inheritdoc}
*
* @see \top\library\cache\CacheIfs::_unset() * @see \top\library\cache\CacheIfs::_unset()
*/ */
public function _unset($name = '') { public function _unset($name = '')
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
public function check($name = '', $time = 0) { /**
* 检测缓存
* @param string $name
* @param int $time
* @return bool
*/
public function check($name = '', $time = 0)
{
if (file_exists($name)) { if (file_exists($name)) {
$modifyTime = filemtime($name); $modifyTime = filemtime($name);
$nowTime = time(); $nowTime = time();
@ -72,4 +85,4 @@ class File implements CacheIfs {
return false; return false;
} }
} }
} }

View File

@ -1,11 +1,13 @@
<?php <?php
namespace top\library\cache\ifs; namespace top\library\cache\ifs;
interface CacheIfs { interface CacheIfs
{
public function set($name = '', $value = ''); public function set($name = '', $value = '');
public function get($name = ''); public function get($name = '');
public function _unset($name = ''); public function _unset($name = '');
} }

View File

@ -7,10 +7,10 @@ use top\library\exception\DatabaseException;
/** /**
* Mysqli数据库驱动 * Mysqli数据库驱动
*
* @author topnuomi 2018年11月20日 * @author topnuomi 2018年11月20日
*/ */
class MySQLi implements DatabaseIfs { class MySQLi implements DatabaseIfs
{
private static $instance; private static $instance;
@ -18,14 +18,16 @@ class MySQLi implements DatabaseIfs {
private $sql; private $sql;
public static function instance() { public static function instance()
{
if (!self::$instance) { if (!self::$instance) {
self::$instance = new self(); self::$instance = new self();
} }
return self::$instance; return self::$instance;
} }
private function __construct() { private function __construct()
{
} }
/** /**
@ -34,7 +36,8 @@ class MySQLi implements DatabaseIfs {
* @return $this * @return $this
* @throws \Exception * @throws \Exception
*/ */
public function connect($config) { public function connect($config)
{
$link = $this->link = @mysqli_connect($config['host'], $config['user'], $config['passwd'], $config['dbname']); $link = $this->link = @mysqli_connect($config['host'], $config['user'], $config['passwd'], $config['dbname']);
if ($link === false) { if ($link === false) {
throw new DatabaseException(mysqli_connect_error()); throw new DatabaseException(mysqli_connect_error());
@ -44,12 +47,14 @@ class MySQLi implements DatabaseIfs {
} }
/** /**
* 插入
* @param string $table * @param string $table
* @param array $data * @param array $data
* @return int|string * @return int|string
* @throws \Exception * @throws \Exception
*/ */
public function insert($table, $data) { public function insert($table, $data)
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
if (count($data) == count($data, 1)) { // 一维数组 if (count($data) == count($data, 1)) { // 一维数组
$query = 'insert into ' . $table; $query = 'insert into ' . $table;
@ -72,6 +77,7 @@ class MySQLi implements DatabaseIfs {
} }
/** /**
* 更新
* @param string $table * @param string $table
* @param array $join * @param array $join
* @param array|string $on * @param array|string $on
@ -82,7 +88,8 @@ class MySQLi implements DatabaseIfs {
* @return int * @return int
* @throws \Exception * @throws \Exception
*/ */
public function update($table, $join, $on, $where, $order, $limit, $data) { public function update($table, $join, $on, $where, $order, $limit, $data)
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
$join = $this->processJoin($join, $on); $join = $this->processJoin($join, $on);
$where = $this->processWhere($where); $where = $this->processWhere($where);
@ -104,6 +111,7 @@ class MySQLi implements DatabaseIfs {
} }
/** /**
* 查询一条记录
* @param string $table * @param string $table
* @param $distinct * @param $distinct
* @param array|string $field * @param array|string $field
@ -114,7 +122,8 @@ class MySQLi implements DatabaseIfs {
* @return array|null * @return array|null
* @throws \Exception * @throws \Exception
*/ */
public function find($table, $distinct, $field, $join, $on, $where, $order) { public function find($table, $distinct, $field, $join, $on, $where, $order)
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
$join = $this->processJoin($join, $on); $join = $this->processJoin($join, $on);
$distinct = $this->processDistinct($distinct); $distinct = $this->processDistinct($distinct);
@ -131,6 +140,7 @@ class MySQLi implements DatabaseIfs {
} }
/** /**
* 查询所有记录
* @param string $table * @param string $table
* @param $distinct * @param $distinct
* @param array|string $field * @param array|string $field
@ -142,7 +152,8 @@ class MySQLi implements DatabaseIfs {
* @return array|null * @return array|null
* @throws \Exception * @throws \Exception
*/ */
public function select($table, $distinct, $field, $join, $on, $where, $order, $limit) { public function select($table, $distinct, $field, $join, $on, $where, $order, $limit)
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
$join = $this->processJoin($join, $on); $join = $this->processJoin($join, $on);
$distinct = $this->processDistinct($distinct); $distinct = $this->processDistinct($distinct);
@ -160,6 +171,7 @@ class MySQLi implements DatabaseIfs {
} }
/** /**
* 删除
* @param array|string $effect * @param array|string $effect
* @param string $table * @param string $table
* @param array $join * @param array $join
@ -170,7 +182,8 @@ class MySQLi implements DatabaseIfs {
* @return int * @return int
* @throws \Exception * @throws \Exception
*/ */
public function delete($effect, $table, $join, $on, $where, $order, $limit) { public function delete($effect, $table, $join, $on, $where, $order, $limit)
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
$effect = $this->effect($effect); $effect = $this->effect($effect);
$join = $this->processJoin($join, $on); $join = $this->processJoin($join, $on);
@ -188,7 +201,8 @@ class MySQLi implements DatabaseIfs {
* @return array|bool|null * @return array|bool|null
* @throws \Exception * @throws \Exception
*/ */
public function tableDesc($table) { public function tableDesc($table)
{
$sql = 'desc ' . $table; $sql = 'desc ' . $table;
if (!$result = $this->query($sql)) { if (!$result = $this->query($sql)) {
return false; return false;
@ -198,6 +212,7 @@ class MySQLi implements DatabaseIfs {
} }
/** /**
* 计数
* @param $table * @param $table
* @param $field * @param $field
* @param $join * @param $join
@ -206,7 +221,8 @@ class MySQLi implements DatabaseIfs {
* @return mixed * @return mixed
* @throws \Exception * @throws \Exception
*/ */
public function count($table, $field, $join, $on, $where) { public function count($table, $field, $join, $on, $where)
{
$field = $this->processField($field); $field = $this->processField($field);
$join = $this->processJoin($join, $on); $join = $this->processJoin($join, $on);
$where = $this->processWhere($where); $where = $this->processWhere($where);
@ -227,7 +243,8 @@ class MySQLi implements DatabaseIfs {
* @return bool * @return bool
* @throws \Exception * @throws \Exception
*/ */
public function common($table, $distinct, $field, $join, $on, $where, $type) { public function common($table, $distinct, $field, $join, $on, $where, $type)
{
$distinct = $this->processDistinct($distinct); $distinct = $this->processDistinct($distinct);
if ($distinct) { if ($distinct) {
$field = $distinct; $field = $distinct;
@ -252,7 +269,8 @@ class MySQLi implements DatabaseIfs {
* @return bool|\mysqli_result * @return bool|\mysqli_result
* @throws \Exception * @throws \Exception
*/ */
public function query($query) { public function query($query)
{
$result = mysqli_query($this->link, $query); $result = mysqli_query($this->link, $query);
if (!$result) if (!$result)
throw new DatabaseException(mysqli_error($this->link)); throw new DatabaseException(mysqli_error($this->link));
@ -265,11 +283,13 @@ class MySQLi implements DatabaseIfs {
* *
* @return string * @return string
*/ */
public function sql() { public function sql()
{
return trim($this->sql, ' '); return trim($this->sql, ' ');
} }
public function effect($effect) { public function effect($effect)
{
if ($effect) { if ($effect) {
if (is_array($effect)) { if (is_array($effect)) {
$effect = implode(',', $effect); $effect = implode(',', $effect);
@ -279,7 +299,8 @@ class MySQLi implements DatabaseIfs {
return ''; return '';
} }
private function processDistinct($distinct) { private function processDistinct($distinct)
{
if ($distinct) { if ($distinct) {
if (is_array($distinct)) { if (is_array($distinct)) {
$distinct = implode(',', $distinct); $distinct = implode(',', $distinct);
@ -291,11 +312,11 @@ class MySQLi implements DatabaseIfs {
/** /**
* 组合字段 * 组合字段
*
* @param string|array $field * @param string|array $field
* @return string * @return string
*/ */
private function processField($field) { private function processField($field)
{
if (!$field) { if (!$field) {
$field = '*'; $field = '*';
} else if (is_array($field)) { } else if (is_array($field)) {
@ -306,12 +327,12 @@ class MySQLi implements DatabaseIfs {
/** /**
* 组合where条件 * 组合where条件
*
* @param array $array * @param array $array
* @param string $glue * @param string $glue
* @return string * @return string
*/ */
private function processWhere(array $array, $glue = 'and') { private function processWhere(array $array, $glue = 'and')
{
$where = []; $where = [];
foreach ($array as $value) { foreach ($array as $value) {
if (empty($value)) continue; if (empty($value)) continue;
@ -351,11 +372,11 @@ class MySQLi implements DatabaseIfs {
/** /**
* 组合order * 组合order
*
* @param string $order * @param string $order
* @return string * @return string
*/ */
private function processOrder($order = '') { private function processOrder($order = '')
{
if ($order) { if ($order) {
$order = ' order by ' . $order; $order = ' order by ' . $order;
} }
@ -364,11 +385,11 @@ class MySQLi implements DatabaseIfs {
/** /**
* 组合limit * 组合limit
*
* @param string $limit * @param string $limit
* @return string * @return string
*/ */
private function processLimit($limit = '') { private function processLimit($limit = '')
{
if ($limit) { if ($limit) {
if (is_array($limit)) { if (is_array($limit)) {
$limit = ' limit ' . implode(',', $limit); $limit = ' limit ' . implode(',', $limit);
@ -381,12 +402,12 @@ class MySQLi implements DatabaseIfs {
/** /**
* 链接多表join on * 链接多表join on
*
* @param array $data * @param array $data
* @param string|array $on * @param string|array $on
* @return string * @return string
*/ */
private function processJoin($data, $on) { private function processJoin($data, $on)
{
$join = []; $join = [];
for ($i = 0; $i < count($data); $i++) { for ($i = 0; $i < count($data); $i++) {
if (is_array($on[$i])) { if (is_array($on[$i])) {
@ -408,11 +429,11 @@ class MySQLi implements DatabaseIfs {
/** /**
* 检查并处理空值 * 检查并处理空值
* * @param $value
* @param array|string $array * @return array|string
* @return array
*/ */
private function checkNull($value) { private function checkNull($value)
{
if (is_array($value)) { if (is_array($value)) {
foreach ($value as $k => $v) { foreach ($value as $k => $v) {
if (!is_numeric($v) && !$v) { if (!is_numeric($v) && !$v) {
@ -431,7 +452,8 @@ class MySQLi implements DatabaseIfs {
return $value; return $value;
} }
private function writeLogs($result, $query) { private function writeLogs($result, $query)
{
if (DEBUG) { if (DEBUG) {
$error = ''; $error = '';
if (!$result) { if (!$result) {
@ -448,7 +470,8 @@ EOF;
/** /**
* 关闭数据库连接 * 关闭数据库连接
*/ */
public function close() { public function close()
{
if ($this->link) { if ($this->link) {
if (mysqli_close($this->link)) { if (mysqli_close($this->link)) {
return true; return true;
@ -460,7 +483,8 @@ EOF;
/** /**
*/ */
public function __destruct() { public function __destruct()
{
$this->close(); $this->close();
} }
} }

View File

@ -1,83 +1,77 @@
<?php <?php
namespace top\library\database\ifs; namespace top\library\database\ifs;
/** /**
* 数据库操作接口 * 数据库操作接口
*
* @author topnuomi 2018年11月19日 * @author topnuomi 2018年11月19日
*/ */
interface DatabaseIfs { interface DatabaseIfs
{
/** /**
* 连接数据库 * 连接数据库
* * @param array $config
* @param array $config
*/ */
public function connect($config); public function connect($config);
/** /**
* 插入记录 * 插入记录
* * @param string $table
* @param string $table * @param array $data
* @param array $data
*/ */
public function insert($table, $data); public function insert($table, $data);
/** /**
* 更新记录 * 更新记录
* * @param string $table
* @param string $table * @param array $join
* @param array $join * @param string|array $on
* @param string|array $on * @param string|array $where
* @param string|array $where * @param string $order
* @param string $order * @param string $limit
* @param string $limit * @param array $data
* @param array $data
*/ */
public function update($table, $join, $on, $where, $order, $limit, $data); public function update($table, $join, $on, $where, $order, $limit, $data);
/** /**
* 查找一条记录 * 查找一条记录
* * @param string $table
* @param string $table * @param string|array $field
* @param string|array $field * @param array $join
* @param array $join * @param string|array $on
* @param string|array $on * @param string|array $where
* @param string|array $where * @param string $order
* @param string $order
*/ */
public function find($table, $distinct, $field, $join, $on, $where, $order); public function find($table, $distinct, $field, $join, $on, $where, $order);
/** /**
* 查找全部 * 查找全部
* * @param string $table
* @param string $table * @param string|array $field
* @param string|array $field * @param array $join
* @param array $join * @param string|array $on
* @param string|array $on * @param string|array $where
* @param string|array $where * @param string $order
* @param string $order * @param string $limit
* @param string $limit
*/ */
public function select($table, $distinct, $field, $join, $on, $where, $order, $limit); public function select($table, $distinct, $field, $join, $on, $where, $order, $limit);
/** /**
* 删除记录 * 删除记录
* * @param string|array $effect
* @param string|array $effect * @param string $table
* @param string $table * @param array $join
* @param array $join * @param string|array $on
* @param string|array $on * @param string|array $where
* @param string|array $where * @param string $order
* @param string $order * @param string $limit
* @param string $limit
*/ */
public function delete($effect, $table, $join, $on, $where, $order, $limit); public function delete($effect, $table, $join, $on, $where, $order, $limit);
/** /**
* 执行一条SQL * 执行一条SQL
* * @param string $query
* @param string $query
*/ */
public function query($query); public function query($query);
@ -85,4 +79,4 @@ interface DatabaseIfs {
* 关闭数据库连接 * 关闭数据库连接
*/ */
public function close(); public function close();
} }

View File

@ -2,12 +2,13 @@
namespace top\library\error; namespace top\library\error;
use top\library\exception\BaseException;
use Throwable; use Throwable;
class BaseError extends \Error { class BaseError extends \Error
{
public function __construct($message = "", $code = 0, Throwable $previous = null) { public function __construct($message = "", $code = 0, Throwable $previous = null)
{
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
} }
@ -16,15 +17,15 @@ class BaseError extends \Error {
* @param $errstr * @param $errstr
* @param $errfile * @param $errfile
* @param $errline * @param $errline
* @throws BaseException
*/ */
public function handler($errno, $errstr, $errfile, $errline) { public function handler($errno, $errstr, $errfile, $errline)
{
if (DEBUG) { if (DEBUG) {
$content = $errstr . '<br />' . $errfile . ' 第' . $errline . '行'; $content = $errstr . '<br />' . $errfile . ' 第' . $errline . '行';
} else { } else {
$content = $errstr; $content = $errstr;
} }
// throw new BaseException($errstr, 0, null, $errfile, $errline); // throw new BaseException($errstr, 0, null, $errfile, $errline);
echo '<p style="font-size: 12px; font-weight: 100;">'.$content.'</p>'; echo '<p style="font-size: 12px; font-weight: 100;">' . $content . '</p>';
} }
} }

View File

@ -4,9 +4,11 @@ namespace top\library\exception;
use Throwable; use Throwable;
class BaseException extends \Exception { class BaseException extends \Exception
{
public function __construct($message = "", $code = 0, Throwable $previous = null, $file = '', $line = '') { public function __construct($message = "", $code = 0, Throwable $previous = null, $file = '', $line = '')
{
if ($file) if ($file)
$this->file = $file; $this->file = $file;
if ($line) { if ($line) {
@ -15,7 +17,8 @@ class BaseException extends \Exception {
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
} }
public function syntaxHighlight($code) { public function syntaxHighlight($code)
{
$code = preg_replace('/"(.*?)"/U', '"<span style="color: #007F00">$1</span>"', $code); $code = preg_replace('/"(.*?)"/U', '"<span style="color: #007F00">$1</span>"', $code);
$code = preg_replace('/(\s)\b(.*?)((\b|\s)\()/U', '$1<span style="color: #aa0">$2</span>$3', $code); $code = preg_replace('/(\s)\b(.*?)((\b|\s)\()/U', '$1<span style="color: #aa0">$2</span>$3', $code);
$code = preg_replace('/(class)(.+)\s/', '<span style="color: #aa0;">$0</span>', $code); $code = preg_replace('/(class)(.+)\s/', '<span style="color: #aa0;">$0</span>', $code);
@ -33,7 +36,8 @@ class BaseException extends \Exception {
* @param $line * @param $line
* @return string * @return string
*/ */
private function readErrorFile($filename, $line) { private function readErrorFile($filename, $line)
{
$file = file($filename); $file = file($filename);
$totalLine = count($file); $totalLine = count($file);
$offset = 10; $offset = 10;
@ -52,7 +56,8 @@ class BaseException extends \Exception {
/** /**
* @param \Exception|null $exception * @param \Exception|null $exception
*/ */
public function handler($exception = null) { public function handler($exception = null)
{
if (DEBUG) { if (DEBUG) {
$message = htmlspecialchars($exception->getMessage()); $message = htmlspecialchars($exception->getMessage());
$file = $exception->getFile(); $file = $exception->getFile();
@ -242,7 +247,8 @@ EOF;
exit; exit;
} }
public function translateMessage($message) { public function translateMessage($message)
{
$message = str_ireplace( $message = str_ireplace(
['Undefined variable', 'Undefined offset', 'Undefined index', 'syntax error,', 'Use of undefined constant'], ['Undefined variable', 'Undefined offset', 'Undefined index', 'syntax error,', 'Use of undefined constant'],
['未定义变量', '未定义数组下标', '未定义数组索引', '语法错误:', '使用未定义常量:'], ['未定义变量', '未定义数组下标', '未定义数组索引', '语法错误:', '使用未定义常量:'],
@ -250,4 +256,4 @@ EOF;
); );
return $message; return $message;
} }
} }

View File

@ -4,17 +4,21 @@ namespace top\library\exception;
use Throwable; use Throwable;
class DatabaseException extends BaseException { class DatabaseException extends BaseException
public function __construct($message = "", $code = 0, Throwable $previous = null) { {
public function __construct($message = "", $code = 0, Throwable $previous = null)
{
$message = $this->processMessage($message); $message = $this->processMessage($message);
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
} }
public function handler($exception = null) { public function handler($exception = null)
{
parent::handler($this); // TODO: Change the autogenerated stub parent::handler($this); // TODO: Change the autogenerated stub
} }
private function processMessage($message) { private function processMessage($message)
{
$message = str_ireplace([ $message = str_ireplace([
'database', 'database',
'table', 'table',
@ -23,7 +27,7 @@ class DatabaseException extends BaseException {
'column', 'column',
'field', 'field',
'list' 'list'
],[ ], [
'数据库: ', '数据库: ',
'表', '表',
'不存在', '不存在',
@ -34,4 +38,4 @@ class DatabaseException extends BaseException {
], $message); ], $message);
return $message; return $message;
} }
} }

View File

@ -4,8 +4,10 @@ namespace top\library\exception;
use Throwable; use Throwable;
class RouteException extends BaseException { class RouteException extends BaseException
public function __construct($message = "", $code = 0, Throwable $previous = null) { {
public function __construct($message = "", $code = 0, Throwable $previous = null)
{
$message = $this->processMessage($message); $message = $this->processMessage($message);
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
} }
@ -13,17 +15,19 @@ class RouteException extends BaseException {
/** /**
* @param \Exception $exception * @param \Exception $exception
*/ */
public function handler($exception = null) { public function handler($exception = null)
{
parent::handler($this); // TODO: Change the autogenerated stub parent::handler($this); // TODO: Change the autogenerated stub
} }
private function processMessage($message) { private function processMessage($message)
{
$message = str_replace([ $message = str_replace([
'Module', 'Module',
'Controller', 'Controller',
'function', 'function',
'doesn\'t exist', 'doesn\'t exist',
],[ ], [
'模块', '模块',
'控制器', '控制器',
'方法', '方法',
@ -31,4 +35,4 @@ class RouteException extends BaseException {
], $message); ], $message);
return $message; return $message;
} }
} }

View File

@ -3,12 +3,14 @@
/** /**
* 调用请求类 * 调用请求类
*/ */
function request() { function request()
{
$request = \top\library\http\Request::instance(); $request = \top\library\http\Request::instance();
return $request; return $request;
} }
function model($class) { function model($class)
{
static $model = []; static $model = [];
if (!isset($model[$class])) { if (!isset($model[$class])) {
if (class_exists($class)) { if (class_exists($class)) {
@ -24,7 +26,8 @@ function model($class) {
* print_r * print_r
* @param array|string|int|object $value * @param array|string|int|object $value
*/ */
function p($value) { function p($value)
{
echo '<pre>'; echo '<pre>';
print_r($value); print_r($value);
echo '</pre>'; echo '</pre>';
@ -34,7 +37,8 @@ function p($value) {
* var_dump * var_dump
* @param array|string|int|object $value * @param array|string|int|object $value
*/ */
function v($value) { function v($value)
{
echo '<pre>'; echo '<pre>';
var_dump($value); var_dump($value);
echo '</pre>'; echo '</pre>';
@ -46,7 +50,8 @@ function v($value) {
* @param string|int $param * @param string|int $param
* @return string * @return string
*/ */
function u($url, $param = '') { function u($url, $param = '')
{
if (!empty($param) || is_numeric($param)) { if (!empty($param) || is_numeric($param)) {
if (is_array($param)) { if (is_array($param)) {
$param = '/' . implode('/', $param); $param = '/' . implode('/', $param);
@ -63,7 +68,8 @@ function u($url, $param = '') {
* @param $classname * @param $classname
* @return string * @return string
*/ */
function get_table_name($classname) { function get_table_name($classname)
{
$arr = explode('\\', $classname); $arr = explode('\\', $classname);
$class = end($arr); $class = end($arr);
$arr = str_split($class); $arr = str_split($class);
@ -81,7 +87,8 @@ function get_table_name($classname) {
* 获取客户端IP * 获取客户端IP
* @return NULL|number|string * @return NULL|number|string
*/ */
function get_client_ip() { function get_client_ip()
{
return request()->ip(); return request()->ip();
} }
@ -89,7 +96,8 @@ function get_client_ip() {
* 页面跳转 * 页面跳转
* @param $url * @param $url
*/ */
function redirect($url) { function redirect($url)
{
header('location: ' . u($url)); header('location: ' . u($url));
exit; exit;
} }
@ -98,7 +106,8 @@ function redirect($url) {
* 删除目录(包括子目录) * 删除目录(包括子目录)
* @param string $dirName * @param string $dirName
*/ */
function remove_dir($dirName) { function remove_dir($dirName)
{
$handle = @opendir($dirName); $handle = @opendir($dirName);
if ($handle) { if ($handle) {
while (false !== ($item = readdir($handle))) { while (false !== ($item = readdir($handle))) {
@ -120,7 +129,8 @@ function remove_dir($dirName) {
* @param string $str * @param string $str
* @return string * @return string
*/ */
function filter($str) { function filter($str)
{
$replaceArr = array( $replaceArr = array(
"/select\b|insert\b|update\b|delete\b|drop\b|;|\"|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|dump/is" "/select\b|insert\b|update\b|delete\b|drop\b|;|\"|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|dump/is"
); );
@ -136,7 +146,8 @@ function filter($str) {
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
function session($name, $value = '') { function session($name, $value = '')
{
$config = \top\library\Register::get('Config')->get('session'); $config = \top\library\Register::get('Config')->get('session');
if (empty($config) || !$config['prefix']) { if (empty($config) || !$config['prefix']) {
$route = \top\library\Register::get('Route'); $route = \top\library\Register::get('Route');
@ -162,7 +173,8 @@ function session($name, $value = '') {
* @param $key * @param $key
* @return mixed * @return mixed
*/ */
function assoc_unique($arr, $key) { function assoc_unique($arr, $key)
{
$tmp_arr = []; $tmp_arr = [];
foreach ($arr as $k => $v) { foreach ($arr as $k => $v) {
if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在若存在返回true if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在若存在返回true
@ -184,7 +196,8 @@ function assoc_unique($arr, $key) {
* @param bool $isCut * @param bool $isCut
* @return string * @return string
*/ */
function resize_image($imgSrc, $resize_width, $resize_height, $newName = '', $isCut = false) { function resize_image($imgSrc, $resize_width, $resize_height, $newName = '', $isCut = false)
{
$im = @imagecreatefromstring(file_get_contents($imgSrc)); $im = @imagecreatefromstring(file_get_contents($imgSrc));
$exif = exif_read_data($imgSrc); $exif = exif_read_data($imgSrc);
if (!empty($exif['Orientation'])) { if (!empty($exif['Orientation'])) {
@ -245,7 +258,8 @@ function resize_image($imgSrc, $resize_width, $resize_height, $newName = '', $is
* 判断是否是移动端 * 判断是否是移动端
* @return bool * @return bool
*/ */
function is_mobile() { function is_mobile()
{
// 如果有HTTP_X_WAP_PROFILE则一定是移动设备 // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) { if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
return true; return true;
@ -315,7 +329,8 @@ function is_mobile() {
* @param string|array $value * @param string|array $value
* @return boolean * @return boolean
*/ */
function notNull($value) { function notNull($value)
{
if (is_array($value)) { if (is_array($value)) {
if (empty($value)) { if (empty($value)) {
return false; return false;
@ -334,7 +349,8 @@ function notNull($value) {
* @param $value1 * @param $value1
* @return bool * @return bool
*/ */
function notEqual($value, $value1) { function notEqual($value, $value1)
{
if ($value == $value1) { if ($value == $value1) {
return false; return false;
} }
@ -349,10 +365,11 @@ function notEqual($value, $value1) {
* @param int $max * @param int $max
* @return boolean * @return boolean
*/ */
function isBetween($value, $min, $max) { function isBetween($value, $min, $max)
{
$length = mb_strlen($value, 'utf8'); $length = mb_strlen($value, 'utf8');
if ($length < $min || $length > $max) { if ($length < $min || $length > $max) {
return false; return false;
} }
return true; return true;
} }

View File

@ -4,27 +4,30 @@ namespace top\library\http;
/** /**
* 请求类 * 请求类
*
* @author topnuomi 2018年11月23日 * @author topnuomi 2018年11月23日
*/ */
class Request { class Request
{
private $server = []; private $server = [];
private static $instance; private static $instance;
public static function instance() { public static function instance()
{
if (!self::$instance) { if (!self::$instance) {
self::$instance = new self(); self::$instance = new self();
} }
return self::$instance; return self::$instance;
} }
private function __construct() { private function __construct()
{
$this->server = (!empty($_SERVER)) ? $_SERVER : []; $this->server = (!empty($_SERVER)) ? $_SERVER : [];
} }
public function method() { public function method()
{
return (isset($this->server['REQUEST_METHOD']) && $this->server['REQUEST_METHOD'] != '') ? $this->server['REQUEST_METHOD'] : ''; return (isset($this->server['REQUEST_METHOD']) && $this->server['REQUEST_METHOD'] != '') ? $this->server['REQUEST_METHOD'] : '';
} }
@ -33,7 +36,8 @@ class Request {
* *
* @return boolean * @return boolean
*/ */
public function isPost() { public function isPost()
{
return $this->method() == 'POST'; return $this->method() == 'POST';
} }
@ -42,7 +46,8 @@ class Request {
* *
* @return boolean * @return boolean
*/ */
public function isGet() { public function isGet()
{
return $this->method() == 'GET'; return $this->method() == 'GET';
} }
@ -51,7 +56,8 @@ class Request {
* *
* @return boolean * @return boolean
*/ */
public function isPut() { public function isPut()
{
return $this->method() == 'PUT'; return $this->method() == 'PUT';
} }
@ -60,7 +66,8 @@ class Request {
* *
* @return boolean * @return boolean
*/ */
public function isDelete() { public function isDelete()
{
return $this->method() == 'DELETE'; return $this->method() == 'DELETE';
} }
@ -69,7 +76,8 @@ class Request {
* *
* @return boolean * @return boolean
*/ */
public function isHead() { public function isHead()
{
return $this->method() == 'HEAD'; return $this->method() == 'HEAD';
} }
@ -78,7 +86,8 @@ class Request {
* *
* @return boolean * @return boolean
*/ */
public function isPatch() { public function isPatch()
{
return $this->method() == 'PATCH'; return $this->method() == 'PATCH';
} }
@ -87,7 +96,8 @@ class Request {
* *
* @return boolean * @return boolean
*/ */
public function isOptions() { public function isOptions()
{
return $this->method() == 'OPTIONS'; return $this->method() == 'OPTIONS';
} }
@ -96,7 +106,8 @@ class Request {
* *
* @return boolean * @return boolean
*/ */
public function isAjax() { public function isAjax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
} }
@ -108,7 +119,8 @@ class Request {
* @param array $header * @param array $header
* @return boolean * @return boolean
*/ */
public function create($url, $data = [], $header = []) { public function create($url, $data = [], $header = [])
{
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_URL, $url);
if (!empty($data)) { if (!empty($data)) {
@ -129,12 +141,12 @@ class Request {
/** /**
* 获取客户端IP * 获取客户端IP
* * @param int $type
* @param number $type * @param bool $client
* @param string $client * @return mixed
* @return NULL|string|number
*/ */
public function ip($type = 0, $client = true) { public function ip($type = 0, $client = true)
{
$type = $type ? 1 : 0; $type = $type ? 1 : 0;
static $ip = NULL; static $ip = NULL;
if ($ip !== NULL) if ($ip !== NULL)
@ -165,17 +177,20 @@ class Request {
return $ip[$type]; return $ip[$type];
} }
public function post($name) { public function post($name)
{
$data = (isset($_POST[$name])) ? $_POST[$name] : ''; $data = (isset($_POST[$name])) ? $_POST[$name] : '';
return $this->checkData($data); return $this->checkData($data);
} }
public function get($name) { public function get($name)
{
$data = (isset($_GET[$name])) ? $_GET[$name] : ''; $data = (isset($_GET[$name])) ? $_GET[$name] : '';
return $this->checkData($data); return $this->checkData($data);
} }
public function checkData($data) { public function checkData($data)
{
if (is_array($data)) { if (is_array($data)) {
foreach ($data as $k => $v) foreach ($data as $k => $v)
$data[$k] = filter($v); $data[$k] = filter($v);
@ -185,6 +200,7 @@ class Request {
return $data; return $data;
} }
public function __destruct() { public function __destruct()
{
} }
} }

View File

@ -4,7 +4,8 @@ namespace top\library\route;
use top\library\route\ifs\RouteIfs; use top\library\route\ifs\RouteIfs;
class Command implements RouteIfs { class Command implements RouteIfs
{
// 模块 // 模块
public $module = ''; public $module = '';
@ -24,7 +25,8 @@ class Command implements RouteIfs {
/** /**
* 暂时就这样吧(逃... * 暂时就这样吧(逃...
*/ */
public function processing() { public function processing()
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
$this->module = $this->module(); $this->module = $this->module();
$this->ctrl = $this->ctrl(); $this->ctrl = $this->ctrl();
@ -36,7 +38,8 @@ class Command implements RouteIfs {
/** /**
* *
*/ */
public function module() { public function module()
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
return 'home'; return 'home';
} }
@ -44,7 +47,8 @@ class Command implements RouteIfs {
/** /**
* *
*/ */
public function ctrl() { public function ctrl()
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
return 'Index'; return 'Index';
} }
@ -52,7 +56,8 @@ class Command implements RouteIfs {
/** /**
* *
*/ */
public function action() { public function action()
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
return 'index'; return 'index';
} }
@ -60,8 +65,9 @@ class Command implements RouteIfs {
/** /**
* *
*/ */
public function param() { public function param()
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
return []; return [];
} }
} }

View File

@ -6,10 +6,10 @@ use top\library\route\ifs\RouteIfs;
/** /**
* pathinfo模式 * pathinfo模式
*
* @author topnuomi 2018年11月19日 * @author topnuomi 2018年11月19日
*/ */
class Pathinfo implements RouteIfs { class Pathinfo implements RouteIfs
{
// 链接数组 // 链接数组
private $uriArray = []; private $uriArray = [];
@ -45,7 +45,8 @@ class Pathinfo implements RouteIfs {
* 模块名 * 模块名
* @return string * @return string
*/ */
public function module() { public function module()
{
if (isset($this->uriArray[0]) && $this->uriArray[0]) { if (isset($this->uriArray[0]) && $this->uriArray[0]) {
// 模块名小写 // 模块名小写
return strtolower($this->uriArray[0]); return strtolower($this->uriArray[0]);
@ -57,7 +58,8 @@ class Pathinfo implements RouteIfs {
* 控制器名 * 控制器名
* @return string * @return string
*/ */
public function ctrl() { public function ctrl()
{
if (isset($this->uriArray[1]) && $this->uriArray[1]) { if (isset($this->uriArray[1]) && $this->uriArray[1]) {
// 类名首字母大写 // 类名首字母大写
return ucfirst($this->uriArray[1]); return ucfirst($this->uriArray[1]);
@ -69,7 +71,8 @@ class Pathinfo implements RouteIfs {
* 具体执行的方法名 * 具体执行的方法名
* @return mixed|string * @return mixed|string
*/ */
public function action() { public function action()
{
if (isset($this->uriArray[2]) && $this->uriArray[2]) { if (isset($this->uriArray[2]) && $this->uriArray[2]) {
return $this->uriArray[2]; return $this->uriArray[2];
} }
@ -81,7 +84,8 @@ class Pathinfo implements RouteIfs {
* @return array * @return array
* @throws \ReflectionException * @throws \ReflectionException
*/ */
public function param() { public function param()
{
unset($this->uriArray[0]); unset($this->uriArray[0]);
unset($this->uriArray[1]); unset($this->uriArray[1]);
unset($this->uriArray[2]); unset($this->uriArray[2]);
@ -112,7 +116,8 @@ class Pathinfo implements RouteIfs {
* 处理URI * 处理URI
* @return mixed|string * @return mixed|string
*/ */
private function getUri() { private function getUri()
{
if (isset($_SERVER['PATH_INFO'])) { if (isset($_SERVER['PATH_INFO'])) {
$pathinfo = ltrim($_SERVER['PATH_INFO'], '/'); $pathinfo = ltrim($_SERVER['PATH_INFO'], '/');
$uri = ($pathinfo != '') ? $pathinfo : $this->default; $uri = ($pathinfo != '') ? $pathinfo : $this->default;
@ -157,7 +162,8 @@ class Pathinfo implements RouteIfs {
* 根据URI得到带参数的数组 * 根据URI得到带参数的数组
* @return array * @return array
*/ */
private function processUriArray() { private function processUriArray()
{
return explode('/', $this->getUri()); return explode('/', $this->getUri());
} }
@ -165,7 +171,8 @@ class Pathinfo implements RouteIfs {
* 返回解析出的数据 home/controller/index * 返回解析出的数据 home/controller/index
* @throws \ReflectionException * @throws \ReflectionException
*/ */
public function processing() { public function processing()
{
$this->uriArray = $this->processUriArray(); $this->uriArray = $this->processUriArray();
$this->module = $this->module(); $this->module = $this->module();
$this->ctrl = $this->ctrl(); $this->ctrl = $this->ctrl();
@ -174,4 +181,4 @@ class Pathinfo implements RouteIfs {
$this->param = $this->param(); $this->param = $this->param();
unset($this->uriArray); unset($this->uriArray);
} }
} }

View File

@ -1,12 +1,13 @@
<?php <?php
namespace top\library\route\ifs; namespace top\library\route\ifs;
/** /**
* 路由接口 * 路由接口
*
* @author topnuomi 2018年11月19日 * @author topnuomi 2018年11月19日
*/ */
interface RouteIfs { interface RouteIfs
{
/** /**
* 处理路由 * 处理路由
@ -32,4 +33,4 @@ interface RouteIfs {
* 解析参数 * 解析参数
*/ */
public function param(); public function param();
} }

View File

@ -46,4 +46,4 @@ class Smarty implements TemplateIfs {
$templateFile = $this->config['dir'] . $file . '.' . $this->config['ext']; $templateFile = $this->config['dir'] . $file . '.' . $this->config['ext'];
return $this->smarty->fetch($templateFile); return $this->smarty->fetch($templateFile);
} }
} }

View File

@ -8,10 +8,10 @@ use top\library\template\driver\tags\Tags;
/** /**
* 默认的视图驱动 * 默认的视图驱动
*
* @author topnuomi 2018年11月22日 * @author topnuomi 2018年11月22日
*/ */
class Top implements TemplateIfs { class Top implements TemplateIfs
{
private static $instance; private static $instance;
@ -23,7 +23,8 @@ class Top implements TemplateIfs {
private $cacheStatus = false; private $cacheStatus = false;
public static function instance() { public static function instance()
{
if (!self::$instance) { if (!self::$instance) {
self::$instance = new self(); self::$instance = new self();
} }
@ -34,14 +35,16 @@ class Top implements TemplateIfs {
* @return $this * @return $this
* @throws \Exception * @throws \Exception
*/ */
public function run() { public function run()
{
// TODO: Implement run() method. // TODO: Implement run() method.
$this->tags = Tags::instance(); $this->tags = Tags::instance();
$this->config = Register::get('Config')->get('view'); $this->config = Register::get('Config')->get('view');
return $this; return $this;
} }
private function __construct() { private function __construct()
{
} }
/** /**
@ -49,7 +52,8 @@ class Top implements TemplateIfs {
* @param $file * @param $file
* @return string * @return string
*/ */
private function processing($file) { private function processing($file)
{
$compileFileName = $this->config['compileDir'] . md5($file) . '.php'; $compileFileName = $this->config['compileDir'] . md5($file) . '.php';
if (!file_exists($compileFileName) || DEBUG === true) { if (!file_exists($compileFileName) || DEBUG === true) {
$compileFileName = $this->tags->processing($file); $compileFileName = $this->tags->processing($file);
@ -64,7 +68,8 @@ class Top implements TemplateIfs {
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
public function cacheFile($file, $param) { public function cacheFile($file, $param)
{
if (isset($_SERVER['REQUEST_URI'])) { if (isset($_SERVER['REQUEST_URI'])) {
$fileIdent = md5($_SERVER['REQUEST_URI']); $fileIdent = md5($_SERVER['REQUEST_URI']);
} else { } else {
@ -89,7 +94,8 @@ class Top implements TemplateIfs {
* 是否开启页面静态缓存 * 是否开启页面静态缓存
* @param bool $status * @param bool $status
*/ */
public function cache($status) { public function cache($status)
{
$this->cacheStatus = $status; $this->cacheStatus = $status;
} }
@ -101,7 +107,8 @@ class Top implements TemplateIfs {
* @return false|mixed|string * @return false|mixed|string
* @throws \Exception * @throws \Exception
*/ */
public function fetch($file, $param, $cache) { public function fetch($file, $param, $cache)
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
$filename = $this->config['dir'] . $file . '.' . $this->config['ext']; $filename = $this->config['dir'] . $file . '.' . $this->config['ext'];
if (file_exists($filename)) { if (file_exists($filename)) {
@ -122,4 +129,4 @@ class Top implements TemplateIfs {
throw new \Exception('视图文件 \'' . $file . '\' 不存在'); throw new \Exception('视图文件 \'' . $file . '\' 不存在');
} }
} }
} }

View File

@ -7,38 +7,45 @@ use top\library\template\ifs\TemplateIfs;
use Twig\Environment; use Twig\Environment;
use Twig\Loader\FilesystemLoader; use Twig\Loader\FilesystemLoader;
class Twig implements TemplateIfs { class Twig implements TemplateIfs
{
private static $instance; private static $instance;
private $config = []; private $config = [];
private function __construct() { private function __construct()
{
} }
private function __clone() { private function __clone()
{
// TODO: Implement __clone() method. // TODO: Implement __clone() method.
} }
public static function instance() { public static function instance()
{
if (!self::$instance) { if (!self::$instance) {
self::$instance = new self(); self::$instance = new self();
} }
return self::$instance; return self::$instance;
} }
public function run() { public function run()
{
// TODO: Implement run() method. // TODO: Implement run() method.
$this->config = Register::get('Config')->get('view'); $this->config = Register::get('Config')->get('view');
return $this; return $this;
} }
public function cache($status) { public function cache($status)
{
// TODO: Implement cache() method. // TODO: Implement cache() method.
return true; return true;
} }
public function fetch($file, $param, $cache) { public function fetch($file, $param, $cache)
{
$baseViewDir = rtrim($this->config['dir'], '/') . '/'; $baseViewDir = rtrim($this->config['dir'], '/') . '/';
$loader = new FilesystemLoader($baseViewDir); $loader = new FilesystemLoader($baseViewDir);
$loader->addPath($baseViewDir, 'base'); $loader->addPath($baseViewDir, 'base');
@ -50,4 +57,4 @@ class Twig implements TemplateIfs {
$templateFile = '@base/' . $file . '.' . $this->config['ext']; $templateFile = '@base/' . $file . '.' . $this->config['ext'];
return $template->render($templateFile, $param); return $template->render($templateFile, $param);
} }
} }

View File

@ -1,14 +1,15 @@
<?php <?php
namespace top\library\template\driver\tags; namespace top\library\template\driver\tags;
use top\library\Register; use top\library\Register;
/** /**
* 模板标签处理类 * 模板标签处理类
*
* @author topnuomi 2018年11月21日 * @author topnuomi 2018年11月21日
*/ */
class Tags { class Tags
{
public static $instance; public static $instance;
@ -58,8 +59,9 @@ class Tags {
* @return Tags * @return Tags
* @throws \Exception * @throws \Exception
*/ */
public static function instance() { public static function instance()
if (! self::$instance) { {
if (!self::$instance) {
self::$instance = new self(); self::$instance = new self();
} }
return self::$instance; return self::$instance;
@ -69,7 +71,8 @@ class Tags {
* Tags constructor. * Tags constructor.
* @throws \Exception * @throws \Exception
*/ */
private function __construct() { private function __construct()
{
$config = Register::get('Config')->get('view'); $config = Register::get('Config')->get('view');
$this->left = (isset($config['left']) && $config['left']) ? $config['left'] : '{'; $this->left = (isset($config['left']) && $config['left']) ? $config['left'] : '{';
$this->right = (isset($config['right']) && $config['right']) ? $config['right'] : '}'; $this->right = (isset($config['right']) && $config['right']) ? $config['right'] : '}';
@ -78,10 +81,10 @@ class Tags {
/** /**
* 设置模板标签 * 设置模板标签
* * @param array $array
* @param array $array
*/ */
private function setTags($array) { private function setTags($array)
{
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
$tagsInfo = explode(':', $key); $tagsInfo = explode(':', $key);
$tag = $tagsInfo[0]; $tag = $tagsInfo[0];
@ -92,7 +95,7 @@ class Tags {
$attrArr = explode(',', $tagsInfo[1]); $attrArr = explode(',', $tagsInfo[1]);
// 拼接正则表达式 // 拼接正则表达式
$processingArr = []; $processingArr = [];
for ($i = 0; $i < count($attrArr); $i ++) { for ($i = 0; $i < count($attrArr); $i++) {
$processingArr[$attrArr[$i]] = '\\' . ($i + 1); $processingArr[$attrArr[$i]] = '\\' . ($i + 1);
$tag .= '\s' . $attrArr[$i] . '="(.*?)"'; $tag .= '\s' . $attrArr[$i] . '="(.*?)"';
} }
@ -113,11 +116,11 @@ class Tags {
/** /**
* 预处理引入视图标签为了保证require进来的文件中的模板标签可用必须先进行预处理 * 预处理引入视图标签为了保证require进来的文件中的模板标签可用必须先进行预处理
* * @param string $filename
* @param string $filename
* @return string * @return string
*/ */
private function processingViewTag($filename) { private function processingViewTag($filename)
{
$tags = [ $tags = [
'view:name' => '$___view__config = \\framework\\library\\Register::get(\'Config\')->get(\'view\'); require BASEDIR . \'/\' . $___view__config[\'dir\'] . \'name\' . \'.\' . $___view__config[\'ext\'];' 'view:name' => '$___view__config = \\framework\\library\\Register::get(\'Config\')->get(\'view\'); require BASEDIR . \'/\' . $___view__config[\'dir\'] . \'name\' . \'.\' . $___view__config[\'ext\'];'
]; ];
@ -125,7 +128,7 @@ class Tags {
$content = file_get_contents($filename); $content = file_get_contents($filename);
$result = preg_replace($this->tags, $this->processing, $content); $result = preg_replace($this->tags, $this->processing, $content);
$tempFileName = $this->compileDir . md5($filename) . '_temp.php'; $tempFileName = $this->compileDir . md5($filename) . '_temp.php';
if (! is_dir($this->compileDir)) { if (!is_dir($this->compileDir)) {
mkdir($this->compileDir, 0777, true); mkdir($this->compileDir, 0777, true);
} }
// 创建临时文件 // 创建临时文件
@ -146,7 +149,8 @@ class Tags {
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
public function processing($filename) { public function processing($filename)
{
$content = $this->processingViewTag($filename); $content = $this->processingViewTag($filename);
// 加载预设模板标签 // 加载预设模板标签
$this->setTags($this->selfTags); $this->setTags($this->selfTags);
@ -158,7 +162,7 @@ class Tags {
$this->setTags($tags); $this->setTags($tags);
} }
$result = preg_replace($this->tags, $this->processing, $content); $result = preg_replace($this->tags, $this->processing, $content);
if (! is_dir($this->compileDir)) { if (!is_dir($this->compileDir)) {
mkdir($this->compileDir, 0777, true); mkdir($this->compileDir, 0777, true);
} }
// 最终过滤内容中?\>与<?php中间的内容 // 最终过滤内容中?\>与<?php中间的内容
@ -167,4 +171,4 @@ class Tags {
file_put_contents($filename, "<?php /* TOP糯米 */ (!defined('BASEDIR')) && exit(0); ?>" . $result); file_put_contents($filename, "<?php /* TOP糯米 */ (!defined('BASEDIR')) && exit(0); ?>" . $result);
return $filename; return $filename;
} }
} }

View File

@ -4,10 +4,10 @@ namespace top\library\template\ifs;
/** /**
* 模板接口 * 模板接口
*
* @author topnuomi 2018年11月22日 * @author topnuomi 2018年11月22日
*/ */
interface TemplateIfs { interface TemplateIfs
{
public function run(); public function run();
@ -21,4 +21,4 @@ interface TemplateIfs {
* @return mixed * @return mixed
*/ */
public function fetch($file, $param, $cache); public function fetch($file, $param, $cache);
} }