1. Go to this page and download the library: Download awesomite/chariot 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/ */
use Awesomite\Chariot\Pattern\PatternRouter;
class RouterFactory
{
private $cacheFile;
public function __construct(string $cacheFile)
{
$this->cacheFile = $cacheFile;
}
public function rebuildRouter()
{
$router = $this->createRouter();
file_put_contents($this->cacheFile, ' return ' . $router->exportToExecutable() . ';');
}
public function getRouter(): PatternRouter
{
return ();
// decorators are not cacheable, you must add them each time
// $router->addParamDecorator(new MyParamDecorator());
use Awesomite\Chariot\Pattern\PatternInterface;
use Awesomite\Chariot\Pattern\PatternRouter;
use Awesomite\Chariot\Pattern\Patterns;
use Awesomite\Chariot\Pattern\StdPatterns\DatePattern;
$router = new PatternRouter(new Patterns());
/*
* Passed object to method addPattern() must implement interface PatternInterface
*/
$router->getPatterns()->addPattern(':date', new DatePattern());
$router->get('/day/{{ day :date }}', 'showDay');
echo $router->linkTo('showDay')->withParam('day', new \DateTime('2017-07-07')), "\n";
/*
* Output:
* /day/2017-07-07
*/
use Awesomite\Chariot\ParamDecorators\ParamDecoratorInterface;
use Awesomite\Chariot\Pattern\PatternRouter;
use Awesomite\Chariot\ParamDecorators\ContextInterface;
class TitleProvider implements ParamDecoratorInterface
{
private $mapping;
public function __construct(array $mapping)
{
$this->mapping = $mapping;
}
public function decorate(ContextInterface $context)
{
if ('showItem' !== $context->getHandler()) {
return;
}
$id = $context->getParams()['id'] ?? null;
$title = $this->mapping[$id] ?? null;
if (null !== $title) {
$context->setParam('title', $title);
}
}
}
$titleMapping = [
1 => 'my-first-item',
2 => 'my-second-item',
3 => 'my-third-item',
];
$router = PatternRouter::createDefault();
$router->get('/items/{{ id :int }}-{{ title }}', 'showItem');
/*
* Error, because title is not defined
*/
echo 'Without provider: ';
echo $router->linkTo('showItem')->withParam('id', 1), PHP_EOL;
/*
* Valid URL, because title will be provided automatically
*/
$router->addParamDecorator(new TitleProvider($titleMapping));
echo 'With provider: ';
echo $router->linkTo('showItem')->withParam('id', 1), PHP_EOL;
/*
* Output:
*
* Without provider: __ERROR_CANNOT_GENERATE_LINK
* With provider: /items/1-my-first-item
*/