Facebook
From Ivory Crocodile, 6 Years ago, written in PHP.
Embed
Download Paste or View Raw
Hits: 247
  1. <?php
  2. class Router
  3. {
  4.     private $customPath;
  5.     private $url;
  6.     private $pages;
  7.     private $pageError;
  8.     private $status;
  9.     private function __construct($pages, $pageError,$customPath) {
  10.         $this->url = explode('?', $_SERVER['REQUEST_URI'], 2);
  11.         $this->customPath = $customPath;
  12.         $this->pages = $pages;
  13.         $this->pageError = $pageError;
  14.         $this->status = false;
  15.     }
  16.     public function render() {
  17.         foreach ( $this->pages as $key => $page ) {
  18.             if( $this->url[0] === $this->customPath.$page['url'] ) {
  19.                 if( isset( $page['load'] ) ) {
  20.                     if( file_exists( $page['load'] ) ) {
  21.                         require $page['load'];
  22.                     }
  23.                     else {
  24.                         echo 'Error loading add-ons';
  25.                     }
  26.                 }
  27.                 if(isset($page['view']) ) {
  28.                     if( file_exists( $page['view'] ) ) {
  29.                         require $page['view'];
  30.                     }
  31.                     else {
  32.                         echo 'View loading error!';
  33.                     }
  34.                 }
  35.                 $this->status = true;
  36.                 break;
  37.             }
  38.         }
  39.         if( !$this->status ) {
  40.             require $this->pageError;
  41.         }
  42.     }
  43.     public static function getInstance($config) {
  44.         $pages = $config['views'];
  45.         $pageError = $config['pageError'];
  46.         $customPath = $config['customPath'];
  47.         $instance = new self($pages,$pageError,$customPath);
  48.         return $instance;
  49.     }
  50. }
  51. ?>
  52.  
  53.  
  54. <?php
  55. return array(
  56.     'views' => [
  57.         [
  58.             'url' => '/',
  59.             'view' => 'views/home.php',
  60.             'load' => 'php/test.php'
  61.         ],
  62.         [
  63.             'url' => '/panel',
  64.             'view' => 'views/panel.php',
  65.             'load' => 'php/test.php'
  66.         ]
  67.     ],
  68.     'pageError' => 'views/404.php',
  69.     'customPath' => '/public'
  70. )
  71. ?>