Example #1
0
 public static function getInstance()
 {
     if (!self::$instance instanceof self) {
         self::$instance = new self();
     }
     return self::$instance;
 }
Example #2
0
 public static function getInstance()
 {
     if (!isset(self::$instance)) {
         require_once PROJECT_DIR . '/config/routes.php';
         /** @var array $config */
         self::$instance = new Router($config['routes']);
     }
     return self::$instance;
 }
Example #3
0
 public static function getURI()
 {
     $fullURI = substr($_SERVER['REQUEST_URI'], strlen(\Config::$base));
     $queryPosition = strpos($fullURI, '?');
     self::$uri = $queryPosition === FALSE ? $fullURI : substr($fullURI, 0, $queryPosition);
     self::$uriParts = explode('/', trim(Router::$uri, '/'));
     self::$controller = basename(self::translate(current(self::$uriParts)));
     if (empty(self::$controller)) {
         self::$controller = \Config::$root;
     }
 }
Example #4
0
 /**
  * 实例化一个模型
  * @param type $classname_path
  * @param type $hmvc_module_floder
  * @return type CoreModel
  */
 public static function instance($classname_path = null, $hmvc_module_floder = NULL)
 {
     if (!empty($hmvc_module_floder)) {
         CoreRouter::switchHmvcConfig($hmvc_module_floder);
     }
     //这里调用控制器instance是为了触发自动加载,从而避免了插件模式下,直接instance模型,自动加载失效的问题
     CoreController::instance();
     if (empty($classname_path)) {
         $renew = is_bool($classname_path) && $classname_path === true;
         CoreLoader::classAutoloadRegister();
         return empty(self::$instance) || $renew ? self::$instance = new self() : self::$instance;
     }
     $system = CoreLoader::$system;
     $classname_path = str_replace('.', DIRECTORY_SEPARATOR, $classname_path);
     $classname = basename($classname_path);
     $model_folders = $system['model_folder'];
     if (!is_array($model_folders)) {
         $model_folders = array($model_folders);
     }
     $count = count($model_folders);
     CoreLoader::classAutoloadRegister();
     foreach ($model_folders as $key => $model_folder) {
         $filepath = $model_folder . DIRECTORY_SEPARATOR . $classname_path . $system['model_file_suffix'];
         $alias_name = $classname;
         if (isset(CoreModelLoader::$model_files[$alias_name])) {
             return CoreModelLoader::$model_files[$alias_name];
         }
         if (file_exists($filepath)) {
             //在plugin模式下,路由器不再使用,那么自动注册不会被执行,自动加载功能会失效,所以在这里再尝试加载一次,
             //如此一来就能满足两种模式
             //CoreLoader::classAutoloadRegister();
             if (!class_exists($classname, FALSE)) {
                 CoreLoader::includeOnce($filepath);
             }
             if (class_exists($classname, FALSE)) {
                 return CoreModelLoader::$model_files[$alias_name] = new $classname();
             } else {
                 if ($key == $count - 1) {
                     Fn::trigger404('Model Class:' . $classname . ' not found.');
                 }
             }
         } else {
             if ($key == $count - 1) {
                 Fn::trigger404($filepath . ' not  found.');
             }
         }
     }
 }
