Example #1
0
 public static function run()
 {
     session_start();
     $router = new Router();
     list($controller, $action, $mergedParams) = $router->parse();
     return $router->dispatch($controller, $action, $mergedParams);
 }
Example #2
0
 static function run()
 {
     if (!self::$init) {
         self::$init = true;
         self::init();
     }
     $route = Router::dispatch();
     if (!empty($route)) {
         if (is_callable($route['callback'])) {
             call_user_func_array($route['callback'], $route['params']);
         } else {
             if (strpos($route['callback'], '@') !== false) {
                 $pieces = explode('@', $route['callback']);
                 $route['action'] = $pieces[1];
                 $route['controller'] = $pieces[0];
             } else {
                 $route['action'] = 'index';
                 $route['controller'] = $route['callback'];
             }
             self::loadRoute($route);
         }
     } else {
         call_user_func(self::$error404);
     }
 }
 protected function setParams()
 {
     global $routes;
     $do = $this->request->get('do', '');
     unset($this->request->get['do']);
     unset($this->request->request['do']);
     if (!empty($do) && (preg_match('/^(?P<lang>[a-zA-Z]{2})\\/(?P<target>[a-zA-Z0-9]+)\\/(?P<action>[a-zA-Z0-9]+)\\/?(?P<params>.*?)?\\/?$/', $do, $matches) || preg_match('/^(?P<lang>[a-zA-Z]{2})\\/(?P<target>[a-zA-Z0-9]+)\\/?(?P<params>.*?)?\\/?$/', $do, $matches) || preg_match('/^(?P<target>[a-zA-Z0-9]{3,})\\/(?P<action>[a-zA-Z0-9]+)\\/?(?P<params>.*?)?\\/?$/', $do, $matches) || preg_match('/^(?P<target>[a-zA-Z0-9]{3,})\\/?(?P<params>.*?)?\\/?$/', $do, $matches) || preg_match('/^(?P<lang>[a-zA-Z]{2})\\/?$/', $do, $matches))) {
     }
     $lang = !empty($matches['lang']) ? $matches['lang'] : '';
     $this->target = !empty($matches['target']) ? $matches['target'] : DEFAULT_CONTROLLER_TARGET;
     $this->action = !empty($matches['action']) ? $matches['action'] : DEFAULT_CONTROLLER_ACTION;
     $this->params = !empty($matches['params']) ? explode('/', $matches['params']) : array();
     $router = new Router($lang, $routes);
     $router->dispatch($this);
     $this->route = $this->target . '/' . $this->action . '/' . implode('/', $this->params);
     $this->uri = ROOT_HTTP . $this->target . '/' . $this->action . '/';
     if (empty($lang)) {
         $lang = Lang::getDefaultLang();
     }
     $this->lang = new Lang($lang);
     $this->querystring = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
     $this->querystring = (!empty($this->querystring) ? '?' : '') . $this->querystring;
     if (get_magic_quotes_gpc()) {
         $this->request = Utils::stripslashes($this->request);
         $this->post = Utils::stripslashes($this->post);
         $this->get = Utils::stripslashes($this->get);
     }
     $this->session = !SESSION_DISABLED ? Session::getInstance(SESSION_DEFAULT_NAME) : null;
 }
Example #4
0
 public function __construct($routes, $base = '/')
 {
     if (!isset($_SESSION)) {
         session_start();
     }
     Router::dispatch($routers, $base);
 }
Example #5
0
 /**
  *  T' the high seas! Garrr!
  */
 public function setSail()
 {
     $request = new Request($_GET, $_POST, $_COOKIE, $_SERVER);
     $router = new Router($request);
     $response = new Response();
     $dispatcher = new Dispatcher($router->dispatch(), $response);
     $dispatcher->fireCannons();
 }
