PHP code example of websitesql / router

1. Go to this page and download the library: Download websitesql/router 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/ */

    

websitesql / router example snippets


use WebsiteSQL\Router\Router;
use WebsiteSQL\Router\Container;
use WebsiteSQL\Router\Strategy\ApiStrategy;
use WebsiteSQL\Router\Factory\ResponseFactory;

// Create container & router
$router = new Router();
$container = new Container();

// Create the strategy
$responseFactory = new ResponseFactory();
$strategy = new ApiStrategy($responseFactory);
$strategy->setContainer($container);
$strategy->setCorsOptions([
	'origin' => ['https://example.com'],
	'methods' => ['GET', 'POST', 'PUT', 'DELETE'],
	'headers.allow' => ['Content-Type', 'Authorization'],
	'headers.expose' => ['Etag'],
	'credentials' => true,
	'cache' => 86400
]);
$router->setStrategy($strategy);

// Define routes
$router->get('/users', 'UserController::listUsers');
$router->post('/users', 'UserController::createUser');

// Dispatch the request
$response = $router->dispatch($request);

// Example controller using ApiStrategy
public function getUser(ServerRequestInterface $request): array
{
    $userId = $request->getAttribute('id');
    $user = $this->userRepository->find($userId);
    
    // Return data as array - ApiStrategy will convert to proper response
    return ['data' => $user];
}

use WebsiteSQL\Router\Strategy\ApiStrategy;

$strategy = new ApiStrategy();
$strategy->setContainer($container);

// Configure CORS 
$strategy->setCorsOptions([
    'origin' => ['https://example.com'],
    'methods' => ['GET', 'POST', 'PUT', 'DELETE'],
    'headers.allow' => ['Content-Type', 'Authorization'],
    'headers.expose' => ['Etag'],
    'credentials' => true,
    'cache' => 86400
]);

$router->setStrategy($strategy);