Warning: Cannot use a scalar value as an array in /home/admin/public_html/forum/include/fm.class.php on line 757

Warning: Invalid argument supplied for foreach() in /home/admin/public_html/forum/include/fm.class.php on line 770
Форумы портала PHP.SU :: Версия для печати :: Проблема с относительными путями файлов в шаблоне mvc
Форумы портала PHP.SU » » Объектно-ориентированное программирование » Проблема с относительными путями файлов в шаблоне mvc

Страниц (1): [1]
 

1. Corpsee - 04 Сентября, 2011 - 10:03:19 - перейти к сообщению
Делаю простой 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:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3. define('SITE_PATH', realpath(dirname(__FILE__)));
  4. define('CLASS_EXT', '.php');
  5. define('TEMPLATE_EXT', '.tpl.php');
  6. define('ENVIRONMENT', 'development');
  7.  
  8. if (defined('ENVIRONMENT'))
  9. {
  10.         switch (ENVIRONMENT)
  11.         {
  12.                 case 'development':
  13.                         error_reporting(E_ALL/* & ~E_NOTICE*/); break;
  14.                 case 'production':
  15.                         error_reporting(0); break;
  16.                 default:
  17.                         exit ('Не установлены параметры окружения');
  18.         }
  19. }
  20.  
  21. require_once SITE_PATH . '/config/default.php';
  22.  
  23. function __autoload ($class)
  24. {
  25.         global $config;
  26.  
  27.         $paths = array(
  28.                 'core' => $config['path']['core'] . '/' . $class . CLASS_EXT,
  29.                 'controllers' => $config['path']['controllers'] . '/' . $class . CLASS_EXT,
  30.                 'models' => $config['path']['models'] . '/' . $class . CLASS_EXT,
  31.         );
  32.  
  33.         $flag = FALSE;
  34.  
  35.         try
  36.         {
  37.                 foreach ($paths as $path)
  38.                 {
  39.                         if (is_readable($path))
  40.                         {
  41.                                 include_once $path;
  42.                                 $flag = TRUE;
  43.                         }
  44.                 }
  45.                 if (!$flag)
  46.                 {
  47.                         throw new Exception('Не найден файл класса: ' . $class);
  48.                 }
  49.         }
  50.         catch (Exception $e) {}
  51. }
  52.  
  53. $router = new Router();
  54. $router->run();
  55. ?>
  56.  


router.php

PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3. class Router
  4. {
  5.         private $controller;
  6.  
  7.         private $action;
  8.  
  9.         private $params = array();
  10.  
  11.         public function run ()
  12.         {
  13.                 $this->getController();
  14.  
  15.         if (!is_callable(array($this->controller, $this->action))) { $this->action = 'index'; }
  16.  
  17.                 $controller = new $this->controller;
  18.                 $controller->{(string)$this->action}($this->params);
  19.         }
  20.  
  21.         private function getController ()
  22.         {
  23.                 $url = $this->getURI();
  24.  
  25.                 $rules = array(
  26.                                       ''                   => 'gallery/show',
  27.                                       'gallery'         => 'gallery/show',
  28.                                       'gallery/show' => 'gallery/show'
  29.                 );
  30.  
  31.                 foreach ($rules as $key => $value)
  32.                 {
  33.                         if(preg_match('!' . $key . '!', $url))
  34.                         {
  35.                                 $route = preg_replace('!' . $key . '!', $value, $url);
  36.                         }
  37.                 }
  38.  
  39.                 $parts = explode('/', $route);
  40.         $this->controller = $parts[0] . 'Controller';
  41.  
  42.                 if(isset( $parts[1])) { $this->action = $parts[1]; }
  43.                 if(isset( $parts[2])) { $this->params = array_slice($parts, 2); }
  44.  
  45.         if (empty($this->controller)) { $this->controller = 'indexController'; }
  46.                 if (empty($this->action)) { $this->action = 'index'; }
  47.         }
  48.  
  49.         private function getURI()
  50.         {
  51.                 if(!empty($_SERVER['REQUEST_URI']))
  52.                 {
  53.                         return trim($_SERVER['REQUEST_URI'], '/');
  54.                 }
  55.  
  56.         if(!empty($_SERVER['QUERY_STRING']))
  57.                 {
  58.                         return trim($_SERVER['QUERY_STRING'], '/');
  59.                 }
  60.         }
  61. }
  62. ?>
  63.  


default.php (конфигурация)

PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3. $config = array(
  4.         'path'     => array(
  5.                 'core'        => SITE_PATH . '/core',
  6.                 'controllers' => SITE_PATH . '/app/controllers',
  7.                 'models'     => SITE_PATH . '/app/models',
  8.                 'templates'   => SITE_PATH . '/app/templates'
  9.         ),
  10.         'database' => array()
  11. );
  12. ?>
  13.  


Controller.php

PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3. abstract class Controller
  4. {
  5.     protected $template;
  6.  
  7.         abstract function index ();
  8. }
  9. ?>
  10.  


galleryController.php

PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3. class galleryController extends Controller
  4. {
  5.         public function index () {}
  6.  
  7.         public function show ()
  8.         {
  9.         $vars = array(
  10.                         'page' => array(
  11.                                 'doctype'     => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
  12.                                 'title'       => 'Заголовок'
  13.                         )
  14.                 );
  15.  
  16.                 $this->template = new Template();
  17.                 $this->template->renderTemplate('index', $vars);
  18.         }
  19.  
  20. }
  21. ?>
  22.  


Template.php

PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP
  3. class Template
  4. {
  5.         private $path;
  6.  
  7.         public function __construct ()
  8.         {
  9.                 global $config;
  10.  
  11.                 try
  12.                 {
  13.                         if (!is_dir($config['path']['templates']))
  14.                 {
  15.                                 throw new Exception ('Неверная директория шаблонов: ' . $config['path']['templates'] );
  16.                 }
  17.                 $this->path = $config['path']['templates'];
  18.                 }
  19.                 catch (Exception $e) {}
  20.         }
  21.  
  22.         public function getTemplate ($template, $vars = array())
  23.         {
  24.                 $template_path = $this->path . '/' . $template . TEMPLATE_EXT;
  25.  
  26.                 extract($vars);
  27.  
  28.                 ob_start();
  29.                 include $template_path;
  30.  
  31.                 return ob_get_clean();
  32.         }
  33.  
  34.         public function renderTemplate ($template, $vars = array())
  35.         {
  36.                 echo $this->getTemplate($template, $vars);
  37.         }
  38. }
  39. ?>
  40.  


index.tpl.php

PHP:
скопировать код в буфер обмена
  1.  
  2. <?PHP echo $page['doctype']; ?>
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ru">
  4.     <head>
  5.                 <title><?PHP echo $page['title']; ?></title>
  6.         <meta http-equiv="content-Language" content="ru" />
  7.         <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  8.     </head>
  9.     <body>
  10.         <img src="files/pictures/php.png" title="php" width="553" height="291" />
  11.     </body>
  12. </html>
  13.  


Структура директорий такая:

/ (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)

Все тоже самое одним архивом
2. Corpsee - 04 Сентября, 2011 - 18:56:48 - перейти к сообщению
Проблема решилась заменой путей относительными от корня "/files...".

Но все равно будет интересно узнать почему относительные пути так себя ведут) Если они относительно физических файлов, то шаблон находиться в одном месте, так что, видимо от url зависит, но в таком случае не понятно почему отбрасывается последний член в цепочке, такая логика была бы уместна для "./files"...

 

Powered by ExBB FM 1.0 RC1