Example #6
0
 public static function dispatch($routes = [], $base = '/', $uri = null, $method = null, ...$extra)
 {
     $result = null;
     if (!$base || substr($base, 0, 1) != '/') {
         $base = '/' . $base;
     }
     if (is_null($uri)) {
         $uri = $_SERVER['REQUEST_URI'];
     }
     if (is_null($method)) {
         $method = $_SERVER['REQUEST_METHOD'];
     }
     $baselen = strlen($base);
     if (substr($uri, 0, $baselen) !== $base) {
         throw new RouterException('URI base doesn\'t match for route, debug info: ' . $base . ' =/=> ' . $uri . ', set up a valid base!');
     }
     $uri = substr($uri, $baselen);
     $found = false;
     foreach ($routes as $route => $action) {
         $splits = explode(':', $route);
         $splits[0] = strtoupper($splits[0]);
         if ($splits[0] == 'ANY') {
             $splits[0] = 'GET,POST';
         }
         $methods = explode(',', $splits[0]);
         $regex = $splits[1];
         if (in_array($method, $methods) && preg_match($regex, $uri, $matches)) {
             $found = true;
             $args = array_merge([$base, $matches, $route], $extra);
             if (is_string($action) && is_callable($action)) {
                 $result = call_user_func_array($action, $args);
             } else {
                 if (is_string($action)) {
                     $result = $action($base, $matches, $route, ...$extra);
                 } else {
                     if (is_callable($action)) {
                         $result = $action($base, $matches, $route, ...$extra);
                     } else {
                         if (is_array($action)) {
                             $result = Router::dispatch($base, $matches, $route, ...$extra);
                         } else {
                             throw new RouterException('Illegal action', 1, null, $base);
                         }
                     }
                 }
             }
             break;
         }
     }
     if (!$found) {
         throw new RouterException('Not found action handler for ' . $uri . ' URI on method ' . $method, 2, null, $base);
     }
     return $result;
 }
 public function dispatch($method = 'GET', $uri = '', $domain = null)
 {
     //slash uri
     $uri = $this->slashUri($uri);
     //found in cache
     if ($route = $this->dispatchViaCache($method, $uri, $domain)) {
         return $route;
     }
     //run normal dispatcher
     $route = parent::dispatch($method, $uri, $domain);
     //found it, lets add it to the map
     if ($route instanceof Route) {
         $this->cache->set($this->getCacheKey($method, $uri, $domain), $route);
     }
     //and return
     return $route;
 }
