PHP code example of cocoon-projet / routing

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

    

cocoon-projet / routing example snippets


use Cocoon\Routing\Router;

$router = Router::getInstance();

// Route simple
$router->get('/home', 'App\Controllers\HomeController@index');

// Route avec paramètres
$router->get('/user/{id}', 'App\Controllers\UserController@show');

// Route avec validation de paramètres
$router->get('/post/{id}', 'App\Controllers\PostController@show')
    ->with('id', '[0-9]+');

use Cocoon\Routing\Facade\Route;

// Routes simples
Route::get('/home', 'App\Controllers\HomeController@index');
Route::post('/user', 'App\Controllers\UserController@store');

// Route avec plusieurs méthodes
Route::match(['GET', 'POST'], '/api/users', 'App\Controllers\Api\UserController@handle');

// Route avec validation de paramètres
Route::get('/post/{id}', 'App\Controllers\PostController@show')
    ->with('id', '[0-9]+');

// Routes nommées
Route::get('/user/{id}', 'App\Controllers\UserController@show')
    ->name('user.show');

// Groupe de routes avec préfixe
Route::group('admin', function() {
    Route::get('/dashboard', 'App\Controllers\Admin\DashboardController@index');
    Route::get('/users', 'App\Controllers\Admin\UserController@index');
});

// Groupe avec validation de paramètres
Route::group('api', function() {
    Route::get('/users/{id}', 'App\Controllers\Api\UserController@show')
        ->with('id', '[0-9]+');
});

// Création de routes RESTful pour une ressource
Route::resource('posts', 'App\Controllers\PostController');

use Cocoon\Routing\Middleware\DispatcherMiddleware;

// Configuration du middleware
$middleware = new DispatcherMiddleware($router);

// Utilisation avec un framework PSR-15
$response = $middleware->process($request, $handler);

// Activation du cache des routes
$router->cache(true, __DIR__ . '/cache');

// Patterns prédéfinis
Route::get('/user/{id}', 'App\Controllers\UserController@show'); // {id} est automatiquement validé comme numérique

// Patterns personnalisés
Route::get('/post/{slug}', 'App\Controllers\PostController@show')
    ->with('slug', '[a-z0-9\-]+');

// Patterns multiples
Route::get('/category/{category}/post/{slug}', 'App\Controllers\PostController@show')
    ->withs([
        'category' => '[a-z]+',
        'slug' => '[a-z0-9\-]+'
    ]);