Establishment of route mvc
-
I understand that the topic that has been afflicted, and there are many (some) examples on the Internet.
The thing is, I have routs, but they're curves. Type:
array(new Route('/url','className','methodName'));
and mass through new Router;
The point is, for everything to work, I need to create a separate file and write two methods there:
__construct($args=[]) {$this->args = $args}
and method, to produce a copy of a class called class, parameters and parameters.
Anyway, what's above doesn't matter.
The point is, it's like my experience in writing a rolling, and I''ve got a hard way in my head, alas.
How can you write a system like properly? Not using dop class, that is: Two classes Route, Router:
$router = [new Route('/','main','index')]; new Router($router);
P.s: Don't ask me to write, just push me into thinking. Thank you.
-
Hello!
MVC means you have controllers to work with a data-produced website and pictures.
In the idea, the structure of the crypt catalogues could be something like:
\Core //базовые классы Controller.php Model.php View.php //и роутер Route.php \Controllers //тут должны лежать контроллеры, для примера положу блог.пхп для блога blog.php error404.php \Models //тут должны лежать модели, для примера положу модель блог.пхп для блога blog.php \Views //тут должны лежать вьюхи, для примера положу пару вьюх для блога //я тут показал файлы html, но тут могут быть и файлы php blog_index.html blog_post.html error404.html \More //в этой папке пускай будут лежать какие-нибудь дополнительные классы
The first thing we need to do is describe a carloider so we don't invent bikes and include classes as we wish (to be included in the index file):
autodoader.php*
<?php spl_autoload_register(function($class){ $file = SITE_DIR.'/'.str_replace('\\', '/', $class).'.php'; if (file_exists($file)) require_once $file; });
Basic classes (they are supposed to have a base function defined):
Core/Controller.php
<?php namespace Core; abstract class Controller { public View = null;
public function __construct() { $this->init(); } abstract function init();
}
\Core\Model.php
<?php
namespace Core;
abstract class Model
{
}
_
<?php
namespace Core;
class View
{
public function addTemplate($template)
{
//тут нужно описать процедуру подгрузки шаблона
}public function addView($view) { //тут нужно описать процедуру подгрузки вьюхи } public function show() { //тут нужно сделать вывод контента }
}
In fact, your View class may be a casing over some sort of template to work with him more comfortable. In this case, I highly recommend that you not write your template, but use something ready. I like the best of the ready. Twig♪
It is further necessary to take the URL received and to take the way out of it to call the right controller:
_
<?php
namespace Core;
class Route
{
static public $routes = null;static function start() { if (self::$routes == null) { $url = explode('?', substr(strtolower($_SERVER['REQUEST_URI'], 1))); self::$routes = explode('/', $url[0]); } $controller_name = 'main'; $action_name = 'index'; if (!empty(self::$routes[0])) { $controller_name = self::$routes[0]; } if (!empty(self::$routes[1])) { $action_name = self::$routes[1]; } $controller_class = '\\Controllers\\'.$controller_name; $action_name = 'action_'.$action_name; $controller = new $controller_class; if(method_exists($controller, $action_name)) { $controller->$action_name(); } else { Route::Error404(); } } public static function Error404() { $protocol = 'http'; if ($_SERVER['SERVER_PORT']==443) $protocol = 'https'; $host = $protocol.'://'.$_SERVER['HTTP_HOST']; header('HTTP/1.1 404 Not Found'); header("Status: 404 Not Found"); header('Location:'.$host.'/error404'); }
}
\Controllers\error404.php
<?php
namespace Controllers;
class error404 extends \Core\Controller
{
public function init()
{
}public function action_index() { $this->View->addTemplate('basic'); $this->View->addView('error404'); $this->View->show(); }
}
\Views\error404.html
<h1>Ошибка 404</h1>
<p>Страница не доступна или не существует.</p>
And you have to have something. index.php (or some other file) that will start everything.
<?php
include "autoloader.php";\Core\Route()::start();
Come on! Even though I've been in some detail, I just wanted to push you into some kind of automation. Rooting can also be performed with files (writing paths to some Rooting file/fail, for example Symfony). Anyway, I wrote the code right here without checking his work capacity. I also don't insist on his ideals.
I'd be glad if I could help.