Example #8
0
 /**
  * init function of the beginning 
  */
 public static function init()
 {
     set_error_handler(array('App', "appError"));
     set_exception_handler(array('App', "appException"));
     //set timezone
     if (function_exists('data_default_timezone_set')) {
         date_default_timezone_set(C('default_timezone'));
     }
     //set autoloader
     if (function_exists('spl_autoload_register')) {
         spl_autoload_register(array('Base', 'autoload'));
     }
     // Session initial lize
     if (isset($_REQUEST[C("VAR_SESSION_ID")])) {
         session_id($_REQUEST[C("VAR_SESSION_ID")]);
     }
     if (C('SESSION_AUTO_START')) {
         session_start();
     }
     //if is WEB PUB MODE do the dispatche from the request prams
     if (PUB_MODE == 'WEB') {
         Router::dispatch();
     } elseif (PUB_MODE == 'IO') {
         //for api project
         // DO IO ACTION
         if (isset($_GET['m']) && isset($_GET['a'])) {
             define('MODULE_NAME', $_GET['m']);
             define('ACTION_NAME', $_GET['a']);
         } else {
             define('MODULE_NAME', 'index');
             define('ACTION_NAME', 'index');
         }
     } elseif (PUB_MODE == 'CLI') {
         //for backend project
         //CLI MODE
         define('MODULE_NAME', isset($_SERVER['argv'][1]) ? strtolower($_SERVER['argv'][1]) : 'index');
         define('ACTION_NAME', isset($_SERVER['argv'][2]) ? strtolower($_SERVER['argv'][2]) : 'index');
     }
     //check language
     self::checkLanguage();
     return;
 }
 protected function setParams()
 {
     global $routes;
     $do = $this->request->get('do', '');
     unset($this->request->get['do']);
     unset($this->request->request['do']);
     if (!empty($do) && (preg_match('/^(?P<lang>[a-zA-Z]{2})\\/(?P<target>[a-zA-Z0-9]+)\\/(?P<action>[a-zA-Z0-9]+)\\/?(?P<params>.*?)?\\/?$/', $do, $matches) || preg_match('/^(?P<lang>[a-zA-Z]{2})\\/(?P<target>[a-zA-Z0-9]+)\\/?(?P<params>.*?)?\\/?$/', $do, $matches) || preg_match('/^(?P<target>[a-zA-Z0-9]{3,})\\/(?P<action>[a-zA-Z0-9]+)\\/?(?P<params>.*?)?\\/?$/', $do, $matches) || preg_match('/^(?P<target>[a-zA-Z0-9]{3,})\\/?(?P<params>.*?)?\\/?$/', $do, $matches) || preg_match('/^(?P<lang>[a-zA-Z]{2})\\/?$/', $do, $matches))) {
     }
     $lang = !empty($matches['lang']) ? $matches['lang'] : '';
     $this->target = !empty($matches['target']) ? $matches['target'] : 'home';
     $this->action = !empty($matches['action']) ? $matches['action'] : 'index';
     $this->params = !empty($matches['params']) ? explode('/', $matches['params']) : array();
     /*
     echo 'LANG >> '.$lang.'<br>';
     echo 'TARGET >> '.print_r($this->target, true).'<br>';
     echo 'ACTION >> '.print_r($this->action, true).'<br>';
     echo 'PARAMS >> '.print_r($this->params, true).'<br>';
     */
     $router = new Router($lang, $routes);
     $router->dispatch($this);
     //$path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
     //$root_path = trim(ROOT_DIR.'/'.(!empty($lang) ? $lang : ''), '/');
     $this->route = $this->target . '/' . $this->action . '/' . implode('/', $this->params);
     $this->uri = ROOT_HTTP . $this->target . '/' . $this->action . '/';
     if (empty($lang)) {
         $lang = Lang::getDefaultLang();
     }
     $this->lang = new Lang($lang);
     $this->querystring = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
     $this->querystring = (!empty($this->querystring) ? '?' : '') . $this->querystring;
     if (get_magic_quotes_gpc()) {
         $this->request = Utils::stripslashes($this->request);
         $this->post = Utils::stripslashes($this->post);
         $this->get = Utils::stripslashes($this->get);
     }
 }
Example #10
0
<?php

require_once 'core/Router.php';
$routes = array(array("#view/posts/([0-9]+)#i", 'post.php', array('id')));
$path = Router::dispatch($routes);
/*if(preg_match('#view/posts/([0-9]+)$#i', $path, $matches)){
  $_GET['id'] = $matches[1];
  require('post.php');
}*/
Example #11
0
    }
}
//initiate config
new \core\config();
//create alias for Router
use core\router, helpers\url;
//define routes
Router::any('admin', '\\controllers\\admin\\admin@index');
Router::any('admin/login', '\\controllers\\admin\\auth@login');
Router::any('admin/logout', '\\controllers\\admin\\auth@logout');
Router::any('admin/users', '\\controllers\\admin\\users@index');
Router::any('admin/users/add', '\\controllers\\admin\\users@add');
Router::any('admin/users/edit/(:num)', '\\controllers\\admin\\users@edit');
Router::any('admin/posts', '\\controllers\\admin\\posts@index');
Router::any('admin/posts/add', '\\controllers\\admin\\posts@add');
Router::any('admin/posts/edit/(:num)', '\\controllers\\admin\\posts@edit');
Router::any('admin/posts/delete/(:num)', '\\controllers\\admin\\posts@delete');
Router::any('admin/cats', '\\controllers\\admin\\cats@index');
Router::any('admin/cats/add', '\\controllers\\admin\\cats@add');
Router::any('admin/cats/edit/(:num)', '\\controllers\\admin\\cats@edit');
Router::any('admin/cats/delete/(:num)', '\\controllers\\admin\\cats@delete');
Router::any('', '\\controllers\\blog@index');
Router::any('category/(:any)', '\\controllers\\blog@cat');
Router::any('(:any)', '\\controllers\\blog@post');
//if no route found
Router::error('\\core\\error@index');
//turn on old style routing
Router::$fallback = false;
//execute matched routes
Router::dispatch();
Example #12
0
 /**
  * @group issues
  * @ticket 37
  **/
 public function test_optional_parameter_in_class_routes()
 {
     $r = new Router();
     $r->any('/optional/*', 'Respect\\Rest\\MyOptionalParamRoute');
     $response = $r->dispatch('get', '/optional')->response();
     $this->assertEquals('John Doe', (string) $response);
 }
