Answer the question
In order to leave comments, you need to log in
MVC routing in php?
Hello toasters!
I have a simple MVC implementation
here is the router:
<?php
class Router
{
private $routes;
public function __construct()
{
$routesPath = ROOT.'/config/routes.php';
$this->routes = include($routesPath);
}
private function getURI ()
{
if (!empty($_SERVER['REQUEST_URI'])) {
return trim($_SERVER['REQUEST_URI'], '/');
}
}
public function run ()
{
// Получить строку запроса
$uri = $this->getURI();
// Проверить наличие такого запроса в routes.php
foreach ($this->routes as $uriPattern => $path) {
// Сравниваем $uriPattern и $uri
if (preg_match("~$uriPattern~", $uri)) {
// Получаем внутренний путь из внешнего согласно правилу
$internalRoute = preg_replace("~$uriPattern~", $path, $uri);
// Определить какой контроллер
// и action обрабатывают запрос
$segments = explode('/', $internalRoute);
$controllerName = array_shift($segments).'Controller'; //array_shift выбирает 1-ый елемент и уничтожает его
$controllerName = ucfirst($controllerName);
$actionName = 'action'.ucfirst(array_shift($segments));
$parameters = $segments; //т.к. после 2-ух array_shift останутся одни параметры, они сюда и запишутся
// Подключить файл класса-контроллера
$controllerFile = ROOT . '/controllers/' .
$controllerName . '.php';
$internalRoute = preg_replace("~$uriPattern~", $path, $uri);
if (file_exists($controllerFile)) {
include_once ($controllerFile);
}
// Создать обьект, вызвать метод (т.е. action)
$controllerObject = new $controllerName;
$result = call_user_func_array(array($controllerObject, $actionName), $parameters);
if ($result != null) {
break;
}
}
}
}
}
"products" => "site/products"
, public static function actionProducts()
{
...
return true;
}
Answer the question
In order to leave comments, you need to log in
Firstly
dataType: "json", // data transfer typeit is not a transfer type, but the data type of the expected response. That is, json should arrive in response.
but die doesn't work.. WHY? It works on any other page, but not here ... maybe because ajax sent data here? TELL ME PLEASE)))))die works, it's just that you don't understand what you're doing, and that makes you crap. The server returns a string to the SCRIPT, which, apart from the fact that nothing is in json, is not yet "added" to the html, but is returned to the script as a return variable. Look in the browser console - there should be a corresponding error, and in the network tab there should also be a response body.
Just take a klein router or aura router, take it all apart, see what goes where, how why, and everything will become clear to you.
And another OOP router != MVC application. You can put a cool router and then nagovnokodit.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question