PHP code example of thewunder / croute

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

    

thewunder / croute example snippets


$router = Router::create($eventDispatcher, ['Your\\Controller\\Namespace'], $container, [$dependency1, $dependency2]);
$router->route($request);

namespace Your\Controller\Namespace

class IndexController extends Croute\Controller
{
    public function __construct($dependency1, $dependency2)
    {
        //...
    }

    /**
     * Will be available at http://yourdomain/
     * and  testAction()
    {
        return new Response('Test Action');
    }
}

    #[HttpMethod('POST')]
    public function saveAction()

#[Secure]
class IndexController extends Controller
{

#[\Attribute(\Attribute::TARGET_CLASS|\Attribute::TARGET_METHOD)]
class MyAttribute implements RoutingAttribute
{
    public function __construct(public string $option)
    {}
}


class MyAttributeHandler extends BasicAttributeHandler
{
    public function getAttributeClass(): string
    {
        return MyAttribute::class;
    }

    public function handleRequest(MyAttribute|RoutingAttribute $attribute, Request $request): ?Response 
    {
        // Return a response will immediately return that response, bypassing the normal controller action
        if ($attribute->option == 'teapot') {
            return new Response("I'm a teapot", Response::HTTP_I_AM_A_TEAPOT);
        }
        return null;
    }
}



$router->addAttributeHandler(new MyAttributeHandler());


    public function myListener(ControllerLoadedEvent $event)
    {
        $event->setResponse(new Response('PermissionDenied', 403));
    }