Ответов: 1 Просмотров: 2329
|
Делаю простой MVC, с целью разобраться с ним. То, что на данный момент сделано, работает, но есть один нюанс с путями, в котором я не могу разобраться.
Есть роутер, который разбирает url-адрес на контроллер, действие и параметры и запускает их в соответствии с заданными правилами (ниже приведу код). В файлах шаблонов относительные пути для картинок, стилей и прочего (от корневой директории), например: 'files/pictures/php.png'. Так вот, если выполняется правило преобразования url-адресов '' => 'gallery/show' или 'gallery' => 'gallery/show' то все отлично, а если 'gallery/show' => 'gallery/show' - то получаются неправильные пути, он почему-то добавляет к url само правило без последнего члена, в итоге: 'gallery/files/pictures/php.png'. Подскажите, кто знает, в чем проблема?
Вот сам код, прилагаю так же архив со всей структурой)
index.php
PHP:
скопировать код в буфер обмена
<?PHP define('TEMPLATE_EXT', '.tpl.php'); define('ENVIRONMENT', 'development'); { switch (ENVIRONMENT) { case 'development': case 'production': default: exit ('Не установлены параметры окружения'); } } require_once SITE_PATH . '/config/default.php'; function __autoload ($class) { global $config; 'core' => $config['path']['core'] . '/' . $class . CLASS_EXT, 'controllers' => $config['path']['controllers'] . '/' . $class . CLASS_EXT, 'models' => $config['path']['models'] . '/' . $class . CLASS_EXT, ); $flag = FALSE; try { foreach ($paths as $path) { { include_once $path; $flag = TRUE; } } if (!$flag) { throw new Exception('Не найден файл класса: ' . $class); } } catch (Exception $e) {} } $router = new Router(); $router->run(); ?>
router.php
PHP:
скопировать код в буфер обмена
<?PHP class Router { private $controller; private $action; private $params = array(); public function run () { $this->getController(); if (!is_callable(array($this->controller, $this->action))) { $this->action = 'index'; } $controller = new $this->controller; $controller->{(string)$this->action}($this->params); } private function getController () { $url = $this->getURI(); '' => 'gallery/show', 'gallery' => 'gallery/show', 'gallery/show' => 'gallery/show' ); foreach ($rules as $key => $value) { { } } $this->controller = $parts[0] . 'Controller'; if(isset( $parts[1 ])) { $this->action = $parts[1 ]; } if (empty($this->controller)) { $this->controller = 'indexController'; } if (empty($this->action)) { $this->action = 'index'; } } private function getURI() { if(!empty($_SERVER['REQUEST_URI'])) { return trim($_SERVER['REQUEST_URI'], '/'); } if(!empty($_SERVER['QUERY_STRING'])) { return trim($_SERVER['QUERY_STRING'], '/'); } } } ?>
default.php (конфигурация)
PHP:
скопировать код в буфер обмена
<?PHP 'core' => SITE_PATH . '/core', 'controllers' => SITE_PATH . '/app/controllers', 'models' => SITE_PATH . '/app/models', 'templates' => SITE_PATH . '/app/templates' ), ); ?>
Controller.php
galleryController.php
PHP:
скопировать код в буфер обмена
<?PHP class galleryController extends Controller { public function index () {} public function show () { 'doctype' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', 'title' => 'Заголовок' ) ); $this->template = new Template(); $this->template->renderTemplate('index', $vars); } } ?>
Template.php
PHP:
скопировать код в буфер обмена
<?PHP class Template { private $path; public function __construct () { global $config; try { if (!is_dir($config['path']['templates'])) { throw new Exception ('Неверная директория шаблонов: ' . $config['path']['templates'] ); } $this->path = $config['path']['templates']; } catch (Exception $e) {} } public function getTemplate ($template, $vars = array()) { $template_path = $this->path . '/' . $template . TEMPLATE_EXT; include $template_path; } public function renderTemplate ($template, $vars = array()) { echo $this->getTemplate($template, $vars); } } ?>
index.tpl.php
PHP:
скопировать код в буфер обмена
<?PHP echo $page['doctype']; ?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru"> <head> <title><?PHP echo $page['title']; ?></title> <meta http-equiv="content-Language" content="ru" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> </head> <body> <img src="files/pictures/php.png" title="php" width="553" height="291" /> </body> </html>
Структура директорий такая:
/ (1)
. app (2)
. . controllers (3)
. . . galleryController.php (4)
. . templates (3)
. . . index.tpl.php (4)
. config (2)
. . default.php (3)
. core (2)
. . Controller.php (3)
. . Template.php (3)
. . Router.php (3)
. files (2)
. . pictures (3)
. . . php.png (4)
. index.php (2)
Все тоже самое одним архивом |