本文整理汇总了PHP中Router类的典型用法代码示例。如果您正苦于以下问题:PHP Router类的具体用法?PHP Router怎么用?PHP Router使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Router类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testDatasRoute
public function testDatasRoute()
{
$router = new \Router();
$router->datas('/', 'Tests\\TestController', 'getPost');
$this->assertEquals('getPost', $router->search('GET', '/'));
$this->assertEquals('getPost', $router->search('POST', '/'));
}
示例2: getRouter
public function getRouter()
{
$router = new Router();
foreach ($this->getActionRoutes() as $methodRoute) {
list($route, $methodName) = $methodRoute;
$method = new \ReflectionMethod($this, $methodName);
$httpMethod = 'GET';
$hasRoute = false;
if ($comment = $method->getDocComment()) {
if (preg_match('~^[\\s*]*\\@method\\s([^\\s]+)~im', $comment, $match)) {
$httpMethod = trim(strtoupper(array_pop($match)));
}
if (preg_match('~^[\\s*]*\\@route\\s([^\\s]+)~im', $comment, $match)) {
$route = trim(array_pop($match));
$hasRoute = true;
}
}
if (!$hasRoute) {
foreach ($method->getParameters() as $parameter) {
$route .= '/{' . ($parameter->isOptional() ? '?' : '') . $parameter->getName() . '}';
}
}
$router->add($httpMethod, $route, [get_class($this), $methodName]);
}
return $router;
}
示例3: start
function start () {
// Output-buffering: ON
ob_start();
// Pre-view middleware
// ### TODO ###
// Use the Router to map the command string to a view
try {
$router = new Router($this->routes, $this->command);
$router->start();
}
catch (Http404Exception $e) {
return self::http_404($e->getMessage());
}
catch (Exception $e) {
return self::http_500($e->getMessage());
}
// Post-view middleware
// ### TODO ###
// Output-buffering: Flush
ob_end_flush();
}
示例4: setParams
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;
}
示例5: getController
public function getController()
{
$Router = new Router();
$this->Router = $Router;
$xml = new \DOMDocument();
$xml->load(__DIR__ . '/../../App/' . $this->name . '/Config/routes.xml');
$routes = $xml->getElementsByTagName('route');
// On parcourt les routes du fichier XML.
foreach ($routes as $route) {
$vars = [];
// On regarde si des variables sont présentes dans l'URL.
if ($route->hasAttribute('vars')) {
$vars = explode(',', $route->getAttribute('vars'));
}
// On ajoute la route au routeur.
$Router->addRoute(new Route($route->getAttribute('url'), $route->getAttribute('module'), $route->getAttribute('action'), $vars));
}
try {
// On récupère la route correspondante à l'URL.
$matchedRoute = $Router->getRoute($this->httpRequest->requestURI());
} catch (\RuntimeException $e) {
if ($e->getCode() == Router::NO_ROUTE) {
// Si aucune route ne correspond, c'est que la page demandée n'existe pas.
$this->httpResponse->redirect404();
}
}
// On ajoute les variables de l'URL au tableau $_GET.
$_GET = array_merge($_GET, $matchedRoute->vars());
// On instancie le contrôleur.
$controllerClass = 'App\\' . $this->name . '\\Modules\\' . $matchedRoute->module() . '\\' . $matchedRoute->module() . 'Controller';
return new $controllerClass($this, $matchedRoute->module(), $matchedRoute->action());
}
示例6: route
public function route($model, $form, $fieldName, $fieldType, $path)
{
$field = $form->fields()->{$fieldName};
if (!$field or $field->type() !== $fieldType) {
throw new Exception('Invalid field');
}
$routes = $field->routes();
$router = new Router($routes);
if ($route = $router->run($path)) {
if (is_callable($route->action()) and is_a($route->action(), 'Closure')) {
return call($route->action(), $route->arguments());
} else {
$controllerFile = $field->root() . DS . 'controller.php';
$controllerName = $fieldType . 'FieldController';
if (!file_exists($controllerFile)) {
throw new Exception(l('fields.error.missing.controller'));
}
require_once $controllerFile;
if (!class_exists($controllerName)) {
throw new Exception(l('fields.error.missing.class'));
}
$controller = new $controllerName($model, $field);
return call(array($controller, $route->action()), $route->arguments());
}
} else {
throw new Exception(l('fields.error.route.invalid'));
}
}
示例7: testEquals
/**
* @dataProvider testEqualsProvider
*/
function testEquals($method, $val)
{
$r = new Router();
$r->initNoCall();
$call = call_user_func([$r, $method]);
$this->assertEquals($val, $call, _unit_dump(['method' => $method, 'expected' => $val, 'actual' => $call]));
}
示例8: testSpeedRegexRoutes
public function testSpeedRegexRoutes()
{
$start = microtime(1);
$router = new Router();
$router->addRouteRule(new RouteRule("show/<d>", "show/<d>"));
$end = microtime(1) - $start;
echo sprintf('Initialize %8d rules at %f sec, per 1 rule %0.20f sec', 1, $end, $end / 1), PHP_EOL;
$start = microtime(1);
$data = serialize($router);
$end = microtime(1) - $start;
echo sprintf('Serialize %8d rules at %f sec, per 1 rule %0.20f sec', 1, $end, $end / 1), PHP_EOL;
$start = microtime(1);
unserialize($data);
$end = microtime(1) - $start;
echo sprintf('Unserialize %8d rules at %f sec, per 1 rule %0.20f sec', 1, $end, $end / 1), PHP_EOL;
$count = 1000;
$start = microtime(1);
for ($i = 0; $i < $count; $i++) {
$router->createUrl("show/{$i}");
}
$end = microtime(1) - $start;
echo sprintf('Create %8d urls at %f sec, per 1 call %0.20f sec', $count, $end, $end / $count), PHP_EOL;
$start = microtime(1);
for ($i = 0; $i < $count; $i++) {
$router->matchUrl("show/{$i}");
}
$end = microtime(1) - $start;
echo sprintf('Found %8d urls at %f sec, per 1 call %0.20f sec', $count, $end, $end / $count), PHP_EOL;
}
示例9: isAllowedUrl
public static function isAllowedUrl($url)
{
include SYS_APPLICATION_PATH . DS . 'config' . DS . 'routes.php';
$route = new \Router($routes, '/index.php', $url);
$structure = $route->getCallStructure();
return self::isAllowed($structure['controller'], $structure['action'], $structure['parms']);
}
示例10: run
public static function run()
{
session_start();
$router = new Router();
list($controller, $action, $mergedParams) = $router->parse();
return $router->dispatch($controller, $action, $mergedParams);
}
示例11: run
function run()
{
$router = new Router();
try {
/** @var RouterResult $result */
$result = $router->process($this->config['routes']);
$actionName = $result->getActionName();
$controllerName = $result->getControllerName();
$params = $result->getParams();
/** @var Controller $controller */
$controller = new $controllerName();
$controller->setParams($params);
if ($controller instanceof \Framework\Config\ConfigAwareInterface) {
$controller->setConfig($this->config);
}
$viewData = $controller->{$actionName}();
if ($controller->getUseTemplate() == true) {
$template = $result->getController() . '/' . $result->getAction();
$useLayout = $controller->getUseLayout();
$view = new View();
$view->display($viewData, $template, $useLayout);
}
} catch (Exception\NotFoundException $e) {
header("HTTP/1.0 404 Not Found");
$message = $this->config['environment'] === \Framework\App::DEVELOPMENT_ENVIRONMENT ? 'Page Not Found' : $e->getMessage();
$view = new View();
$view->display(['message' => $message], 'error/error');
} catch (Exception\BaseException $e) {
header("HTTP/1.0 500 Internal Server Error");
$message = $this->config['environment'] === \Framework\App::DEVELOPMENT_ENVIRONMENT ? 'Internal Server Error' : $e->getMessage();
$view = new View();
$view->display(['message' => $message], 'error/error');
}
}
示例12: __construct
function __construct()
{
$sesion = new Sesion('usuario');
$router = new Router();
$router->AppRoutes();
$router->View($sesion);
}
示例13: __construct
/**
* Bese controller constructor: restores user object by using session data and
* checks a permission to a requested action
*
* @param LiveCart $application Application instance
* @throws AccessDeniedExeption
*/
public function __construct(LiveCart $application)
{
parent::__construct($application);
$this->router = $this->application->getRouter();
if (!$application->isInstalled() && !$this instanceof InstallController) {
header('Location: ' . $this->router->createUrl(array('controller' => 'install', 'action' => 'index')));
exit;
}
unset($this->locale);
unset($this->config);
unset($this->user);
unset($this->session);
$this->checkAccess();
$this->application->setRequestLanguage($this->request->get('requestLanguage'));
$this->configFiles = $this->getConfigFiles();
$this->application->setConfigFiles($this->configFiles);
$localeCode = $this->application->getLocaleCode();
// add language code to URL for non-default languages
if ($localeCode != $this->application->getDefaultLanguageCode()) {
$this->router->setAutoAppendVariables(array('requestLanguage' => $localeCode));
}
// verify that the action is accessed via HTTPS if it is required
if ($this->router->isSSL($this->request->getControllerName(), $this->request->getActionName()) && !$this->router->isHttps()) {
header('Location: ' . $this->router->createFullUrl($_SERVER['REQUEST_URI'], true));
exit;
}
}
示例14: testFindMatch
public function testFindMatch()
{
$pattern = 'admin/edit/:id';
$router = new Router();
$this->assertEquals($router->findMatch($pattern, 'admin/edit/1'), true);
$this->assertEquals($router->findMatch($pattern, 'admin/create/1'), false);
}
示例15: getController
public function getController()
{
$router = new Router();
$xml = new \DOMDocument();
$xml->load(__DIR__ . '/../../App/' . $this->name . '/Config/route.xml');
$routes = $xml->getElementByTagName("route");
foreach ($routes as $route) {
$vars = [];
if ($route->hasAttribute('vars')) {
$vars = explode(',', $route->getAttribute('vars'));
}
$router->addRoute(new Route($route->getAttribute('url'), $route->getAttribute('module'), $route->getAttribute('action'), $vars));
}
try {
$matched_route = $router->getRoute($this->httpRequest->requestURI());
} catch (\RuntimeException $exception) {
if ($exception->getCode() == Router::NO_ROUTE) {
$this->httpResponse->redirect404();
}
}
// Add variables in tab: $_GET
$_GET = array_merge($_GET, $matched_route->module(), $matched_route->action());
// Instancie the controller
$controller_class = 'App\\' . $this->name . '\\Modules\\' . $matched_route->module() . '\\' . $matched_route->module() . 'Controllers';
return new $controller_class($this, $matched_route->module(), $matched_route->action());
}