Example #5
0
 /**
  * Runs the callback for the given request.
  */
 public static function dispatch()
 {
     $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
     $method = $_SERVER['REQUEST_METHOD'];
     $searches = array_keys(static::$patterns);
     $replaces = array_values(static::$patterns);
     self::$routes = str_replace('//', '/', self::$routes);
     $found_route = false;
     // parse query parameters
     $query = '';
     $q_arr = array();
     if (strpos($uri, '&') > 0) {
         $query = substr($uri, strpos($uri, '&') + 1);
         $uri = substr($uri, 0, strpos($uri, '&'));
         $q_arr = explode('&', $query);
         foreach ($q_arr as $q) {
             $qobj = explode('=', $q);
             $q_arr[] = array($qobj[0] => $qobj[1]);
             if (!isset($_GET[$qobj[0]])) {
                 $_GET[$qobj[0]] = $qobj[1];
             }
         }
     }
     // check if route is defined without regex
     if (in_array($uri, self::$routes)) {
         $route_pos = array_keys(self::$routes, $uri);
         // foreach route position
         foreach ($route_pos as $route) {
             if (self::$methods[$route] == $method || self::$methods[$route] == 'ANY') {
                 $found_route = true;
                 //if route is not an object
                 if (!is_object(self::$callbacks[$route])) {
                     //call object controller and method
                     self::invokeObject(self::$callbacks[$route]);
                     if (self::$halts) {
                         return;
                     }
                 } else {
                     //call closure
                     call_user_func(self::$callbacks[$route]);
                     if (self::$halts) {
                         return;
                     }
                 }
             }
         }
         // end foreach
     } else {
         // check if defined with regex
         $pos = 0;
         // foreach routes
         foreach (self::$routes as $route) {
             $route = str_replace('//', '/', $route);
             if (strpos($route, ':') !== false) {
                 $route = str_replace($searches, $replaces, $route);
             }
             if (preg_match('#^' . $route . '$#', $uri, $matched)) {
                 if (self::$methods[$pos] == $method || self::$methods[$pos] == 'ANY') {
                     $found_route = true;
                     //remove $matched[0] as [1] is the first parameter.
                     array_shift($matched);
                     if (!is_object(self::$callbacks[$pos])) {
                         //call object controller and method
                         self::invokeObject(self::$callbacks[$pos], $matched);
                         if (self::$halts) {
                             return;
                         }
                     } else {
                         //call closure
                         call_user_func_array(self::$callbacks[$pos], $matched);
                         if (self::$halts) {
                             return;
                         }
                     }
                 }
             }
             $pos++;
         }
         // end foreach
     }
     if (self::$fallback) {
         //call the auto dispatch method
         $found_route = self::autoDispatch();
     }
     // run the error callback if the route was not found
     if (!$found_route) {
         if (!self::$errorCallback) {
             self::$errorCallback = function () {
                 header("{$_SERVER['SERVER_PROTOCOL']} 404 Not Found");
                 $data['title'] = '404';
                 $data['error'] = "Oops! Page not found.";
                 View::renderTemplate('header', $data);
                 View::render('error/404', $data);
                 View::renderTemplate('footer', $data);
             };
         }
         if (!is_object(self::$errorCallback)) {
             //call object controller and method
             self::invokeObject(self::$errorCallback, null, 'No routes found.');
             if (self::$halts) {
                 return;
             }
         } else {
             call_user_func(self::$errorCallback);
             if (self::$halts) {
                 return;
             }
         }
     }
 }
Example #6
0
$system['db']['sqlite3']['database'] = 'sqlite:d:/wwwroot/sdb.db';
$system['db']['sqlite3']['dbprefix'] = '';
$system['db']['sqlite3']['db_debug'] = TRUE;
$system['db']['sqlite3']['char_set'] = 'utf8';
$system['db']['sqlite3']['dbcollat'] = 'utf8_general_ci';
$system['db']['sqlite3']['swap_pre'] = '';
$system['db']['sqlite3']['autoinit'] = TRUE;
$system['db']['sqlite3']['stricton'] = FALSE;
/**
 * PDO mysql数据库配置示例,hostname 其实就是pdo的dsn部分,
 * 如果连接其它数据库按着pdo的dsn写法连接即可
 */
$system['db']['pdo_mysql']['dbdriver'] = 'pdo';
$system['db']['pdo_mysql']['hostname'] = 'mysql:host=localhost;port=3306';
$system['db']['pdo_mysql']['username'] = '******';
$system['db']['pdo_mysql']['password'] = '******';
$system['db']['pdo_mysql']['database'] = 'test';
$system['db']['pdo_mysql']['dbprefix'] = '';
$system['db']['pdo_mysql']['db_debug'] = TRUE;
$system['db']['pdo_mysql']['char_set'] = 'utf8';
$system['db']['pdo_mysql']['dbcollat'] = 'utf8_general_ci';
$system['db']['pdo_mysql']['swap_pre'] = '';
$system['db']['pdo_mysql']['autoinit'] = TRUE;
$system['db']['pdo_mysql']['stricton'] = FALSE;
/**
 * -------------------------数据库配置结束--------------------------
 */