Example #13
0
include './config/autoloader.php';
?>
<!doctype html>
<html class='admin-page'>
<head>
	<meta name='viewport' content='width=device-width,initial-scale=1' >
	<link href='/reset.css' rel='stylesheet'/>
	<link href='/main.css' rel='stylesheet'/>
  <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js?autoload=true&amp;skin=sunburst&amp;lang=css" defer="defer"></script>
</head>
<body>
	<div class='container'>
		<div class='inner-container'>
			<?php 
$router = new Router();
$router->route('/admin.php/edit/:articleid', 'admin\\edit\\EditArticleHandler');
$router->route('/admin.php/create', 'admin\\create\\CreateArticleHandler');
$router->route('/admin.php', 'admin\\ShowArticlesHandler');
$router->route('/admin.php/cancel-edit/:articleid', 'admin\\CancelEditHandler');
$router->route('/admin.php/create/:articleid', 'CreateArticleHandler');
$router->route('/admin.php/create/preview/:articleid', 'admin\\create\\preview\\CreatePreviewArticleHandler');
$router->route('/admin.php/edit/preview/:articleid', 'admin\\edit\\preview\\EditPreviewArticleHandler');
$router->setDefaultHandlerClass('admin\\ShowArticlesHandler');
$router->dispatch();
?>
		</div>
	</div>
</body>
</html>

