1. Go to this page and download the library: Download tobento/service-routing library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
tobento / service-routing example snippets
use Tobento\Service\Routing\Router;
use Tobento\Service\Routing\RequestData;
use Tobento\Service\Routing\UrlGenerator;
use Tobento\Service\Routing\RouteFactory;
use Tobento\Service\Routing\RouteDispatcher;
use Tobento\Service\Routing\Constrainer\Constrainer;
use Tobento\Service\Routing\RouteHandler;
use Tobento\Service\Routing\MatchedRouteHandler;
use Tobento\Service\Routing\RouteResponseParser;
// Any PSR-11 container
$container = new \Tobento\Service\Container\Container();
$router = new Router(
new RequestData(
$_SERVER['REQUEST_METHOD'] ?? 'GET',
rawurldecode($_SERVER['REQUEST_URI'] ?? ''),
'example.com',
),
new UrlGenerator(
'https://example.com/basepath',
'a-random-32-character-secret-signature-key',
),
new RouteFactory(),
new RouteDispatcher($container, new Constrainer()),
new RouteHandler($container),
new MatchedRouteHandler($container),
new RouteResponseParser(),
);
$router->setBaseUri('/path/app/');
$router->get('blog/{slug}', 'Controller::method');
// you can define as many as you want:
$router->get('blog/{slug}/comment/{id}', 'Controller::method');
// using a question mark for optional parameters
$router->get('{?locale}/blog/{?id}', 'Controller::method');
// or using wildcard to allow any path
$router->get('blog/{path*}', 'Controller::method');
// By providing class and method name:
$router->get('blog', [Controller::class, 'method']);
$router->get('blog', [new Controller(), 'method']);
$router->get('blog', Controller::class); // __invoke method called
// Using Class::method syntax:
$router->get('blog', 'Controller::method');
// Using closure:
$router->get('blog', function() {
return 'welcome';
});
// You might provide data for build-in method parameters:
$router->get('blog', [Controller::class, 'method', ['name' => 'value']]);
// do not allow any uri query parameters:
$router->get('blog/{slug}', 'Controller::method')->query(null);
// allow only certain query characters:
$router->get('blog/{slug}', 'Controller::method')->query('/^[a-zA-Z0-9=&\/,\[\]-]+?$/');
$router->get('blog', [Controller::class, 'method'])
->name('blog');
$blogUrl = $router->url('blog')->get();
$blogUrl = (string) $router->url('blog');
// if your route uri has parameters:
$router->get('blog/edit/{id}', [Controller::class, 'method'])
->name('blog.edit');
$blogUrl = $router->url('blog.edit', ['id' => 5])->get();
use Tobento\Service\Routing\RouteInterface;
// must implement RouteInterface
$router->addRoute(new CustomRoute());
$router->addRoutes([
new CustomRoute(),
new CustomRoute(),
]);
use Tobento\Service\Routing\RouteInterface;
$routes = $router->getRoutes();
// returns: array<int|string, RouteInterface>
use Tobento\Service\Routing\RouteInterface;
$route = $router->getRoute('name');
// returns: null|RouteInterface
use Tobento\Service\Routing\RouteInterface;
$matchedRoute = $router->getMatchedRoute();
// returns: null|RouteInterface
use Tobento\Service\Routing\RouteGroupInterface;
$router->group('admin', function(RouteGroupInterface $group) {
// supports any basic routing methods:
$group->get('blog', [Controller::class, 'method'])->name('admin.blog');
// resources:
$group->resource('products', ProductsController::class);
// The group uri 'admin' gets prepended to route names for resources only.
// $router->getRoute('admin.products.index');
// $router->url('admin.products.index');
// group:
$group->group('account', function(RouteGroupInterface $group) {
// define routes.
});
// you might overwrite the group parameters by defining it:
$group->get('blog', [Controller::class, 'method'])
->middleware(Middleware::class);
})->domain('sub.example.com')
->middleware(Middleware::class)
->baseUrl('sub.example.com')
->parameter('name', 'value')
->locale('de')
->locales(['de', 'en'])
->localeOmit('de')
->localeName('locale')
->localeFallbacks(['de' => 'en']);
use Tobento\Service\Routing\RouteGroupInterface;
$router->group('{locale}', function(RouteGroupInterface $group) {
// locale is available too.
$group->get('blog/{id}', function($locale, $id) {
// do something
});
})->where('locale', ':in:de:fr');
use Tobento\Service\Routing\RouteInterface;
$router->get('{?locale}/{about}', function($locale, $about) {
return [$locale, $about];
})
->name('about')
// default parameters will be used if not specified on domain:
->trans('about', ['de' => 'ueber-uns', 'en' => 'about', 'fr' => 'se-presente'])
->domain('example.ch', function(RouteInterface $route): void {
$route->locales(['de', 'fr'])
->localeOmit('de')
->localeFallbacks(['fr' => 'de'])
->trans('about', ['de' => 'ueber-uns', 'fr' => 'se-presente']);
})->domain('example.de', function(RouteInterface $route): void {
$route->locales(['de', 'en'])
->localeOmit('de')
->localeFallbacks(['en' => 'de']);
});
$router->get('blog', [Controller::class, 'method'])
->name('blog')
->domain('example.ch')
->domain('example.de');
// current domain url:
$url = $router->url('blog');
// get specific domain url:
$url = $router->url('blog')->domain('example.de');
// get all domained urls:
$urls = $router->url('blog')->domained();
/*[
'example.ch' => 'https://example.ch/blog',
'example.de' => 'https://example.de/blog',
]*/
// you may get all translated urls from current or specific domain:
$urls = $router->url('blog')->translated();
$urls = $router->url('blog')->domain('example.de')->translated();
use Tobento\Service\Routing\Router;
use Tobento\Service\Routing\RequestData;
use Tobento\Service\Routing\UrlGenerator;
use Tobento\Service\Routing\RouteFactory;
use Tobento\Service\Routing\RouteDispatcher;
use Tobento\Service\Routing\Constrainer\Constrainer;
use Tobento\Service\Routing\RouteHandler;
use Tobento\Service\Routing\MatchedRouteHandler;
use Tobento\Service\Routing\RouteResponseParser;
use Tobento\Service\Routing\Domains;
use Tobento\Service\Routing\Domain;
// Any PSR-11 container
$container = new \Tobento\Service\Container\Container();
// Domains
$domains = new Domains(
new Domain(key: 'example.ch', domain: 'ch.localhost', uri: 'http://ch.localhost'),
new Domain(key: 'example.de', domain: 'de.localhost', uri: 'http://de.localhost'),
);
$router = new Router(
new RequestData(
$_SERVER['REQUEST_METHOD'] ?? 'GET',
rawurldecode($_SERVER['REQUEST_URI'] ?? ''),
'ch.localhost',
),
new UrlGenerator(
'https://example.com/basepath',
'a-random-32-character-secret-signature-key',
),
new RouteFactory($domains), // pass domains
new RouteDispatcher($container, new Constrainer()),
new RouteHandler($container),
new MatchedRouteHandler($container),
new RouteResponseParser(),
);
// Adding Routes:
// Set the domain name as the key specified above:
$router->get('blog', [Controller::class, 'method'])
->domain('example.ch')
->domain('example.de');
use Tobento\Service\Dater\Dater;
$router->get('unsubscribe/{user}', [Controller::class, 'method'])
->signed('unsubscribe');
// generate a signed url with no expiring.
$url = (string) $router->url('unsubscribe', ['user' => 5])->sign();
// https://example.com/basepath/unsubscribe/5/a0df83344703b26cd1f9cdcb05196082a6a7799e84b4748a5610d3256b556c55
// generate a signed url which expires in 10 days.
$url = (string) $router->url('unsubscribe', ['user' => 5])->sign((new Dater())->addDays(10));
// https://example.com/basepath/unsubscribe/5/a0df83344703b26cd1f9cdcb05196082a6a7799e84b4748a5610d3256b556c55/1630752459
// generate a signed url with no expiring and add signature data as query parameters.
$url = (string) $router->url('unsubscribe', ['user' => 5])->sign(withQuery: true);
// https://example.com/basepath/unsubscribe/5?signature=6d632a4a8981b1fb017ad6f82067370d6c98ddcd8c6d18cb4fc30c1d44e0f67e
// generate a signed url which expires in 10 days and add signature data as query parameters.
$url = (string) $router->url('unsubscribe', ['user' => 5])->sign((new Dater())->addDays(10), true);
// https://example.com/basepath/unsubscribe/5?expires=1630752540&signature=6d632a4a8981b1fb017ad6f82067370d6c98ddcd8c6d18cb4fc30c1d44e0f67e
$router->get('{?locale}/about', [Controller::class, 'method'])
->name('about');
// get current locale url:
$url = (string) $router->url('about');
// https://example.com/basepath/about
// get specific locale url:
$url = (string) $router->url('about')->locale('en');
// https://example.com/basepath/en/about
// get all translated urls:
$urls = $router->url('about')->translated();
/*[]*/
// get/create specific translated urls:
$urls = $router->url('about')->translated(['de', 'fr']);
/*[
'de' => 'https://example.com/basepath/de/about',
'fr' => 'https://example.com/basepath/fr/about',
]*/
$router->get('{?locale}/about', [Controller::class, 'method'])
->name('about')
->locales(['de', 'en']); // the supported locales, MUST be called before any other locale methods.
// get current locale url:
$url = (string) $router->url('about');
// https://example.com/basepath/about
// get specific locale url:
$url = (string) $router->url('about')->locale('en');
// https://example.com/basepath/en/about
// get all translated urls:
$urls = $router->url('about')->translated();
/*[
'de' => 'https://example.com/basepath/de/about',
'en' => 'https://example.com/basepath/en/about',
]*/
// get/create specific translated urls:
$urls = $router->url('about')->translated(['de', 'fr']);
/*[
'de' => 'https://example.com/basepath/about',
'fr' => 'https://example.com/basepath/fr/about',
]*/
$router->get('{?locale}/about', [Controller::class, 'method'])
->name('about')
->locales(['de', 'en'])
->localeOmit('en');
// get current locale url:
$url = (string) $router->url('about');
// https://example.com/basepath/about
// get specific locale url:
$url = (string) $router->url('about')->locale('en');
// https://example.com/basepath/about
// get all translated urls:
$urls = $router->url('about')->translated();
/*[
'de' => 'https://example.com/basepath/de/about',
'en' => 'https://example.com/basepath/about',
]*/
$router->get('{locale}/about', [Controller::class, 'method'])
->name('about')
->locale('en');
// get current locale url:
$url = (string) $router->url('about');
// https://example.com/basepath/en/about
// get specific locale url:
$url = (string) $router->url('about')->locale('de');
// https://example.com/basepath/de/about
// get all translated urls:
$urls = $router->url('about')->translated();
/*[
'en' => 'https://example.com/basepath/en/about',
]*/
$router->get('{?loc}/about', [Controller::class, 'method'])
->name('about')
->localeName('loc'); // the locale uri definition name, 'locale' is the default name
$router->get('/{about}', [Controller::class, 'method'])
->name('about')
->locale('de') // set the current locale.
->trans('about', ['de' => 'ueber-uns', 'en' => 'about']);
// get current locale url:
$url = (string) $router->url('about');
// https://example.com/basepath/ueber-uns
// get specific locale url:
$url = (string) $router->url('about')->locale('en');
// https://example.com/basepath/about
// get all translated urls:
$urls = $router->url('about')->translated();
/*[
'de' => 'https://example.com/basepath/ueber-uns',
'en' => 'https://example.com/basepath/about',
]*/
$router->get('/{about}', [Controller::class, 'method'])
->name('about')
->locales(['en']) // the supported locales, MUST be called before any other locale methods.
->locale('de') // set the current locale.
->trans('about', ['de' => 'ueber-uns', 'en' => 'about']);
// get current locale url:
$url = (string) $router->url('about');
// https://example.com/basepath/ueber-uns
// get specific locale url:
$url = (string) $router->url('about')->locale('en');
// https://example.com/basepath/about
// get all translated urls:
$urls = $router->url('about')->translated();
/*[
'en' => 'https://example.com/basepath/about',
]*/
$router->get('/{about}', [Controller::class, 'method'])
->name('about')
->locales(['en', 'de', 'fr'])
->localeFallbacks(['fr' => 'en'])
->locale('de') // set the current locale.
->trans('about', ['de' => 'ueber-uns', 'en' => 'about']);
// get current locale url:
$url = (string) $router->url('about');
// https://example.com/basepath/ueber-uns
// get specific locale url:
$url = (string) $router->url('about')->locale('fr');
// https://example.com/basepath/about
// get all translated urls:
$urls = $router->url('about')->translated();
/*[
'en' => 'https://example.com/basepath/about',
'de' => 'https://example.com/basepath/ueber-uns',
'fr' => 'https://example.com/basepath/about',
]*/
$router->get('{?locale}/{about}', [Controller::class, 'method'])
->name('about')
->localeOmit('en')
->trans('about', ['de' => 'ueber-uns', 'en' => 'about']);
// get current locale url:
$url = (string) $router->url('about');
// https://example.com/basepath/about
// get specific locale url:
$url = (string) $router->url('about')->locale('de');
// https://example.com/basepath/de/ueber-uns
// get all translated urls:
$urls = $router->url('about')->translated();
/*[
'de' => 'https://example.com/basepath/de/ueber-uns',
'en' => 'https://example.com/basepath/about',
]*/
$router->get('/{about}', [Controller::class, 'method'])
->name('about')
->locale('de') // set the current locale.
->trans('about', ['de' => 'ueber-uns', 'en' => 'about']);
$url = (string) $router->url('about', ['locale' => 'de', 'about' => 'ueberuns'])->locale('en');
// https://example.com/basepath/ueberuns
$router->get('blog/edit', [Controller::class, 'method'])->name('blog.edit');
$router->matched('blog.edit', function() {
// do something after the route has been matched.
});
// instead of:
$router->get('blog/{word}', 'Controller::method')
->where('word', '(foo|bar)');
// you can use a rule:
$router->get('blog/{word}', 'Controller::method')
->where('word', ':in:foo:bar');
// using rule with array syntax.
$router->get('blog/{word}', 'Controller::method')
->where('word', ['in', 'foo', 'bar']);
// rule with regex:
$router->getRouteDispatcher()
->rule('slug')
->regex('[a-z0-9-]+');
// rule with regex closure:
$router->getRouteDispatcher()
->rule('slug')
->regex(function(array $parameters): null|string {
// build the regex based on the parameters
});
// rule with matches:
$router->getRouteDispatcher()
->rule('slug')
->matches(function(string $value, array $parameters): bool {
// handle
});
// or by adding a rule.
$router->getRouteDispatcher()->addRule('slug', new SlugRule());
use Tobento\Service\Routing\RouteNotFoundException;
use Tobento\Service\Routing\InvalidSignatureException;
use Tobento\Service\Routing\TranslationException;
try {
$matchedRoute = $router->dispatch();
} catch (RouteNotFoundException $e) {
// handle exception
} catch (InvalidSignatureException $e) {
// handle exception
} catch (TranslationException $e) {
// handle exception
}
// call matched route handler for handling registered matched event actions.
$router->getMatchedRouteHandler()->handle($matchedRoute);
// handle the matched route.
$routeResponse = $router->getRouteHandler()->handle($matchedRoute);
// create response.
$response = (new \Nyholm\Psr7\Factory\Psr17Factory())->createResponse(200);
// parse the route response.
$response = $router->getRouteResponseParser()->parse($response, $routeResponse);
// emitting response.
(new \Laminas\HttpHandlerRunner\Emitter\SapiEmitter())->emit($response);
use Tobento\Service\Middleware\MiddlewareDispatcherInterface;
use Tobento\Service\Middleware\MiddlewareDispatcher;
use Tobento\Service\Middleware\AutowiringMiddlewareFactory;
use Tobento\Service\Middleware\FallbackHandler;
// adjust route parameters passed to the request attributes if needed:
$router->setRequestAttributes(['uri', 'name', 'request_uri']);
// After PreRouting or Routing Middleware: $request->getAttribute('route.name');
// Middleware Handling:
$container->set(MiddlewareDispatcherInterface::class, function($container) {
return new MiddlewareDispatcher(
new FallbackHandler((new \Nyholm\Psr7\Factory\Psr17Factory())->createResponse(200)),
new AutowiringMiddlewareFactory($container)
);
});
$middlewareDispatcher = $container->get(MiddlewareDispatcherInterface::class);
// add MethodOverride middleware if needed.
$middlewareDispatcher->add(\Tobento\Service\Routing\Middleware\MethodOverride::class);
// add PreRouting middleware if needed.
$middlewareDispatcher->add(\Tobento\Service\Routing\Middleware\PreRouting::class);
// ... more middlewares
$middlewareDispatcher->add(\Tobento\Service\Routing\Middleware\Routing::class);
$request = (new \Nyholm\Psr7\Factory\Psr17Factory())->createServerRequest('GET', 'https://example.com');
$response = $middlewareDispatcher->handle($request);
// emitting response.
(new \Laminas\HttpHandlerRunner\Emitter\SapiEmitter())->emit($response);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.