/* End of file index.php */
include FRAMEWORK_PATH . '/core/MicroPHP.php';
CoreRouter::setConfig($system);
Example #7
0
 public static function dispatch()
 {
     $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
     $method = $_SERVER['REQUEST_METHOD'];
     $searches = array_keys(static::$patterns);
     $replaces = array_values(static::$patterns);
     self::$routes = str_replace('//', '/', self::$routes);
     $found_route = false;
     $query = '';
     $q_arr = array();
     if (strpos($uri, '&') > 0) {
         $query = substr($uri, strpos($uri, '&') + 1);
         $uri = substr($uri, 0, strpos($uri, '&'));
         $q_arr = explode('&', $query);
         foreach ($q_arr as $q) {
             $qobj = explode('=', $q);
             $q_arr[] = array($qobj[0] => $qobj[1]);
             if (!isset($_GET[$qobj[0]])) {
                 $_GET[$qobj[0]] = $qobj[1];
             }
         }
     }
     if (in_array($uri, self::$routes)) {
         $route_pos = array_keys(self::$routes, $uri);
         foreach ($route_pos as $route) {
             if (self::$methods[$route] == $method || self::$methods[$route] == 'ANY') {
                 $found_route = true;
                 if (!is_object(self::$callbacks[$route])) {
                     self::invokeObject(self::$callbacks[$route]);
                     if (self::$halts) {
                         return;
                     }
                 } else {
                     call_user_func(self::$callbacks[$route]);
                     if (self::$halts) {
                         return;
                     }
                 }
             }
         }
     } else {
         $pos = 0;
         foreach (self::$routes as $route) {
             $route = str_replace('//', '/', $route);
             if (strpos($route, ':') !== false) {
                 $route = str_replace($searches, $replaces, $route);
             }
             if (preg_match('#^' . $route . '$#', $uri, $matched)) {
                 if (self::$methods[$pos] == $method || self::$methods[$pos] == 'ANY') {
                     $found_route = true;
                     array_shift($matched);
                     if (!is_object(self::$callbacks[$pos])) {
                         self::invokeObject(self::$callbacks[$pos], $matched);
                         if (self::$halts) {
                             return;
                         }
                     } else {
                         call_user_func_array(self::$callbacks[$pos], $matched);
                         if (self::$halts) {
                             return;
                         }
                     }
                 }
             }
             $pos++;
         }
     }
     if (self::$fallback) {
         $found_route = self::autoDispatch();
     }
     if (!$found_route) {
         if (!self::$errorCallback) {
             self::$errorCallback = function () {
                 header("{$_SERVER['SERVER_PROTOCOL']} 404 Not Found");
                 $data['title'] = '404';
                 $data['error'] = "Страница не найдена.";
                 View::render('Error/404', $data);
             };
         }
         if (!is_object(self::$errorCallback)) {
             self::invokeObject(self::$errorCallback, null, 'Маршруты не найдены.');
             if (self::$halts) {
                 return;
             }
         } else {
             call_user_func(self::$errorCallback);
             if (self::$halts) {
                 return;
             }
         }
     }
 }
Example #8
0
 /**
  * 实例化一个loader
  * @param type $renew               是否强制重新new一个loader,默认只会new一次
  * @param type $hmvc_module_floder  hmvc模块文件夹名称
  * @return type CoreLoader
  */
 public static function instance($renew = null, $hmvc_module_floder = null)
 {
     $default = CoreLoader::$system;
     if (!empty($hmvc_module_floder)) {
         CoreRouter::switchHmvcConfig($hmvc_module_floder);
     }
     //在plugin模式下,路由器不再使用,那么自动注册不会被执行,自动加载功能会失效,所以在这里再尝试加载一次,
     //如此一来就能满足两种模式
     self::classAutoloadRegister();
     //这里调用控制器instance是为了触发自动加载,从而避免了插件模式下,直接instance模型,自动加载失效的问题
     CoreController::instance();
     $renew = is_bool($renew) && $renew === true;
     $ret = empty(self::$instance) || $renew ? self::$instance = new self() : self::$instance;
     CoreLoader::$system = $default;
     return $ret;
 }
Example #9
0
 /**
  * 
  * 匹配一个路由
  * @param string $pattern
  * @param string $url
  * @return bool
  * 
  * @codephp
  * 
  * $pattern = '(:let)/(:let)/(:any)';
  * $url = '/main/index';
  * self::match($pattern, $url);
  * 
  * @endcode
  * 
  */
 public static function match($pattern, $url)
 {
     $key = str_replace(array(':any', ':let', ':num', ':ln'), array('.*', '[a-zA-Z]+', '[0-9]+', '[a-zA-Z0-9]+'), $pattern);
     if (preg_match("#^{$key}\$#", $url, $vars)) {
         self::$matched_pattern = $key;
         return $vars;
     }
     return false;
 }
Example #10
0
$system['db']['sqlite3']['swap_pre'] = '';
$system['db']['sqlite3']['autoinit'] = TRUE;
$system['db']['sqlite3']['stricton'] = FALSE;
/**
 * PDO mysql数据库配置示例,hostname 其实就是pdo的dsn部分,
 * 如果连接其它数据库按着pdo的dsn写法连接即可
 */