Example #14
0
 /**
  * @brief init LogX 全局初始化方法
  *
  * @return void
  */
 public static function init()
 {
     // 输出 Logo
     if (isset($_GET['591E-D5FC-8065-CD36-D3E8-E45C-DB86-9197'])) {
         Response::logo();
     }
     // 非 DEBUG 模式下关闭错误输出
     if (defined('LOGX_DEBUG')) {
         error_reporting(E_ALL);
     } else {
         error_reporting(0);
     }
     // 设置自动载入函数
     function __autoLoad($className)
     {
         if (substr($className, -7) == 'Library' && is_file(LOGX_LIB . $className . '.php')) {
             @(require_once LOGX_LIB . $className . '.php');
         }
     }
     // 设置错误与异常处理函数
     set_error_handler(array(__CLASS__, 'error'));
     set_exception_handler(array(__CLASS__, 'exception'));
     // 运行环境检查
     if (!version_compare(PHP_VERSION, '5.0.0', '>=')) {
         throw new LogXException(sprintf(_t('LogX needs PHP 5.0.x or higher to run. You are currently running PHP %s.'), PHP_VERSION));
     }
     if (!version_compare(PHP_VERSION, '5.2.0', '>=')) {
         // 针对低版本 PHP 的兼容代码
         @(require_once LOGX_CORE . 'Compat.php');
     }
     // 设置语言
     if (defined('LOGX_LANGUAGE')) {
         Language::set(LOGX_LANGUAGE);
     } else {
         Language::set('zh-cn');
     }
     // 预编译核心文件
     global $coreFiles;
     if (!defined('LOGX_DEBUG') && !file_exists(LOGX_CACHE . '~core.php')) {
         Compile::build(LOGX_CACHE, $coreFiles, 'core');
     } elseif (!defined('LOGX_DEBUG')) {
         $file_time = filemtime(LOGX_CACHE . '~core.php');
         foreach ($coreFiles as $file) {
             if (filemtime($file) > $file_time) {
                 Compile::build(LOGX_CACHE, $coreFiles, 'core');
                 break;
             }
         }
     }
     self::$_globalVars = array('RUN' => array('TIME' => microtime(TRUE), 'MEM' => function_exists('memory_get_usage') ? memory_get_usage() : 0, 'LANG' => 'zh-cn'), 'SYSTEM' => array('OS' => PHP_OS, 'HTTP' => Request::S('SERVER_SOFTWARE', 'string'), 'PHP' => PHP_VERSION, 'MYSQL' => ''), 'SUPPORT' => array('MYSQL' => function_exists('mysql_connect'), 'GD' => function_exists('imagecreate'), 'MEMCACHE' => function_exists('memcache_connect'), 'SHMOP' => function_exists('shmop_open'), 'GZIP' => function_exists('ob_gzhandler'), 'TIMEZONE' => function_exists('date_default_timezone_set'), 'AUTOLOAD' => function_exists('spl_autoload_register')), 'INI' => array('ALLOW_CALL_TIME_PASS_REFERENCE' => ini_get('allow_call_time_pass_reference'), 'MAGIC_QUOTES_GPC' => ini_get('magic_quotes_gpc'), 'REGISTER_GLOBALS' => ini_get('register_globals'), 'ALLOW_URL_FOPEN' => ini_get('allow_url_fopen'), 'ALLOW_URL_INCLUDE' => ini_get('allow_url_include'), 'SAFE_MODE' => ini_get('safe_mode'), 'MAX_EXECUTION_TIME' => ini_get('max_execution_time'), 'MEMORY_LIMIT' => ini_get('memory_limit'), 'POST_MAX_SIZE' => ini_get('post_max_size'), 'FILE_UPLOADS' => ini_get('file_uploads'), 'UPLOAD_MAX_FILESIZE' => ini_get('upload_max_filesize'), 'MAX_FILE_UPLOADS' => ini_get('max_file_uploads')));
     // 清除不需要的变量,防止变量注入
     $defined_vars = get_defined_vars();
     foreach ($defined_vars as $key => $value) {
         if (!in_array($key, array('_POST', '_GET', '_COOKIE', '_SERVER', '_FILES'))) {
             ${$key} = '';
             unset(${$key});
         }
     }
     // 对用户输入进行转义处理
     if (!get_magic_quotes_gpc()) {
         $_GET = self::addSlashes($_GET);
         $_POST = self::addSlashes($_POST);
         $_COOKIE = self::addSlashes($_COOKIE);
     }
     // 开启输出缓存
     if (defined('LOGX_GZIP') && self::$_globalVars['SUPPORT']['GZIP']) {
         ob_start('ob_gzhandler');
     } else {
         ob_start();
     }
     // 连接到数据库
     Database::connect(DB_HOST, DB_USER, DB_PWD, DB_NAME, DB_PCONNECT);
     self::$_globalVars['SYSTEM']['MYSQL'] = Database::version();
     // 设定时区
     if (self::$_globalVars['SUPPORT']['TIMEZONE']) {
         date_default_timezone_set(OptionLibrary::get('timezone'));
     }
     // 连接到缓存
     Cache::connect(CACHE_TYPE);
     // 初始化路由表
     Router::init();
     // 初始化主题控制器
     Theme::init();
     // 初始化 Plugin
     Plugin::initPlugins();
     // 初始化全局组件
     Widget::initWidget('Global');
     Widget::initWidget('Widget');
     Widget::initWidget('Page');
     Widget::initWidget('User');
     // 尝试自动登录
     Widget::getWidget('User')->autoLogin();
     // 启动路由分发
     Router::dispatch();
 }
Example #15
0
 public function dispatch()
 {
     $this->router->dispatch($this->router->request());
 }
Example #16
0
<?php

