abstract boot steps elegantly

This commit is contained in:
printempw 2016-07-28 12:01:00 +08:00
parent 7e7e4a7da5
commit 02d2102687
6 changed files with 242 additions and 96 deletions

83
app/Services/Boot.php Normal file
View File

@ -0,0 +1,83 @@
<?php
namespace App\Services;
use \Illuminate\Database\Capsule\Manager as Capsule;
use \Pecee\SimpleRouter\SimpleRouter as Router;
class Boot
{
public static function loadDotEnv()
{
if (Config::checkDotEnvExist()) {
$dotenv = new \Dotenv\Dotenv(BASE_DIR);
$dotenv->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');
}
}

72
app/Services/Config.php Normal file
View File

@ -0,0 +1,72 @@
<?php
namespace App\Services;
use Illuminate\Database\Capsule\Manager as Capsule;
use App\Services\Schema;
use App\Exceptions\E;
class Config
{
public static function getDbConfig()
{
return require BASE_DIR.'/config/database.php';
}
public static function getViewConfig()
{
return require BASE_DIR."/config/view.php";
}
/**
* Check database config
*
* @param array $config
* @return \MySQLi
*/
public static function checkDbConfig(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("无法连接至 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` 文件夹,请先运行 <a href='./setup'>安装程序</a>,或者手动放置一个。", -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;
}
}

View File

@ -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 表。请先运行 <a href='./setup'>安装程序</a>。", -1, true);
}
if (!is_dir(BASE_DIR."/textures/"))
throw new E("根目录下未发现 `textures` 文件夹,请先运行 <a href='./setup'>安装程序</a>,或者手动放置一个。", -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();
}

24
app/Services/Schema.php Normal file
View File

@ -0,0 +1,24 @@
<?php
namespace App\Services;
use Illuminate\Database\Capsule\Manager as Capsule;
class Schema
{
/**
* Facade for Illuminate\Database\Schema
*
* @param string $method
* @param array $args
* @return mixed
*/
public static function __callStatic($method, $args)
{
// the instance of capusle has been set as global
$instance = Capsule::schema();
return call_user_func_array([$instance, $method], $args);
}
}

View File

@ -19,5 +19,8 @@ return [
'Mail' => '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'
];

View File

@ -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();