$system['db']['pdo_mysql']['dbdriver'] = 'pdo';
$system['db']['pdo_mysql']['hostname'] = 'mysql:host=localhost;port=3306';
$system['db']['pdo_mysql']['username'] = '******';
$system['db']['pdo_mysql']['password'] = '******';
$system['db']['pdo_mysql']['database'] = 'test';
$system['db']['pdo_mysql']['dbprefix'] = '';
$system['db']['pdo_mysql']['db_debug'] = TRUE;
$system['db']['pdo_mysql']['char_set'] = 'utf8';
$system['db']['pdo_mysql']['dbcollat'] = 'utf8_general_ci';
$system['db']['pdo_mysql']['swap_pre'] = '';
$system['db']['pdo_mysql']['autoinit'] = TRUE;
$system['db']['pdo_mysql']['stricton'] = FALSE;
/**
 * -------------------------数据库配置结束--------------------------
 */
if ($system['debug']) {
    ini_set('display_errors', TRUE);
    error_reporting(E_ALL);
}
/* End of file index.php */
include FRAMEWORK_PATH . '/core/MicroPHP.php';
CoreRouter::setConfig($system);
CoreRouter::loadClass();
echo number_format(utime() - START_TIME, 5) . 's';
Example #11
0
 /**
  * Runs the callback for the given request
  */
 public static function dispatch()
 {
     $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
     $method = $_SERVER['REQUEST_METHOD'];
     $searches = array_keys(static::$patterns);
     $replaces = array_values(static::$patterns);
     $found_route = false;
     self::$routes = str_replace('//', '/', self::$routes);
     // Check if route is defined without regex
     if (in_array($uri, self::$routes)) {
         $route_pos = array_keys(self::$routes, $uri);
         foreach ($route_pos as $route) {
             // Using an ANY option to match both GET and POST requests
             if (self::$methods[$route] === $method || self::$methods[$route] === 'ANY') {
                 $found_route = true;
                 // If route is not an object
                 if (!is_object(self::$callbacks[$route])) {
                     // Grab all parts based on a / separator
                     $parts = explode('/', self::$callbacks[$route]);
                     // Collect the last index of the array
                     $last = end($parts);
                     // Grab the controller name and method call
                     $segments = explode('@', $last);
                     // Instanitate controller
                     $controller = new $segments[0]();
                     // Call method
                     $controller->{$segments[1]}();
                     if (self::$halts) {
                         return;
                     }
                 } else {
                     // Call closure
                     call_user_func(self::$callbacks[$route]);
                     if (self::$halts) {
                         return;
                     }
                 }
             }
         }
     } else {
         // Check if defined with regex
         $pos = 0;
         foreach (self::$routes as $route) {
             if (strpos($route, ':') !== false) {
                 $route = str_replace($searches, $replaces, $route);
             }
             if (preg_match('#^' . $route . '$#', $uri, $matched)) {
                 if (self::$methods[$pos] === $method || self::$methods[$pos] === 'ANY') {
                     $found_route = true;
                     // Remove $matched[0] as [1] is the first parameter.
                     array_shift($matched);
                     if (!is_object(self::$callbacks[$pos])) {
                         // Grab all parts based on a / separator
                         $parts = explode('/', self::$callbacks[$pos]);
                         // Collect the last index of the array
                         $last = end($parts);
                         // Grab the controller name and method call
                         $segments = explode('@', $last);
                         // Instanitate controller
                         $controller = new $segments[0]();
                         // Fix multi parameters
                         if (!method_exists($controller, $segments[1])) {
                             //"controller and action not found"
                             Debugger::report(500);
                         } else {
                             call_user_func_array(array($controller, $segments[1]), $matched);
                         }
                         if (self::$halts) {
                             return;
                         }
                     } else {
                         call_user_func_array(self::$callbacks[$pos], $matched);
                         if (self::$halts) {
                             return;
                         }
                     }
                 }
             }
             $pos++;
         }
     }
     // Run the error callback if the route was not found
     if ($found_route === false) {
         if (!self::$error_callback) {
             self::$error_callback = function () {
                 Debugger::report(404);
             };
         } else {
             if (is_string(self::$error_callback)) {
                 self::get($_SERVER['REQUEST_URI'], self::$error_callback);
                 self::$error_callback = null;
                 self::dispatch();
                 return;
             }
         }
         call_user_func(self::$error_callback);
     }
 }
Example #12
0
 public function __construct()
 {
     self::$_routeMap = CoreHelper::loadConfig("receive_routes", "router");
 }
