Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • master
1 result

Target

Select target project
  • iml-open-source/tinyrouter-php-class
1 result
Select Git revision
  • master
1 result
Show changes
Commits on Source (2)
## Copy php class file
Copy the file *tinyrouter.class.php* somewhere into your project.
In your php script reference its location, e.g.
```php
// load the class
require_once('../classes/tinyrouter.class.php');
```
## Enable pretty print url
Optional: you can redirect all incoming requests in subdir /api to the index.php that will use the router.
On Apache httpd this feature needs enabled mod_rewrite module.
```txt
<Location "/api">
Require all granted
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^api(/.*)$ index.php?request=$1
</Location>
```
Example urls:
without pretty print:
`http://localhost/api/index.php?request=/apps/12345/meta`
with pretty print:
`http://localhost/api/apps/12345/meta`
## Example
## Config
```php
// load the class
require_once('../classes/tinyrouter.class.php');
// define routes
$aRoutes=[
[ "/config", "get_config" ],
[ "/config/@var", "get_config_var" ],
[ "/apps", "listapps" ],
[ "/apps/@appid:[0-9a-f]*", "acess_appdata" ],
[ "/apps/@appid:[0-9a-f]*/@what:[a-z]*", "acess_appdata" ],
// ^ ^
// | |
// route callback (string|array|... any type you want to get back)
// string = folder
// @var = set a variable
// @var:regex = set variable if it matches the given regex
];
// take an url ... or use the request uri if you have pretty urls
$sApiUrl=isset($_GET['request']) && $_GET['request'] ? $_GET['request'] : false;
// init the class
$oRouter=new tinyrouter($aRoutes, $sApiUrl);
// it is the same like
// $oRouter=new tinyrouter();
// $oRouter->setRoutes($aRoutes);
// $oRouter->setUrl($sApiUrl);
// get the last matching route
$aFoundRoute=$oRouter->getRoute();
if(!$aFoundRoute){
header('HTTP/1.0 400 Bad request');
die('<h1>400 Bad request</h1>');
}
// ... continue
```
The getRoute() method returns an array
* request url
* request method (GET|POST|PUT|DELETE|...)
* with the matching route
* name of the callback
* vars on parts with starting @ chars
```txt
// on url /apps/12345/meta
Array
(
[request-method] => GET
[request] => /apps/12345/meta
[route] => /apps/@appid:[0-9a-f]*/@what:[a-z]*
[callback] => acess_appdata
[vars] => Array
(
[appid] => 12345
[what] => meta
)
)
```
If no route matches - or a variable did not match a required regex - then getRoute() returns *false*.
Maybe the keys of the array change in future. You can access the data with specialized getter functions:
```php
// get the fallback
$sAction=$oRouter->getCallback();
// all vars
$aAllvars=$oRouter->getVars();
// get single vars
$sAppId=$oRouter->getVar('appid');
$sWhat=$oRouter->getVar('what');
```
You can get the nth element from the request url. In our example with index 0 you
get the 1st element which can be "config" or "apps".
```php
// get 1st
$sItem=isset($oRouter->getUrlParts()[0]) ? $oRouter->getUrlParts()[0] : false;
```
With those elements you get from the router you easily cam build your switch case blocks to
execute the wanted method of your class.
\ No newline at end of file
......@@ -2,88 +2,13 @@
Axels first php class of a router.
## Installation
You can define routes static and dynamic url parts and a callback object per route.
The getRoute() method returns found route including set vars and the callback object.
In the most simple case check if a callback exists and execute it.
Copy the file *tinyrouter.class.php* somewhere into your project.
Institute for Medical Education; University of Bern
## Example
📄 Source: <https://git-repo.iml.unibe.ch/iml-open-source/tinyrouter-php-class>
📜 License: GNU GPL 3.0
📖 Docs: <https://os-docs.iml.unibe.ch/tinyrouter-php-class/>
```php
// load the class
require_once('../classes/tinyrouter.class.php');
// define routes
$aRoutes=[
[ "/config", "get_config" ],
[ "/config/@var", "get_config_var" ],
[ "/apps", "listapps" ],
[ "/apps/@appid:[0-9a-f]*", "acess_appdata" ],
[ "/apps/@appid:[0-9a-f]*/@what:[a-z]*", "acess_appdata" ],
// ^ ^
// | |
// route callback (string|array|... any type you want to get back)
// string = folder
// @var = set a variable
// @var:regex = set variable if it matches the given regex
];
// take an url ... or use the request uri if you have pretty urls
$sApiUrl=isset($_GET['request']) && $_GET['request'] ? $_GET['request'] : false;
// init the class
$oRouter=new tinyrouter($aRoutes, $sApiUrl);
// it is the same like
// $oRouter=new tinyrouter();
// $oRouter->setRoutes($aRoutes);
// $oRouter->setUrl($sApiUrl);
// get the last matching route
$aFoundRoute=$oRouter->getRoute();
if(!$aFoundRoute){
header('HTTP/1.0 400 Bad request');
die('<h1>400 Bad request</h1>');
}
// ... continue
```
The getRoute() method returns an array
* with the matching route
* name of the callback
* vars on parts with starting @ chars
```txt
// on url /apps/12345/meta
Array
(
[route] => /apps/@appid:[0-9a-f]*/@what:[a-z]*
[callback] => acess_appdata
[vars] => Array
(
[appid] => 12345
[what] => meta
)
)
```
If no route matches - or a variable did not match a required regex - then getRoute() returns *false*.
Maybe the keys of the array change in future. You can access the data with specialized getter functions:
```php
// get the fallback
$sAction=$oRouter->getCallback();
// all vars
$aAllvars=$oRouter->getVars();
// get single vars
$sAppId=$oRouter->getVar('appid');
$sWhat=$oRouter->getVar('what');
```
{
"title": "__PRODUCT__",
"title": "Tinyrouter php class",
"author": "Axel Hahn",
"tagline": "__DESCRIPTION__",
"tagline": "Simplify routing by defining routes and callback objects",
"ignore": {
"files": ["30_PHP-client/Plugins/Checks/_skeleton.md"],
"folders": ["99_Not_Ready"]
......@@ -12,12 +12,12 @@
"date_modified": false,
"jump_buttons": true,
"edit_on_github_": "iml-it/__PROJECT__/tree/master/docs",
"edit_on_": {
"edit_on": {
"name": "Gitlab",
"basepath": "https://git-repo.iml.unibe.ch/iml-open-source/__PROJECT__/tree/master/docs"
"basepath": "https://git-repo.iml.unibe.ch/iml-open-source/tinyrouter-php-class/tree/master/docs"
},
"links": {
"Git Repo": "__GITURL__"
"Git Repo": "https://git-repo.iml.unibe.ch/iml-open-source/tinyrouter-php-class"
},
"theme": "daux-blue",
"search": true
......
......@@ -24,11 +24,13 @@
*
**/
namespace iml;
class tinyrouter{
public $sUrl = '';
public $sMethod = '';
public $aRoutes = [];
public $aMatch = false;
/**
* constructor
......@@ -40,6 +42,10 @@
$this->setUrl($sUrl);
}
// ----------------------------------------------------------------------
// protected functions
// ----------------------------------------------------------------------
/**
* detect last matching route item
* if no route matches then it returns false
......@@ -87,6 +93,8 @@
}
if($bFoundRoute){
$aReturn=[
"request-method"=>(isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : false),
"request-url"=>$this->sUrl,
"route"=>$aRoutecfg[0],
"callback"=>$aRoutecfg[1],
"vars"=>$aVars
......@@ -98,9 +106,14 @@
return $this->aMatch;
}
// ----------------------------------------------------------------------
// public functions :: setter
// ----------------------------------------------------------------------
/**
* set routes
* @param array $aRoutes list of [ route, more params ... ]
* @return boolean
*/
public function setRoutes($aRoutes=[]){
if(is_array($aRoutes) && count($aRoutes)){
......@@ -112,12 +125,18 @@
/**
* set incoming url
* @param string sUrl url to fetch; https://api.exaple.com/
*/
public function setUrl($sUrl){
$this->sUrl=$sUrl;
$this->_getRoute();
return true;
}
// ----------------------------------------------------------------------
// public functions :: getter
// ----------------------------------------------------------------------
/**
* helper function: get url parts as array
* @returns array
......