/** * Main method for running application. * * @param $server */ public function run($server) { try { $controller = $this->router->parseUrl($server); $controller = $this->actionFactory->create($controller); $controller->execute(); } catch (\Exception $e) { echo $e->getMessage(); } }
/** * Генерирует URL на страницу, заданную при помощи массива с именем маршрута в нулевом ключе и возможными * дополнительными параметрами в других ключах * * @param array $route * @return string * @throws \app\Exception */ public static function to(array $route) { $routeName = $route[0]; unset($route[0]); $reverse = Router::getInstance()->getRouteReverse($routeName); $search = array_keys($route); array_walk($search, function (&$value) { $value = "<{$value}>"; }); $replace = array_values($route); return str_replace($search, $replace, $reverse); }
public function testResolver() { $mock = $this->mockMiddleware(); $resolver = \App\Router::resolver('/' . $mock); $this->clean(); $this->assertTrue(is_array($resolver)); $this->assertTrue(array_key_exists('name', $resolver)); $this->assertTrue(array_key_exists('path', $resolver)); $this->assertTrue(array_key_exists('middleware', $resolver)); $this->assertTrue(array_key_exists('allowed_methods', $resolver)); $this->assertEquals($mock, $resolver['name']); $this->assertEquals('/' . $mock, $resolver['path']); $this->assertTrue(is_a($resolver['middleware'], "App\\Middlewares\\{$mock}")); }
public function run() { Router::init(); $routerParams = Router::match($_SERVER["REQUEST_URI"]); if ($routerParams === false) { die("403 Bad Request: Route not found"); } $controllerFullName = "\\App\\Controllers\\" . $routerParams["_controller"]; if (!method_exists($controllerFullName, $routerParams["_method"])) { die("404 not found"); } $reflectionMethod = new \ReflectionMethod($controllerFullName, $routerParams["_method"]); $reflectionMethod->invokeArgs(new $controllerFullName(), $routerParams["_params"]); }
public function actionProfile($params = []) { if (Student::isAuthorized()) { $student = new Student(); $student->loadModelFromDb(['email' => $_COOKIE['email']]); if (isset($_POST) && !empty($_POST)) { // TODO: validate user input // TODO: replace 'on' value in $_POST["local"] $student->fetchSchema(); foreach ($_POST as $key => $attribute) { if ($student->{$key} !== $attribute) { $student->modifiedAttributes[$key] = $attribute; } } if (!empty($student->modifiedAttributes)) { $student->update(); } } $this->render('profile.php', ['student' => $student]); } else { Router::error('403'); } }
* On initialise le Router avec les paramètres de l'URL passés par le .htaccess * On initialise les SESSIONS. */ Router::initialize($_GET); Session::initialize(); /* * On assigne dans des variables : * - Le nom de classe du controlleur à instancier * - Le chemin de fichier PHP de la classe du controleur * - Le nom de la méthode à appeler * - Les eventuelles variables passées par URL */ $controllerName = Router::getControllerName(); $controllerFilePath = CONTROLLERS_DIR . Router::getControllerFilename(); $methodName = Router::getMethodName(); $args = Router::getArgs(); // On charge le controleur appellé ou celui par défaut if (file_exists($controllerFilePath)) { include_once $controllerFilePath; $controllerInstance = new $controllerName(); // On appelle beforeFilter(); if (method_exists($controllerInstance, 'beforeFilter')) { $controllerInstance->beforeFilter(); } // Si une méthode est définie if (method_exists($controllerInstance, $methodName)) { $controllerInstance->{$methodName}($args); } else { Error::throwError('Erreur 404!', 'Erreur 404! : La page demandée est inexistante ou n\'existe plus.'); } } else {
public function checkRouter($route) { return Router::checkRoute($route); }
<?php require_once __DIR__ . "/AutoLoader.php"; use app\Router; use app\Controller; $kernel = new Router($_GET); $controller = $kernel->getController(); $controller->ExecuteAction();
public static function run() { self::getInstance(); Router::run(); }
/** * App 404 error */ public function show404() { $this->router->show404(); }
/** * */ public function execute() { // execute page Router::executePage(); }
<?php use App\Router; Router::add('/', 'IndexController@index'); Router::add('/report', 'ReportController@index'); Router::add('/category', 'CategoryController@index'); Router::add('/category/new', 'CategoryController@add'); Router::add('/category/edit/{id}', 'CategoryController@edit'); Router::add('/category/delete/{id}', 'CategoryController@delete'); Router::add('/category/find', 'CategoryController@find'); Router::add('/releases', 'ReleasesController@index'); Router::add('/releases/new', 'ReleasesController@add'); Router::add('/releases/view/{id}', 'ReleasesController@view'); Router::add('/releases/edit/{id}', 'ReleasesController@edit'); Router::add('/releases/delete/{id}', 'ReleasesController@delete'); Router::add('/releases/find', 'ReleasesController@find');
<?php require __DIR__ . '/../vendor/autoload.php'; require '../app/config.php'; use app\Router; $router = new Router(); $router->run();