Как организовать Router php

Рейтинг: 6Ответов: 1Опубликовано: 12.11.2014

Подскажите алгоритм, этапы, как лучше сделать такую систему роутинга. Читал много про роутинг но, там все как-то просто реализовано было, без регистрации их. Пытался разобрать framework-и, но все как-то сложно сделано.

Подскажите, с чего начать, или посоветуйте похожую уже готовую систему.

P.S. Прошу не ругать за свой велосипед будущий. :)

Настройки роутеров записаны в следующем виде:

 <?php
    return array(
    'home' => array(
       'pattern' => '/',
       'controller' => 'Blog\\Controller\\IndexController',
       'action' => 'index'
    ),
    'hello' => array(
      'pattern' => '/',
      'controller' => 'Blog\\Controller\\HelloController',
      'action' => 'index'
    ),
    'show_post' => array(
      'pattern' => '/posts/{id}',
      'controller' => 'Blog\\Controller\\PostController',
      'action' => 'show',
      '_requirements' => array(
        'id' => '\d+'
      )
    ),
 );

 class Router{
   private $registry;
   private $path;
   private $args = array();

   function __construct($registry){//  список всех роутеров
     $this->registry = $registry;
   }

}

Ответы

▲ 1

Вам нужно использовать spl_autoload_register. Проще говоря, автозагрузка классов. Выглядеть это должно примерно, вот так: spl_autoload_register("autoloader");

function autoloader($class) {
$dirs = array(
'controllers/',
'models/',
'core/'
);

$class = strtolower($class);
foreach ($dirs as $location) {
if(file_exists(__DIR__.'/'.$location.$class.'.php')){
require_once(__DIR__.'/'.$location.$class.'.php');
break;
}
}
}

А дальше, через route, делайте проверки..