PHP code example of crazy-goat / micro-app

1. Go to this page and download the library: Download crazy-goat/micro-app 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/ */

    

crazy-goat / micro-app example snippets

 
 
# myapp.php
oApp\Attributes\Route;
use CrazyGoat\MicroApp\MicroApp;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\Response;

class HelloWorldController
{
    #[Route]
    public function handle(Request $request): Response
    {
        return new Response(body:'Hello World');
    }
}

(new MicroApp())
        ->withController(new HelloWorldController())
        ->getApplication()
        ->run();

## examples
// register route to / with GET method
#[Route] 

// register the route to /hello/{name} with the GET method.
#[Route(pattern: '/hello/{name}')]  

(new MicroApp())
        ->withController(new HelloWorldController())
        ->onEvent('onConnect', function (TcpConnection $connection) {
            echo "Client connected from {" . $connection->getRemoteIp() . ":" . $connection->getRemotePort() . "}\n";
        })
        ->getApplication()
        ->run();

class MySimpleMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        // Pre-process request
        echo "Middleware executed before controller.\n";

        $response = $next($request); // Call the next middleware or controller

        // Post-process response
        echo "Middleware executed after controller.\n";

        return $response;
    }
}

// Registering the middleware
(new MicroApp())
        ->withMiddleware(new MySimpleMiddleware(), 0)
        ->withController(new HelloWorldController())
        ->getApplication()
        ->run();
bash
php myapp.php server start --listen=127.0.0.1 --port=8081