Preconditions
This tutorial will help you to installing and configuring Slim Framework on a VPS step by step. With this tutorial, you will be able to obtain an operational and working case of Slim Framework including a folder structure which can be used for basing your project in.
This tutorial presumes that you have your preferred stack like LAMP deployed on Ubuntu. However, in case your application is not using MySQL, you can skip the installation of LAMP stack. But the minimal requirement is that you should have PHP (minimum 5.3 version) and Apache web server (with Mod_Rewrite) installed.
Quick Setup for Preconditions:
1. To Deploy Apache
apt-get update
apt-get install apache2
2. To Deploy PHP
apt-get install php5 libapache2-mod-php5 php5-mcrypt
3. Make sure to Enable mod_rewrite
a2enmod rewrite
4. Update the Apache configuration file
Update the Apache configuration file and for the document root, put AllowOverride All instead of AllowOverride None. This configuration file could be any one of the files given below as per your server setup:
/etc/apache2/apache2.conf
/etc/apache2/sites-enabled/000-default
/etc/apache2/sites-available/default
Now in the configuration file, find the section containing the following:
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
Modify this to the section given below and then save the file:
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
5. Restart Apache
service apache2 restart
Additionally, this tutorial presumes that you are familiar with basics of Linux.
Slim Framework- what is it?
Slim is an exceptionally efficient, popular, easy to use and fast open source microframework for PHP. It not only finds application in the development of small to mid sized web applications but can also be utilized efficiently for developing large scale PHP applications.
Slim comprises a number of power packed utilities that are typically expected within a framework:
HTTP caching
Robust, flexible and easy to use router
Secure cookies
Custom view for rendering templates
Simple configuration
Convenient to use debugging and error handling
Installation
You can instll Slim Framework in three simple steps
Download Slim Framework
Extract it from Zip File
Copy it to a Common Location
1. Slim Framework Download
Slim Framework can be downloaded through the command given below:
wget https://github.com/codeguy/Slim/zipball/master
This command fetches the framework as a zip file and then it is stored in the recent directory alongwith the name master.
2. Extracting it from the Zip File
In order to extract the zip file’s contents, following command can be used:
unzip master -d ./
Note: In case you encounter an error that unzip is not installed, then it can be installed with the command–apt-get install unzip
and this command can then be executed for extracting all files.
Using the command line above, the files are extracted in a folder that’s named in a fashion like codeguy-Slim-3a2ac72. The framework folder- Slim is contained within this folder.
3. Copying Slim Framework onto a Common Location
codeguy-Slim-3a2ac72/Slim folder will now be copied onto a common location as /usr/local/Slim. It can now be accessed by all the projects on the server that utilize Slim. This will not only prevent all maintenance issues but will also avoid duplication that might result from duplicate deployments.
Now the folder can be copied with the command given below:
cp -r ./codeguy-Slim-3a2ac72/Slim /usr/local/Slim
Note: If any other version of Slim is downloaded then the extracted folder’s name (codeguy-Slim-3a2ac72
) might vary slightly. Ensure that the folder’s name is accordingly modified in the command above.
On completing the above step, it can be referenced from this location by any Slim Framework using project.
Important Note: Frameworks are deployed in the public folder/document root by a number of tutorials (as /var/www/Slim
). When framework files are installed outside the public folder/document root (as done above) the application becomes comparably more safe as the files of the framework become inaccessible in any browser.
Organization of Your Slim Based Project
A Slim project normally comprises three major directories:
1. Slim framework directory
This is the directory copied in the step above and it includes the framework files (/usr/local/Slim)
2. Project directory
Project directory includes all the project files like views, routers, models etc. Slim does not constrain a specific structure of the project as it is a microframework, that allows one with the freedom to structure their project files in any way they seem right. This especially helps in those cases where the developers are accustomed with a specific folder structure.
This project directory can remain at any location on the server, but ideally it should not be accessible by web. It can be placed in the /usr/local or in the user’s home folder. Like, if the project is created in HelloSlim named folder, then it could be placed at ~/HelloSlim or /usr/local/HelloSlim or any of your preferred location.
Given below is a way in which files can be arranged in this folder:
HelloSlim
|- Routes
| |- route1.php
| |- route2.php
|- Models
| |- model1.php
| |- model2.php
|- Views
| |- footer.php
| |- header.php
| |- sidebar.php
| |- view1.php
| |- view2.php
|- Class
| |- class1.php
| |- class2.php
|- routes.php //contains 'include' statements for all routes in the 'Routes' folder
|- includes.php //contains 'include' statements for all models/classes in the 'Models/Class' folders
This folder structure can be created by execution of the commands given below:
mkdir /usr/local/HelloSlim
mkdir /usr/local/HelloSlim/Routes
mkdir /usr/local/HelloSlim/Models
mkdir /usr/local/HelloSlim/Views
mkdir /usr/local/HelloSlim/Class
Note: You can utilize the folder structure given or can modify it fully in accordance with your preferences.
3. Document root/Public folder
This folder is the one that’s accessible by web (generally located at /var/www). This folder includes only two files related to Slim:
index.php
.htaccess
The document folder also comprises all the image and style files as well as the projects script. You can organize the things by dividing them into images, styles and scripts folders respectively.
Here’s an example of the document root folder structure:
Document Root (eg. /var/www/)
|- scripts
| |- jquery.min.js
| |- custom.js
|- styles
| |- style.css
| |- bootstrap.min.css
|- images
| |- logo.png
| |- banner.jpg
|- .htaccess
|- index.php
File Contents
On the assumption that the structure provided above is the same as that of your project, you need to fill the .htaccess and index.php files (in the document root) with the respective contents provided below:
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
index.php
<?php
require '/usr/local/Slim/Slim.php'; //include the framework in the project
\Slim\Slim::registerAutoloader(); //register the autoloader
$projectDir = '/usr/local/HelloSlim'; //define the directory containing the project files
require "$projectDir/includes.php"; //include the file which contains all the project related includes
$app = new \Slim\Slim(array(
'templates.path' => '/usr/local/HelloSlim/Views'
)); //instantiate a new Framework Object and define the path to the folder that holds the views for this project
require "$projectDir/routes.php"; //include the file which contains all the routes/route inclusions
$app->run(); //load the application
In order to finish this tutorial on the assumption that the project is arranged according to the folder structure explained in the section above, the routes.php and includes.php files (in the project directory) should contain the content given below:
routes.php
<?php
require '/usr/local/HelloSlim/Routes/route1.php';
require '/usr/local/HelloSlim/Routes/route2.php';
Note: The routes can be directly created in this file rather than including different files involving routes. But the project can be more maintainable if routes are defined in different, logically arranged files.
includes.php
<?php
require "/usr/local/HelloSlim/Class/class1.php";
require "/usr/local/HelloSlim/Class/class2.php";
require "/usr/local/HelloSlim/Models/model1.php";
require "/usr/local/HelloSlim/Models/model2.php";
Sample Slim Application
Since you are now familiar with setting up a Slim application, let’s develop an easy application that performs the following:
Handles static Routes (GET & POST)
Handles dynamic Routes
Uses views
Note: This example will presume that Slim is installed deployed as explained above.
The needs of this example application are chalked below:
Route Type Action
/hello GET (static) Displays a static View
/hello/NAME GET (dynamic) Displays a dynamic View
/greet POST Displays a View after a POST request
This sample will need the following files to be developed in the Application folder (/usr/local/HelloSlim/):
HelloSlim
|- Routes
| |- getRoutes.php
| |- postRoutes.php
|- Views
| |- footer.php
| |- header.php
| |- hello.php
| |- greet.php
|- routes.php
The public folder/document root will seem to be something like below:
Here’s an instance of the document root folder structure:
Document Root (eg. /var/www/)
|- .htaccess
|- index.php
Now populate these files as below:
1. /var/www/.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
2. /var/www/index.php
<?php
require '/usr/local/Slim/Slim.php'; //include the framework in the project
\Slim\Slim::registerAutoloader(); //register the autoloader
$projectDir = '/usr/local/HelloSlim'; //define the directory containing the project files
$app = new \Slim\Slim(array(
'templates.path' => '/usr/local/HelloSlim/Views'
)); //instantiate a new Framework Object and define the path to the folder that holds the views for this project
require "$projectDir/routes.php"; //include the file which contains all the routes/route inclusions
$app->run(); //load the application
3. /usr/local/HelloSlim/Routes/getRoutes.php
<?php
$app->get('/', function(){
echo 'This is a simple starting page';
});
//The following handles any request to the /hello route
$app->get('/hello', function() use ($app){
// the following statement invokes and displays the hello.php View
$app->render('hello.php');
});
//The following handles any dynamic requests to the /hello/NAME routes (like /hello/world)
$app->get('/hello/:name', function($name) use ($app){
// the following statement invokes and displays the hello.php View. It also passes the $name variable in an array so that the view can use it.
$app->render('hello.php', array('name' => $name));
4. /usr/local/HelloSlim/Routes/postRoutes.php
<?php
//The following handles the POST requests sent to the /greet route
$app->post('/greet', function() use ($app){
//The following statement checks if 'name' has been POSTed. If it has, it assigns the value to the $name variable. If it hasn't been set, it assigns a blank string.
$name = (null !== $app->request->post('name'))?$app->request->post('name'):'';
//The following statement checks if 'greeting' has been POSTed. If it has, it assigns the value to the $greeting variable. If it hasn't been set, it assigns a blank string.
$greeting = (null !== $app->request->post('greeting'))?$app->request->post('greeting'):'';
// the following statement invokes and displays the 'greet.php' View. It also passes the $name & $greeting variables in an array so that the view can use them.
$app->render('greet.php', array(
'name' => $name,
'greeting' => $greeting
));
});
5. /usr/local/HelloSlim/Views/footer.php
<small>Copyright notice...</small>
</body>
</html>
6. /usr/local/HelloSlim/Views/header.php
<!DOCTYPE html> <html> <head> <title>Sample Slim Application</title> </head< <body>
7. /usr/local/HelloSlim/Views/hello.php
<?php include('header.php'); ?>
<h1>Hello <?php echo isset($name)?$name:''; ?></h1>
<h2>Send a greeting</h2>
<form method='POST' action='/greet'>
<label>Name</label><br>
<input name='name' placeholder='Who do you want to greet?'><br>
<label>Greeting</label><br>
<input name='greeting' placeholder='Your greeting message'><br>
<input type='submit' value='Greet!'>
</form>
<?php include('footer.php'); ?>
8. /usr/local/HelloSlim/Views/greet.php
<?php
include('header.php');
echo "<p>$greeting, $name</p><p><a href='/hello'>First Page</a></p>";
include('footer.php');
9. /usr/local/HelloSlim/routes.php
<?php
include 'Routes/getRoutes.php';
include 'Routes/postRoutes.php';
Sample Application Screenshots
Now if you see your new sample application at http://yourdomain.com/, you will see something like below:
On visiting http://yourdomain.com/hello, you will see the following:
On visiting http://yourdomain.com/hello/World, you will see the following:
Note: When ‘World’ is replaced in the URL with some other word, the page’s content will be changed accordingly.
For testing the POST route, put a name and greeting in the fields provided and press the ‘Greet!’ button as given below:
On pressing the ‘Greet!’ button, you will get something like this: