ceus-media / router
0.5.1
2024-10-24 19:59 UTC
Requires
- php: ^8.1
- ext-memcache: *
- ceus-media/cache: ^0.6 | 0.6.x-dev
- ceus-media/common: ^1.0 | 1.0.x-dev
Requires (Dev)
- ceus-media/doc-creator: ^1.0 | 1.0.x-dev
- php-parallel-lint/php-parallel-lint: *
- phpstan/phpstan: ^1
- phpstan/phpstan-strict-rules: ^1
- phpunit/phpunit: ^9.5 | ^10.1
README
PHP router for HTTP requests.
Branch for PHP 8 support.
Examples
Simplest: single JSON file
Route map as JSON file:
[
{
"controller": "Controller_Test",
"action": "test",
"pattern": "test :a (:b)",
"method": "CLI"
},
{
"controller": "Controller_Test",
"action": "test",
"pattern": "\/test\/:a\/(:b)",
"method": "GET"
}
]
As you can see, the router works for CLI and HTTP environments.
Controller class:
class Controller_Test
{
public function test( string $a = NULL, ?string $b = NULL ): string
{
return 'Called: Controller_Test::test($a, $b)' );
}
}
Router setup:
use CeusMedia\Router;
$source = Router\Registry\Source\JsonFile::create()->setResource( 'test.json' );
$registry = Router\Registry::create()->addSource( $source );
$router = Router\Router::create()->setRegistry( $registry );
Resolving a route:
$path = 'test a1 b2';
$route = $router->resolve( $path );
You could execute the resolved route controller action like this:
$result = \CeusMedia\Common\Alg\Obj\MethodFactory::staticCallClassMethod(
$route->getController(),
$route->getAction(),
[],
$route->getArguments()
);
Using multiple JSON files in a folder
$source = Router\Registry\Source\JsonFolder::create()->setResource( 'routes/' );
Using a cache on top
Invalidate cache if routes file has changed:
$invalidateCache = FALSE;
if( $invalidateCache ){
$memcache = new Memcache();
$memcache->connect( 'localhost', 11211 );
$memcache->delete( 'CeusMediaRouterCliDemo1' );
}
Setup, related to cache invalidation request:
$sourceMemcache = new Router\Registry\Source\Memcache( 'localhost:11211:CeusMediaRouterCliDemo1' );
$sourceMemcache->setOption( Router\Registry\SourceInterface::OPTION_AUTOSAVE, TRUE );
$sourceMemcache->setOption( Router\Registry\SourceInterface::OPTION_AUTOLOAD, !$invalidateCache );
...
$registry->addSource( $sourceMemcache );
$registry->addSource( $sourceJsonFile );