规范代码风格

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',
'host' => '127.0.0.1',
'user' => 'root',
'passwd' => 'root',
'dbname' => 'hongzheng',
'passwd' => '',
'dbname' => '',
'prefix' => 'cms_',
'charset' => 'utf8'
],

View File

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

View File

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

View File

@ -1,6 +1,7 @@
<?php
class Create {
class Create
{
private $name;
@ -14,7 +15,8 @@ class Create {
private $projectPath;
public function __construct($start, $namespace, $name) {
public function __construct($start, $namespace, $name)
{
$this->name = $name;
$this->dir = __DIR__ . '/';
$this->namespace = $namespace;
@ -25,7 +27,8 @@ class Create {
$this->create();
}
public function replaceContent($content) {
public function replaceContent($content)
{
return str_replace([
'{namespace}',
'{name}'
@ -35,7 +38,8 @@ class Create {
], $content);
}
public function createStartFile() {
public function createStartFile()
{
if ($this->start && !file_exists($this->start)) {
$content = file_get_contents($this->dir . 'tpl/index.tpl');
$content = $this->replaceContent($content);
@ -47,7 +51,8 @@ class Create {
return true;
}
public function createConfig() {
public function createConfig()
{
$configPath = $this->projectPath . 'config/';
$configFile = $configPath . 'config.php';
$tagsFile = $configPath . 'tags.php';
@ -71,7 +76,8 @@ class Create {
return true;
}
public function createMVC() {
public function createMVC()
{
$dirArray = [
'controller',
'model',
@ -110,7 +116,8 @@ class Create {
}
}
public function createFunctions() {
public function createFunctions()
{
$file = $this->projectPath . 'functions.php';
if (!file_exists($file)) {
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';
if (!file_exists($file)) {
if (!file_put_contents($file, "<?php \r\nreturn [];")) {
@ -128,7 +136,8 @@ class Create {
}
}
public function create() {
public function create()
{
$this->createStartFile();
$this->createConfig();
$this->createMVC();
@ -141,4 +150,4 @@ class Create {
$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~');
$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
return [
'register' => [
'Twig' => top\library\template\Twig::class,
// 'Smarty' => top\library\template\Smarty::class,
// 'Top' => top\library\template\Top::class,
'Twig' => \top\library\template\driver\Twig::class,
// 'Smarty' => \top\library\template\driver\Smarty::class,
// 'Top' => \top\library\template\driver\Top::class,
],
'decorator' => [],
'session' => [

View File

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

View File

@ -2,13 +2,37 @@
use \top\Framework;
// 是否开启DEBUG模式
define('DEBUG', true);
// APP目录
define('APP_PATH', '../application/');
// 框架目录
define('FRAMEWORK_PATH', '../framework/');
// 加载框架
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();

View File

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

View File

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

View File

@ -10,18 +10,20 @@ use top\library\Register;
*
* @author topnuomi 2018年11月22日
*/
class ReturnDecorator implements DecoratorIfs {
class ReturnDecorator implements DecoratorIfs
{
public function before() {
public function before()
{
// TODO Auto-generated method stub
}
/**
* 布尔或数组则显示视图
* @param array $data
* @throws \top\library\exception\BaseException
*/
public function after($data) {
public function after($data)
{
// TODO Auto-generated method stub
if (is_bool($data) && $data === true)
$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日
*/
class StringDecorator implements DecoratorIfs {
class StringDecorator implements DecoratorIfs
{
public function before() {
public function before()
{
// TODO Auto-generated method stub
}
@ -19,11 +20,12 @@ class StringDecorator implements DecoratorIfs {
* 字符串则直接输出
* @param array $data
*/
public function after($data) {
public function after($data)
{
// TODO Auto-generated method stub
// 如果是字符串直接echo
if (!is_array($data) && !is_bool($data) && !is_object($data)) {
echo $data;
}
}
}
}

View File

@ -1,4 +1,5 @@
<?php
namespace top\decorator\ifs;
/**
@ -6,7 +7,8 @@ namespace top\decorator\ifs;
*
* @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);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,12 +4,14 @@ namespace top\library;
/**
* 基础控制器
*
* @author topnuomi 2018年11月23日
*/
abstract class Controller {
abstract class Controller
{
public function __construct() {}
public function __construct()
{
}
/**
* 输出JSON数据
@ -19,7 +21,8 @@ abstract class Controller {
* @param array $ext
* @return false|string
*/
protected function json($msg, $code = 1, $data = [], $ext = []) {
protected function json($msg, $code = 1, $data = [], $ext = [])
{
$array = [
'msg' => $msg,
'code' => $code,
@ -34,7 +37,8 @@ abstract class Controller {
* @param bool $status
* @return $this
*/
protected function cache($status = true) {
protected function cache($status = true)
{
Register::get('View')->cache($status);
return $this;
}
@ -44,7 +48,8 @@ abstract class Controller {
* @param $name
* @param $value
*/
protected function param($name, $value) {
protected function param($name, $value)
{
Register::get('View')->param($name, $value);
}
@ -55,7 +60,8 @@ abstract class Controller {
* @param bool $cache
* @return mixed
*/
protected function fetch($file = '', $param = [], $cache = false) {
protected function fetch($file = '', $param = [], $cache = false)
{
return Register::get('View')->fetch($file, $param, $cache);
}
@ -63,7 +69,8 @@ abstract class Controller {
* 跳转非ajax
* @param $url
*/
protected function redirect($url) {
protected function redirect($url)
{
return redirect($url);
}
@ -74,7 +81,8 @@ abstract class Controller {
* @param int $sec
* @return false|mixed|string
*/
protected function tips($message, $url = '', $sec = 3) {
protected function tips($message, $url = '', $sec = 3)
{
if (request()->isAjax()) {
return $this->json($message, '', 'tips', ['url' => $url, 'sec' => $sec]);
} 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日
*/
class Database {
class Database
{
// 数据库驱动
private static $driver;
@ -59,7 +59,8 @@ class Database {
* @param $table
* @param $pk
*/
private function __construct($table, $pk) {
private function __construct($table, $pk)
{
$driver = Register::get('DBDriver');
$this->config = $config = Register::get('Config')->get('db');
$this->table = $config['prefix'] . $table;
@ -67,7 +68,8 @@ class Database {
$this->setDriver($driver, $this->config);
}
private function __clone() {
private function __clone()
{
// TODO: Implement __clone() method.
}
@ -77,7 +79,8 @@ class Database {
* @param DatabaseIfs $driver
* @param array $config
*/
private function setDriver(DatabaseIfs $driver, $config) {
private function setDriver(DatabaseIfs $driver, $config)
{
self::$driver = $driver->connect($config);
}
@ -87,7 +90,8 @@ class Database {
* @param string $pk
* @return mixed
*/
public static function table($table, $pk = '') {
public static function table($table, $pk = '')
{
if (!isset(self::$instance[$table])) {
self::$instance[$table] = new self($table, $pk);
}
@ -99,7 +103,8 @@ class Database {
* @param $effect
* @return \top\library\Database
*/
public function effect($effect) {
public function effect($effect)
{
$this->effect = $effect;
return $this;
}
@ -108,7 +113,8 @@ class Database {
* @param $field
* @return \top\library\Database
*/
public function distinct($field) {
public function distinct($field)
{
$this->distinct = $field;
return $this;
}
@ -118,7 +124,8 @@ class Database {
* @param $field
* @return \top\library\Database
*/
public function field($field) {
public function field($field)
{
$this->field = $field;
return $this;
}
@ -127,7 +134,8 @@ class Database {
* 设置条件
* @return \top\library\Database
*/
public function where() {
public function where()
{
$where = func_get_args();
if (!empty($where)) {
switch (count($where)) {
@ -156,7 +164,8 @@ class Database {
* 设置排序
* @return \top\library\Database
*/
public function order() {
public function order()
{
$order = func_get_args();
if (!empty($order)) {
if (count($order) > 1) {
@ -172,7 +181,8 @@ class Database {
* 设置记录范围
* @return \top\library\Database
*/
public function limit() {
public function limit()
{
$limit = func_get_args();
if (!empty($limit)) {
if (count($limit) > 1) {
@ -192,7 +202,8 @@ class Database {
* @param string $name
* @return \top\library\Database
*/
public function join($type, $table, $name) {
public function join($type, $table, $name)
{
$this->join[] = [
$type,
$this->config['prefix'] . $table,
@ -206,7 +217,8 @@ class Database {
* @param string $on
* @return \top\library\Database
*/
public function on($on) {
public function on($on)
{
$this->on[] = $on;
return $this;
}
@ -217,7 +229,8 @@ class Database {
* @param array $data
* @return int|boolean
*/
public function insert($data) {
public function insert($data)
{
$result = self::$driver->insert($this->table, $data);
return $result;
}
@ -227,7 +240,8 @@ class Database {
* @param bool $param
* @return object
*/
public function find($param = false) {
public function find($param = false)
{
if (is_callable($param))
$param($this);
$field = $this->getPk();
@ -248,7 +262,8 @@ class Database {
* @param callable|string|bool $param
* @return array|boolean
*/
public function select($param = false) {
public function select($param = false)
{
if (is_callable($param))
$param($this);
$field = $this->getPk();
@ -272,7 +287,8 @@ class Database {
* @param callable|string|bool $param
* @return int|boolean
*/
public function update($data, $param = false) {
public function update($data, $param = false)
{
if (is_callable($param))
$param($this);
$field = $this->getPk();
@ -293,7 +309,8 @@ class Database {
* @param callable|string|bool $param
* @return int|boolean
*/
public function delete($param = false) {
public function delete($param = false)
{
if (is_callable($param)) {
$param($this);
}
@ -318,7 +335,8 @@ class Database {
* @param $type
* @return mixed
*/
public function common($param, $type) {
public function common($param, $type)
{
if (is_callable($param)) {
$param($this);
}
@ -340,7 +358,8 @@ class Database {
* @param string $table
* @return mixed
*/
public function tableDesc($table = '') {
public function tableDesc($table = '')
{
$table = ($table) ? $table : $this->table;
if (!isset(self::$tableDesc[$table])) {
self::$tableDesc[$table] = self::$driver->tableDesc($table);
@ -355,7 +374,8 @@ class Database {
* @param string $query
* @return resource|bool
*/
public function query($query) {
public function query($query)
{
$result = self::$driver->query($query);
return $result;
}
@ -365,14 +385,16 @@ class Database {
*
* @return string
*/
public function _sql() {
public function _sql()
{
return self::$driver->sql();
}
/**
* 重置查询条件
*/
private function _reset() {
private function _reset()
{
$this->effect = '';
$this->distinct = '';
$this->field = '';
@ -389,7 +411,8 @@ class Database {
*
* @return string
*/
private function getPk() {
private function getPk()
{
if (!$this->pk) {
$tableInfo = $this->tableDesc();
$pk = '';
@ -403,4 +426,4 @@ class Database {
}
return $this->pk;
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,12 +2,13 @@
namespace top\library\error;
use top\library\exception\BaseException;
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);
}
@ -16,15 +17,15 @@ class BaseError extends \Error {
* @param $errstr
* @param $errfile
* @param $errline
* @throws BaseException
*/
public function handler($errno, $errstr, $errfile, $errline) {
public function handler($errno, $errstr, $errfile, $errline)
{
if (DEBUG) {
$content = $errstr . '<br />' . $errfile . ' 第' . $errline . '行';
} else {
$content = $errstr;
}
// 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;
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)
$this->file = $file;
if ($line) {
@ -15,7 +17,8 @@ class BaseException extends \Exception {
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('/(\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);
@ -33,7 +36,8 @@ class BaseException extends \Exception {
* @param $line
* @return string
*/
private function readErrorFile($filename, $line) {
private function readErrorFile($filename, $line)
{
$file = file($filename);
$totalLine = count($file);
$offset = 10;
@ -52,7 +56,8 @@ class BaseException extends \Exception {
/**
* @param \Exception|null $exception
*/
public function handler($exception = null) {
public function handler($exception = null)
{
if (DEBUG) {
$message = htmlspecialchars($exception->getMessage());
$file = $exception->getFile();
@ -242,7 +247,8 @@ EOF;
exit;
}
public function translateMessage($message) {
public function translateMessage($message)
{
$message = str_ireplace(
['Undefined variable', 'Undefined offset', 'Undefined index', 'syntax error,', 'Use of undefined constant'],
['未定义变量', '未定义数组下标', '未定义数组索引', '语法错误:', '使用未定义常量:'],
@ -250,4 +256,4 @@ EOF;
);
return $message;
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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