PHP Classes

Dframe PHP Router Configuration Generator: Generate configuration files for routing requests

Recommend this page to a friend!
  Info   View files Documentation   View files View files (10)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog (1)    
Last Updated Ratings Unique User Downloads Download Rankings
2022-01-30 (13 days ago) RSS 2.0 feedNot yet rated by the usersTotal: 102 This week: 1All time: 9,529 This week: 161Up
Version License PHP version Categories
dframe-router 4.1.7The PHP License7PHP 5, Code Generation, Configuration, P...
Description Author

This package can generate configuration files for routing requests.

It loads a configuration file with definitions about project details.

The package can scan the configured controllers directory to find controller class files to be scanned in order to generate router configuration PHP script files automatically.

Innovation Award
PHP Programming Innovation award nominee
October 2020
Number 3
MVC based applications can process HTTP requests by routing the requests to controller classes that can perform the desired actions and return the responses.

This package can simplify the configuration of application routing by scanning controller class files to extract the possible actions that they can perform. Then it can generate updated configuration files to define how requests are routed.

Manuel Lemos
Picture of Slawomir Kaleta
  Performance   Level  
Name: Slawomir Kaleta <contact>
Classes: 15 packages by
Country: Poland Poland
Innovation award
Innovation award
Nominee: 3x

Winner: 1x

Details

Dframe/Router - Component

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

php framework dframe logo

Documentation - Router PHP

Composer

$ composer require dframe/router

Simple PHP Router

Creating an application, it's worth taking care of their friendly links. Its has a big part in position in SEO. Link router work in a similar way as network router. It is responsible for calling the method from controller.


$this->router->addRoute([
'page/:method' => [
'page/[method]/',
'task=page&action=[method]'
]
]);
$this->router->makeUrl('page/:action?action=index'); // Return: https://example.php/page/index
$this->router->isActive('page/:action?action=index'); // Current Website true/false

Configuration

We define the table with adresses for our application in the configuration file

  • |https| - true/false forcing https
  • |NAME_CONTROLLER| - Name of the default controller
  • |NAME_METHOD| - Name of the default method from the controller in NAME_CONTROLLER
  • |publicWeb| - Main folder from which files will be read (js, css)
  • |assetsPath| - Dynamic folder
  • |docs/docsId| - Example routing with the |docsId| variable, which contains the |docs/[docsId]/| adress definition and the |task| parameters to which it's assigned.
  • |error/404| - as above
  • |default| - default definition loading the controller/method. |params| defines the possibility of additional parameters appearing, while
'_params' => [
'[name]/[value]/',
'[name]=[value]'
]

defines the way the additional foo=bar parameters should be interpreted.

Config/router.php

 
 return [
     'https' => false,
     'NAME_CONTROLLER' => 'page',    // Default Controller for router
     'NAME_METHOD' => 'index',       // Default Action for router
     'publicWeb' => '',              // Path for public web (web or public_html)
 
     'assets' => [
         'minifyCssEnabled' => true,
         'minifyJsEnabled' => true,
         'assetsDir' => 'assets',
         'assetsPath' => APP_DIR.'View/',
         'cacheDir' => 'cache',
         'cachePath' => APP_DIR.'../web/',
         'cacheUrl' => HTTP_HOST.'/',
     ],
 
     'routes' => [
         'docs/:pageId' => [
             'docs/[pageId]/', 
             'task=page&action=[docsId]&type=docs'
         ],
         
         'error/:code' => [
             'error/[code]/', 
             'task=page&action=error&type=[code]',
             'code' => '([0-9]+)',
             'args' => [
                 'code' => '[code]'
             ],
         ],
         
        ':task/:action' => [
            '[task]/[action]/[params]',
            'task=[task]&action=[action]',
            'params' => '(.*)',
            '_params' => [
                '[name]/[value]/',
                '[name]=[value]'
            ]
        ],

         'default' => [
             '[task]/[action]/[params]',
             'task=[task]&action=[action]',
             'params' => '(.*)',
             '_params' => [
                 '[name]/[value]/', 
                 '[name]=[value]'
             ]
         ]
     ] 
 
 ];

Controller

- makeUrl - is used for generating the full adress. For example |makeurl| - method used for redirections, equivalent of |header| but with a parameter being a key from the Config/router.php table. In case of using docs/:docsld it looks as the following |redirect|

Controller/Page.php

 namespace Controller;
 
 use Dframe\Controller;
 use Dframe\Router\Response;
 
 class PageController extends Controller
 {
 
     /
      * @return bool
      */
     public function index()
     {
         echo $this->router->makeUrl('docs/:docsId?docsId=23');
         return;
     }
 
     /
      * @return mixed
      */
     public function docs()
     {
 
         if (!isset($_GET['docsId'])) {
             return $this->router->redirect('error/:code?code=404');
         }
     }
 
     /
      * @param string $status
      *
      * @return mixed
      */
     public function error($status = '404')
     {
         $routerCodes = $this->router->response();
 
         if (!array_key_exists($status, $routerCodes::$code)) {
             return $this->router->redirect('error/:code?code=500');
         }
 
         $view = $this->loadView('index');
         $smartyConfig = Config::load('view/smarty');
 
         $patchController = $smartyConfig->get('setTemplateDir', APP_DIR . 'View/templates') . '/errors/' . htmlspecialchars($status) . $smartyConfig->get('fileExtension', '.html.php');
 
         if (!file_exists($patchController)) {
             return $this->router->redirect('error/:code?code=404');
         }
 
         $view->assign('error', $routerCodes::$code[$status]);
         return Response::create($view->fetch('errors/' . htmlspecialchars($status)))->headers(['refresh' => '4;' . $this->router->makeUrl(':task/:action?task=page&action=index')]);
     }
 
 }

View

assign - it's a method of the template engine that assignes value to a variable which is used in the template files.

View/templates/index.html.php

https://

Using only PHP

  • |router| all already available methods used like in |page/index|

View/index.php

namespace View;

use Dframe\Asset\Assetic;

class IndexView extends \View\View
{

     /
      * @return bool
      */
     public function init()
     {
         $this->router->assetic = new Assetic();
         $this->assign('router', $this->router);
     }
}

Dframe\Router\Response;

Extention of the basic Dframe\Router is Dframe\Router\Response, adding functionality of setting the response status (404, 500, etc.) and their headers.

return Response::create('Hello Word!')
    ->status(200)
    ->headers([
                  'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
                  'Cache-Control' => 'no-cache',
                  'Pragma',
                  'no-cache'
              ]);

For generating html.

Render json

return Response::renderJSON(['code' => 200, 'data' => []]);

Render json with callback

return Response::renderJSONP(['code' => 200, 'data' => []]);

Redirect

return Response::redirect(':task/:action?task=page&action=login');
  Files folder image Files  
File Role Description
Files folder imageExceptions (3 files)
Files folder imageTests (2 files)
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation
Plain text file Request.php Class Class source
Plain text file Response.php Class Class source
Plain text file Router.php Class Class source

  Files folder image Files  /  Exceptions  
File Role Description
  Plain text file InvalidArgumentException.php Class Class source
  Plain text file RouterException.php Class Class source
  Plain text file RuntimeException.php Class Class source

  Files folder image Files  /  Tests  
File Role Description
  Plain text file ResponseTest.php Class Class source
  Plain text file RouterTest.php Class Class source

 Version Control Unique User Downloads Download Rankings  
 100%
Total:102
This week:1
All time:9,529
This week:161Up
For more information send a message to info at phpclasses dot org.