This tutorial is out of date and no longer maintained.
Just like the world of JavaScript, in the world of PHP, we have a fairly large amount of frameworks and libraries. We could go on all day listing PHP libraries and still not finish in time for Christmas.
But there are some libraries that separate themselves from the chaff, one such example is the Laravel PHP framework.
Another framework that sets itself apart is SLIM.
Taking it straight from the horse’s mouth:
Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.
Emphasis on “micro” and “APIs”. SLIM is not robust with lots of features, what makes it so good is the fact that it creates room for extensibility, thus kinda obeying the Open-closed principle.
At its core, Slim is a dispatcher that receives an HTTP request, invokes an appropriate callback routine, and returns an HTTP response. That’s it.
The fact that SLIM doesn’t come with many dependencies makes it one of the best frameworks out there when it comes to API development.
When it comes to using SLIM, there are four main features:
To get SLIM installed on your computer, the fastest way is to use composer to install a skeletal version of SLIM. But for this tutorial, we will only install SLIM core and then walk through configuring SLIM for a simple application request-response cycle.
To install SLIM we use composer, we create our working directory (call it whatever you want). Then, we move into that directory and run the following composer command which should install SLIM on our machine.
- composer require slim/slim "^3.0"
Note: At the time of writing this article, the current version of SLIM is version 3.5.0.
Ah, the obligatory “Hello World” application. This example will illustrate how easy it is to use SLIM.
In our project directory, we should only see our composer files and a vendor directory. We can then create a index.php
file.
In that file, we add this little code snippet.
<?php
require __DIR__ . '/vendor/autoload.php';
$app = new Slim\App;
$app->get('/', function ($request, $response) {
return 'hello world';
});
$app->run();
First, we load composer’s autoloader, then we create a new instance of the Slim\App
, then call a get method to the home path, and pass a closure that takes in the request and response, and then return "hello world"
(which is converted to a response object by SLIM. Outside the closure, we run the app.
To see our message in the browser, in the root of our working directory, we boot a PHP server.
- php -S localhost:8000
If you open localhost:8000
in the browser, you should see “hello world”. If you use a different server, you should check out the section on server configuration.
The above example only simulated a GET request, as we all know, there are more request types like POST, PUT, PATCH, DELETE, OPTIONS. To use any of these methods in SLIM, we literarily do the same thing we did with the get method above.
<?php
$app->post('/', function ($request, $response) {
return 'hello world';
});
The above route now will only work for POST requests. We can call the rest of the HTTP methods the same way.
The route discussion in this article is a bit vague, in an upcoming article, we will talk about routing in SLIM.
Say we are building an application that is not an API with SLIM, we need a way to organize our templates, not that SLIM requires any template of sorts, but templates make it easier to manage our view files.
There are a lot of templates engines for PHP, but for this tutorial, we will stick with Twig.
Twig allows us to use custom properties to write PHP template files. It compiles to pure PHP code.
To display a variable in twig, we do this.
{{ var }}
This then compiles itself to:
<?php echo $var ?>
We could create global template layouts that we can later extend and keep our page layout and styling consistent.
{% extends "layout.html" %}
{% block content %}
The content of the page...
{% endblock %}
Twig offers many more features. It is also one of the most stable and best PHP template languages out there. Another alternative to twig is Blade (for Laravel), or Smarty.
To get started, we need to install Twig, and to do that, we go into the root of our application and run the following command.
- composer require slim/twig-view
Now that we have twig installed, let’s create a templates
directory at the root of our project. We can now register twig as our view engine/manager in SLIM. In our index.php
file, we add this snippet before our routes.
<?php
// ...
$container = $app->getContainer();
$container['view'] = function ($container) {
$templates = __DIR__ . '/templates/';
$cache = __DIR__ . '/tmp/views/';
$view = new Slim\Views\Twig($templates, compact('cache'));
return $view;
};
First, we grab our app $container
and add a new property called view
. We name it whatever we want (template, page, etc). Just note that this value is important as we will need to reference it soon. We pass a closure that takes in the $container
instance.
Then we create an instance of Slim\Views\Twig
and pass in the directory of our templates, and the second parameter is an array (compact
converts variables to array key-value pairs) where we can pass the location to our template cache directory.
We can disable caching by setting the $cache
variable to false
. After that, we can return the $view
.
To actually use our view files in our routes, we can go back into our router and then return a view file like this.
$app->get('/', function ($request, $response) {
return $this->view->render($response, 'home.twig');
});
Note: Make sure you have a file named home.twig
in your templates directory. Whatever you place in that file gets rendered in the browser.
There is a 100% chance that you don’t use the PHP default server to serve your app in production. Odds are you choose between Apache and the lovely Nginx. For these servers, our routes won’t work without a little URL rewriting. We see how to configure Apache and Nginx, if you use another server, you can check out the web servers section on SLIM’s website.
Wherever you decide to make the root of your application, create a new .htaccess
file and place the following snippet in that file.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
What this does is just serve files and directory that exists on the server, and if they don’t exist then let the routing be handled by our index.php
file.
server {
listen 80;
server_name example.com;
index index.php;
error_log /path/to/example.error.log;
access_log /path/to/example.access.log;
root /path/to/public;
location / {
try_files $uri /index.php$is_args$args;
}
location ~ \.php {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:9000;
}
}
This configuration is similar to the Apache configuration, don’t forget to replace example.com
.
Frameworks like Laravel, Zend, Symfony, etc are really good, but they are not necessary when it comes to building APIs and simple websites (they are too bloated). Slim is an excellent framework, it is easy to use, lightweight, extensible, etc.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.