composer require aloefflerj/yet-another-controller
-
Simple Setup
index.php
<?php declare(strict_types=1); use Aloefflerj\YetAnotherController\Controller\Controller; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; require_once '/vendor/autoload.php'; $controller = new Controller('http://localhost:8000');
-
Adding a simple GET route
index.php
$controller->get('/', function (RequestInterface $request, ResponseInterface $response) { $response->getBody()->write('Welcome home'); return $response->getBody(); });
-
Dispatching routes
index.php
$controller->dispatch();
-
Start your webserver
A simple way to do it would be with the PHP built-in web server:
Run
php -S localhost:8000 -t path/to/your/index
-
Go to your domain home page
http://localhost:8000/
outputs: 'Welcome home'
The $request
and $response
arguments on closure
output are PSR-7 implementations.
The return of the closure
must be a StreamInterface
implementation for the output to work.
$controller->get('/', function (RequestInterface $request, ResponseInterface $response) {
$response->getBody()->write('Welcome home');
return $response->getBody();
});
Since the return of $response->getBody()
is a StreamInterface
implementation the code above will print:
outputs: 'Welcome home'
Alternatively you could simply do echo $response->getBody();
You can pass uri params wiht the syntax /route/{param}
.
For the param
to be accessed, you need a third param on get
method: \stdClass $args
.
To access it inside the closure
output, you must use $args->param
. See the example below:
$controller->get('/mascots/{mascot}', function (RequestInterface $request, ResponseInterface $response, \stdClass $args) {
$response->getBody()->write("PHP {$args->mascot} mascot is awesome");
return $response->getBody();
});
url: localhost:8000/mascots/elephant
outputs: 'PHP elephant mascot is awesome'
To get the body from a request you can access it from the $request
implementation with $request->getBody()
(a StreamInterface
implementation).
The example below will print the request body.
$controller->put('/mascot', function (RequestInterface $request, ResponseInterface $response) {
$requestBody = $request->getBody();
return $requestBody;
});
If I request a POST with the following body:
{
"mascots": [
{
"lang": "php",
"mascot": "elephant"
},
{
"lang": "go",
"mascot": "gopher"
}
]
}
The return should be the same:
{
"mascots": [
{
"lang": "php",
"mascot": "elephant"
},
{
"lang": "go",
"mascot": "gopher"
}
]
}