Example #13
0
 public function __construct()
 {
     parent::__construct();
     $this->router_info = CoreRouter::info();
     // ====================================
     // 确定语言
     // ====================================
     $cookie_lifetime = 7 * 86400;
     if (!empty($_GET['lang']) && preg_match('/^[a-z\\-]+$/', $_GET['lang'])) {
         if ($this->validLanguage($_GET['lang'])) {
             CoreLoader::setCookie('lang', $_GET['lang'], $cookie_lifetime);
             CoreLoader::$system['language'] = $_GET['lang'];
         } else {
             CoreLoader::setCookie('lang', CoreLoader::$system['default_language'], $cookie_lifetime);
             CoreLoader::$system['language'] = CoreLoader::$system['default_language'];
         }
     } else {
         $cookieLang = CoreInput::cookie('lang');
         if (empty($cookieLang) || !preg_match('/^[a-z\\-]+$/', $cookieLang) || !$this->validLanguage($cookieLang)) {
             // if user doesn't specify any language, check his/her browser language
             // check if the visitor language is supported
             // $this->language(true) to return the country code such as en-US zh-CN zh-TW
             $countryCode = true;
             $langcode = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
             $langcode = !empty($langcode) ? explode(';', $langcode) : $langcode;
             $langcode = !empty($langcode[0]) ? explode(',', $langcode[0]) : $langcode;
             if (!$countryCode) {
                 $langcode = !empty($langcode[0]) ? explode('-', $langcode[0]) : $langcode;
             }
             $lang = $langcode[0];
             $lang = strtolower($lang);
             if (preg_match('/^[a-z\\-]+$/', $lang) && $this->validLanguage($lang)) {
                 CoreLoader::setCookie('lang', $lang, $cookie_lifetime);
                 CoreLoader::$system['language'] = $lang;
             } else {
                 CoreLoader::setCookie('lang', CoreLoader::$system['default_language'], $cookie_lifetime);
                 CoreLoader::$system['language'] = CoreLoader::$system['default_language'];
             }
         } else {
             CoreLoader::$system['language'] = $cookieLang;
         }
     }
     #echo CoreLoader::$system['language'];
     $locale = CoreLoader::locale(CoreLoader::$system['language']);
     $langEncoding = explode('.', $locale->getLocale());
     $localeDataFile = CoreLoader::$system['language_folder'] . '/' . $langEncoding[0] . '/locale.php';
     if (file_exists($localeDataFile)) {
         CoreLocale::$LANG = (include $localeDataFile);
     }
     // ====================================
     // 初始化Smarty模板引擎
     // ====================================
     include_once FRAMEWORK_CORE_PATH . '/Smarty/Smarty.class.php';
     $smarty = new Smarty();
     $view_dir = self::$system['view_folder'];
     $cache_dir = self::$system['table_cache_folder'] . '/smarty';
     // $smarty->force_compile = true;
     $smarty->error_reporting = 9;
     //E_ALL;
     $smarty->debugging = false;
     $smarty->caching = false;
     //$smarty->use_sub_dirs = true;
     $smarty->cache_lifetime = 120;
     $smarty->left_delimiter = '<{';
     $smarty->right_delimiter = '}>';
     $smarty->allow_php_templates = true;
     $smarty->setTemplateDir($view_dir);
     $smarty->setCompileDir($cache_dir . '/templates_c/');
     $smarty->setConfigDir($cache_dir . '/configs/');
     $smarty->setCacheDir($cache_dir . '/cache/');
     $smarty->registered_cache_resources = array('phpFastCache', 'memcache');
     //$smarty->caching_type = 'phpFastCache'; //TODO: 缓存无效
     $smarty->caching_type = 'file';
     switch (phpFastCache::$storage) {
         case 'memcache':
         case 'apc':
             $smarty->caching_type = phpFastCache::$storage;
             break;
         default:
             if (function_exists('apc_cache_info')) {
                 $smarty->caching_type = 'apc';
             }
             break;
     }
     $smarty->default_resource_type = 'file';
     //模板保存方式
     // ====================================
     // 设置全局变量
     // ====================================
     $smarty->assignGlobal('TITLE', '');
     $smarty->assignGlobal('KEYWORDS', '');
     $smarty->assignGlobal('DESCRIPTION', '');
     // ====================================
     // 注册自定义函数
     // ====================================
     //$smarty->registerPlugin('function', 'burl', 'build_url');
     //<{burl param=value}> ===> function build_url(...){...}
     //$smarty->registerPlugin('modifier', 'astatus', 'audit_status');
     //<{$var|astatus}> ===> function audit_status(...){...}
     $smarty->registerPlugin('modifier', 'url', 'Fn::url');
     $this->view =& $smarty;
 }