/*Router::add('/',function(){
	echo "Welcome to Vibius 3 development kit";
});*/
// add a new route, which uses later defined regex alternatives,
Router::add('/(profile)/<:num>', function () {
    // return class, function
    return ['App\\controllers\\WelcomeController', 'index'];
})->alias(['/(profile)/<:doge>' => 'GET', '/' => 'GET']);
// add some regex alternatives for routes
Router::alternatives()->add('<:num>', '(\\d+)');
Router::alternatives()->add('<:doge>', '(woof)');
// find the route match
$match = Router::dispatch();
if ($match) {
    //execute the route match here
    $responseHandlers = $match['callback']();
    call_user_func_array($responseHandlers, Request::segmentArray());
} else {
    //handle 404 here
    echo 'not found!';
}
echo "<p> <b>Execution time: </b>" . round((microtime(true) - $GLOBALS['execution_time']) * 1000, 2) . " ms, <b>Memmory used: </b>" . memory_get_peak_usage(true) / 1024 / 1024 . " MB</p>";
Example #17
0
 function test_single_last_param2()
 {
     $r = new Router();
     $args = array();
     $r->any('/documents/**', function ($documentsPath) use(&$args) {
         $args = func_get_args();
     });
     $r->dispatch('get', '/documents/foo/bar')->response();
     $this->assertEquals(array(array('foo', 'bar')), $args);
 }
Example #18
0
<?php

ini_set('display_errors', 1);
require_once 'Component/Annotation.php';
require_once 'Component/EntityMapper.php';
require_once 'Database/PDOAdapter.php';
require_once 'Manager/UnitOfWork.php';
require_once 'Manager/Manager.php';
require_once 'Controller/Rest.php';
require_once 'Controller/AbstractController.php';
require_once 'Controller/ResellerRest.php';
require_once 'Entity/Entity.php';
require_once 'Entity/Reseller.php';
require_once 'Router.php';
$router = new Router();
$router->dispatch($_GET['controller']);
Example #19
0
<?php

define('ROOT_PATH', dirname(__DIR__));
if (empty($_FILES) && !empty($_SERVER['USE_SERVICE'])) {
    require ROOT_PATH . '/bootstrap/service.php';
}
error_reporting(-1);
include ROOT_PATH . '/bootstrap/functions.php';
//$_SERVER['ENABLE_PROFILER']=1;
profilerStart();
include ROOT_PATH . '/bootstrap/start.php';
include ROOT_PATH . '/vendor/phwoolcon/di.php';
set_exception_handler('exceptionHandler');
set_error_handler('errorHandler');
$app = new Phalcon\Mvc\Application($di);
$di->setShared('app', $app);
Router::dispatch()->send();
profilerStop();
 function test_route_ordering_with_when()
 {
     $when = false;
     $r = new Router();
     $r->get('/', 'HOME');
     $r->get('/users', function () {
         return 'users';
     });
     $r->get('/users/*', function ($userId) {
         return 'user-' . $userId;
     })->when(function ($userId) use(&$when) {
         $when = true;
         return is_numeric($userId) && $userId > 0;
     });
     $r->get('/docs', function () {
         return 'DOCS!';
     });
     $response = $r->dispatch('get', '/users/1')->response();
     $this->assertTrue($when);
     $this->assertEquals('user-1', $response);
 }
 public function start()
 {
     $this->router->dispatch($this->container);
 }
Example #22
0
 * Middleware 
 * /middleware/index.php
 * We can use middleware to define route policy
 */
include 'app/middleware/index.php';
/**
 * Routes
 * Interprete all routes and execute actions.
 * Retrieve all params to use in views.
 */
require 'core/Router.php';
$Router = new Router();
// Add user routes
require ROUTES_PATH;
// dispatch HTTP petition
$Router->dispatch($request->params['GET']['u'], $request, $response);
$res = $response;
if (!empty($res->locals)) {
    extract($res->locals);
}
// Flash messages are optional
if (!empty($res->flash)) {
    $flash = $res->flash;
}
if (is_array($flash)) {
    $flash_type = key($flash);
    $flash_message = $flash[$flash_type];
} else {
    $flash_type = 'info';
    $flash_message = $flash;
}
Example #23
0
 public function testExperimentalShell()
 {
     $router = new Router();
     $router->install('/**', function () {
         return 'Installed ' . implode(', ', func_get_args());
     });
     $commandLine = 'install apache php mysql';
     $commandArgs = explode(' ', $commandLine);
     $output = $router->dispatch(array_shift($commandArgs), '/' . implode('/', $commandArgs))->run();
     $this->assertEquals('Installed apache, php, mysql', $output);
 }