Slim 3 Tutorial
Let's take a look at how we can use Slim 3 to write a basic web application. In this tutorial we are going to explore how to write Actions in Slim using PSR-7.
Routing is the practice of matching a URL to a system action
$app->get('/hello[/[{name}]]', function ($req, $res, $args) {
if (!empty($args['name'])) {
return $res->write('Hello ' . $args['name']);
} else {
return $res->write('Hello!');
}
});
The above code tell's slim to register a callback on the route pattern '/hello[/[{name}]]'
This route pattern mounts at /hello
and will pass anything else on into the name key on the args.
Example:
/hello/User
will outputWhy Hello User
/hello
will outputHello!
/hello/omg/wtf/bbq
is a 404 because the route doesn't match.
Slim uses nikic/FastRoute You can read more about complex route patterning at their repository
Templates [TWIG]
Let's take a look at how we can render pages/data using TWIG.
TWIG is a templating language that is php based. It provdes a operating environment that does not allow programmers much freedom. The only data that is accessible is the data that you pass into twig. This prevents you from doing lazy things like executing DB calls in your template.
Slim has it's own TWIG package.
Install it: composer require slim/twig-view
What you will need is to create a templates directory (templates
). Place the hello.twig
in that templates directory
This code is for setting up twig view, it comes from the readme of the project
In hello.twig
: Hello! {{ name }}
or insert your HTML here
This code is where the magic happens.
A brief rundown. We can access the twig renderer from the container using the key view. Which you can see we register in the container with the default config code from above. The render method requires 3 parameters. A ResponseInterface object, a template, and some data.
For more information on Slim-Twig you can read about it here
GET/POST
Let's get down to some actual useful stuff. In this section we will learn how to grab stuff from the super global $_GET
It's actually quite simple. You simply access it via the Request Object like so.
$app->get('/hiya', function ($request, $response, $args) {
$queryParams = $request->getQueryParams();
//...
}
By now I am sure you are wondering how the heck you get stuff from the infinitely more useful $_POST
... Well its pretty much the same thing.
$app->post('/hiya', function ($request, $response, $args) {
$bodyParams = $request->getParsedBody();
//...
}
REST?
Well what about PUT and DELETE?
If you are passing data in the BODY of the message you access it via getParsedBody. Again with the rules mentioned above regarding content-types!
$app->put('/hiya', function ($request, $response, $args) {
$bodyParams = $request->getParsedBody();
//...
}
PSR-7
We haven't really discussed much about the PSR-7 objects Request and Response. They are very very handy to have. Ultimately a web application receives a request, and produces a response. PSR-7 Formalizes this practice.
In particular these objects offer direct access to headers, and data by providing very convenient wrappers around accessing the raw data.
Request Object
The Request Object holds the data the user has sent the server. It is composed of the following components.
- Files - `$_FILES - Uploading Files
- Body -
$_POST
- Request Body/Parsed Request Body - Query Params -
$_GET
- Attributes
- Headers
- ServerParams -
$_SERVER
- You need to typehint ServerRequestInterface
PSR-7 offers a very easy way to grab headers.
string[] $request->headers()
or if you are looking for one in particular
string[] $request->header($name)
The observant will see that even accessing a single header will ALWAYS return an array.
The other super useful thing about the request object is its inclusion to have attributes. You might be wondering what these are for. They are for attaching meta-data to your request. This could be a User object for an authenticated session request. A transaction ID for the request. It could be Session Data ... Literally anything is possible and it is very highly useful in middleware to decorate a request. More on middleware in a minute. To access attributes:
$request = $request->withAttribute('key', 'value');
$attributes = $request->getAttributes();
$attribute = $request->getAttribute('key');
Slim actually uses attributes. You may want to get the current route object being executed. You can accomplish this by accessing it via an Attribute.
$route = $request->getAttribute('route');
Response Object
The response object contains your application's response to the request. Every action in your system should return a Response object for slim to render. If you fail to provide one the contents of the buffer will be dumped which could leak application information and should be avoided! In the response object you can write to it directly via
$response->write("Hi");
You can set the Status code:
$response = $response->withStatus(500);
Middleware
For those who are unfamiliar with the term, Middleware are functions that are applied before and after your action code. Typical use cases are for Session and Security and Logging. In Slim there are 2 types of middleware, Application and Route middleware. Application middleware is applied to all routes in your application. Very useful for logging say all internal errors.
Route Middleware
Route middleware is a more selective way of applying middleware. It is just added different. It is added to a Route or RouteGroup like so.
Example: $app->get( ... ) -> add(function ($req, $res, $next) { return $next($req, $res); });
This is very useful for securing only certain end-points. For further reading on middleware I 100% recommend giving the Slim documentation a read.