From 02d210268789e2688424e54ad3142a9e829980c3 Mon Sep 17 00:00:00 2001 From: printempw Date: Thu, 28 Jul 2016 12:01:00 +0800 Subject: [PATCH] abstract boot steps elegantly --- app/Services/Boot.php | 83 +++++++++++++++++++++++++++++++++++++++ app/Services/Config.php | 72 +++++++++++++++++++++++++++++++++ app/Services/Database.php | 81 +++++++++++++++++--------------------- app/Services/Schema.php | 24 +++++++++++ config/services.php | 5 ++- index.php | 73 +++++++++++----------------------- 6 files changed, 242 insertions(+), 96 deletions(-) create mode 100644 app/Services/Boot.php create mode 100644 app/Services/Config.php create mode 100644 app/Services/Schema.php diff --git a/app/Services/Boot.php b/app/Services/Boot.php new file mode 100644 index 00000000..fe2fdfb4 --- /dev/null +++ b/app/Services/Boot.php @@ -0,0 +1,83 @@ +load(); + } + } + + public static function loadServices() + { + // Set Aliases for App\Services + $services = require BASE_DIR.'/config/services.php'; + + foreach ($services as $facade => $class) { + class_alias($class, $facade); + } + } + + public static function registerErrorHandler() + { + if (!isset($_ENV)) + self::loadDotEnv(); + + if ($_ENV['APP_DEBUG'] !== "false") { + // whoops: php errors for cool kids + $whoops = new \Whoops\Run; + $handler = ($_SERVER['REQUEST_METHOD'] == "GET") ? + new \Whoops\Handler\PrettyPageHandler : new \Whoops\Handler\PlainTextHandler; + $whoops->pushHandler($handler); + $whoops->register(); + } else { + // Register custom error handler + App\Exceptions\ExceptionHandler::register(); + } + } + + public static function bootEloquent(Array $config) + { + $capsule = new Capsule; + $capsule->addConnection($config); + $capsule->setAsGlobal(); + $capsule->bootEloquent(); + } + + public static function startSession() + { + session_start(); + } + + public static function bootRouter() + { + /** + * URL ends with slash will cause many reference problems + */ + if (Http::getUri() != "/" && substr(Http::getUri(), -1) == "/") { + $url = substr(Http::getCurrentUrl(), 0, -1); + Http::redirect($url); + } + + // Require Route Config + Router::group([ + 'exceptionHandler' => 'App\Exceptions\RouterExceptionHandler' + ], function() { + require BASE_DIR.'/config/routes.php'; + }); + } + + public static function run() + { + self::bootRouter(); + // Start Route Dispatching + Router::start('App\Controllers'); + } +} diff --git a/app/Services/Config.php b/app/Services/Config.php new file mode 100644 index 00000000..57c063a4 --- /dev/null +++ b/app/Services/Config.php @@ -0,0 +1,72 @@ +connect_error) + throw new E("无法连接至 MySQL 服务器,请检查你的配置:".$conn->connect_error, $conn->connect_errno, true); + + $conn->query("SET names 'utf8'"); + return true; + } + + public static function checkTableExist(Array $config) + { + $tables = ['users', 'closets', 'players', 'textures', 'options']; + + foreach ($tables as $table_name) { + $table_name = $config['prefix'].$table_name; + if (!Schema::hasTable($table_name)) { + return false; + } + } + return true; + } + + public static function checkFolderExist() + { + if (!is_dir(BASE_DIR."/textures/")) + throw new E("根目录下未发现 `textures` 文件夹,请先运行 安装程序,或者手动放置一个。", -1, true); + + $view_config = self::getViewConfig(); + + if (!is_dir($view_config['cache_path'])) + mkdir($view_config['cache_path']); + + return true; + } + + public static function checkDotEnvExist() + { + if (!file_exists(BASE_DIR."/.env")) + exit('错误:.env 配置文件不存在'); + return true; + } + +} diff --git a/app/Services/Database.php b/app/Services/Database.php index 7ece2595..78dab7cf 100644 --- a/app/Services/Database.php +++ b/app/Services/Database.php @@ -29,51 +29,35 @@ class Database * @param string $table_name * @param array $config */ - function __construct($table_name = '', $config = null) { + function __construct($table_name = '', $config = null) + { $config = is_null($config) ? (require BASE_DIR.'/config/database.php') : $config; - $this->connection = self::checkConfig($config); + @$this->connection = new \mysqli( + $config['host'], + $config['username'], + $config['password'], + $config['database'], + $config['port'] + ); + + if ($this->connection->connect_error) + throw new E("Could not connect to MySQL database. Check your config.php:". + $this->connection->connect_error, $this->connection->connect_errno, true); + + $$this->connection->query("SET names 'utf8'"); $this->table_name = $config['prefix'].$table_name; } - /** - * Check database config - * - * @param Array $config - * @return object instance of MySQLi - */ - public static function checkConfig(Array $config) { - // use error control to hide shitty connect warnings - @$conn = new \mysqli($config['host'], $config['username'], $config['password'], $config['database'], $config['port']); - - if ($conn->connect_error) - throw new E("Could not connect to MySQL database. Check your config.php:".$conn->connect_error, $conn->connect_errno, true); - - $tables = ['users', 'closets', 'players', 'textures', 'options']; - - foreach ($tables as $table_name) { - $table_name = $config['prefix'].$table_name; - $sql = "SELECT table_name FROM `INFORMATION_SCHEMA`.`TABLES` - WHERE table_name ='$table_name' AND TABLE_SCHEMA='".$config['database']."'"; - - if ($conn->query($sql)->num_rows == 0) - throw new E("数据库内未发现 $table_name 表。请先运行 安装程序。", -1, true); - } - - if (!is_dir(BASE_DIR."/textures/")) - throw new E("根目录下未发现 `textures` 文件夹,请先运行 安装程序,或者手动放置一个。", -1, true); - - $conn->query("SET names 'utf8'"); - return $conn; - } - - public function query($sql) { + public function query($sql) + { $result = $this->connection->query($sql); if ($this->connection->error) throw new E("Database query error: ".$this->connection->error.", Statement: ".$sql, -1); return $result; } - public function fetchArray($sql) { + public function fetchArray($sql) + { return $this->query($sql)->fetch_array(); } @@ -87,7 +71,8 @@ class Database * @param boolean $dont_fetch_array, return resources if true * @return array|resources */ - public function select($key, $value, $condition = null, $table = null, $dont_fetch_array = false) { + public function select($key, $value, $condition = null, $table = null, $dont_fetch_array = false) + { $table = is_null($table) ? $this->table_name : $table; if (isset($condition['where'])) { @@ -104,11 +89,13 @@ class Database } - public function has($key, $value, $table = null) { + public function has($key, $value, $table = null) + { return ($this->getNumRows($key, $value, $table) != 0) ? true : false; } - public function insert($data, $table = null) { + public function insert($data, $table = null) + { $keys = ""; $values = ""; $table = is_null($table) ? $this->table_name : $table; @@ -127,23 +114,27 @@ class Database return $this->query($sql); } - public function update($key, $value, $condition = null, $table = null) { + public function update($key, $value, $condition = null, $table = null) + { $table = is_null($table) ? $this->table_name : $table; return $this->query("UPDATE $table SET `$key`='$value'".$this->where($condition)); } - public function delete($condition = null, $table = null) { + public function delete($condition = null, $table = null) + { $table = is_null($table) ? $this->table_name : $table; return $this->query("DELETE FROM $table".$this->where($condition)); } - public function getNumRows($key, $value, $table = null) { + public function getNumRows($key, $value, $table = null) + { $table = is_null($table) ? $this->table_name : $table; $sql = "SELECT * FROM $table WHERE $key='$value'"; return $this->query($sql)->num_rows; } - public function getRecordNum($table = null) { + public function getRecordNum($table = null) + { $table = is_null($table) ? $this->table_name : $table; $sql = "SELECT * FROM $table WHERE 1"; return $this->query($sql)->num_rows; @@ -155,7 +146,8 @@ class Database * @param array $condition, e.g. array('where'=>'username="shit"', 'limit'=>10, 'order'=>'uid') * @return string */ - private function where($condition) { + private function where($condition) + { $statement = ""; if (isset($condition['where']) && $condition['where'] != "") { $statement .= ' WHERE '.$condition['where']; @@ -169,7 +161,8 @@ class Database return $statement; } - function __destruct() { + function __destruct() + { if (!is_null($this->connection)) $this->connection->close(); } diff --git a/app/Services/Schema.php b/app/Services/Schema.php new file mode 100644 index 00000000..32aea866 --- /dev/null +++ b/app/Services/Schema.php @@ -0,0 +1,24 @@ + 'App\Services\Mail', 'Storage' => 'App\Services\Storage', 'Minecraft' => 'App\Services\Minecraft', - 'Updater' => 'App\Services\Updater' + 'Updater' => 'App\Services\Updater', + 'Config' => 'App\Services\Config', + 'Schema' => 'App\Services\Schema', + 'Boot' => 'App\Services\Boot' ]; diff --git a/index.php b/index.php index 37233bde..392f355d 100755 --- a/index.php +++ b/index.php @@ -2,67 +2,38 @@ /** * Bootstrap file of Blessing Skin Server */ -namespace App; -// BASE_DIR +// Define Base Directory define('BASE_DIR', __DIR__); -// Autoloader +// Register Composer Auto Loader require BASE_DIR.'/vendor/autoload.php'; -if (!file_exists(BASE_DIR."/.env")) - exit('错误:.env 配置文件不存在'); +// Load Aliases +App\Services\Boot::loadServices(); -// Load dotenv configuration -$dotenv = new \Dotenv\Dotenv(BASE_DIR); -$dotenv->load(); +// Load dotenv Configuration +Boot::loadDotEnv(); -define('SALT', $_ENV['SALT']); +// Register Error Handler +Boot::registerErrorHandler(); -if ($_ENV['APP_DEBUG'] !== "false") { - // whoops: php errors for cool kids - $whoops = new \Whoops\Run; - $handler = ($_SERVER['REQUEST_METHOD'] == "GET") ? - new \Whoops\Handler\PrettyPageHandler : new \Whoops\Handler\PlainTextHandler; - $whoops->pushHandler($handler); - $whoops->register(); -} else { - // register custom error handler - Exceptions\ExceptionHandler::register(); -} - -// set aliases for App\Services -$services = require BASE_DIR.'/config/services.php'; -foreach ($services as $facade => $class) { - class_alias($class, $facade); -} - -/** - * URL ends with slash will cause many reference problems - */ -if (\Http::getUri() != "/" && substr(\Http::getUri(), -1) == "/") -{ - $url = substr(\Http::getCurrentUrl(), 0, -1); - \Http::redirect($url); -} - -// Check database config -$db_config = require BASE_DIR.'/config/database.php'; -\Database::checkConfig($db_config); +$db_config = Config::getDbConfig(); // Boot Eloquent ORM -$capsule = new \Illuminate\Database\Capsule\Manager; -$capsule->addConnection($db_config); -$capsule->bootEloquent(); +if (Config::checkDbConfig($db_config)) { + Boot::bootEloquent($db_config); +} -session_start(); +// Redirect to Setup Page +if (!Config::checkTableExist($db_config)) { + Http::redirect('../setup/index.php'); +} -// require route config -\Pecee\SimpleRouter\SimpleRouter::group([ - 'exceptionHandler' => 'App\Exceptions\RouterExceptionHandler' -], function() { - require BASE_DIR.'/config/routes.php'; -}); +Config::checkFolderExist(); -// Start route dispatching -\Pecee\SimpleRouter\SimpleRouter::start('App\Controllers'); +// Start Session +Boot::startSession(); + +// Start Route Dispatching +Boot::run();