Organizing Your Slim Based Project

June 29, 2013

Table of Contents

A Slim Based Project is basically extended over three main directories.

  1. Slim framework directory
  1. Project directory

This directory contains your project files like routers, views, models. Being a microframework, Slim is not restrictive on any particular project structure. This means that you are allowed to structure your project files in any way you like. This is particularly helpful in cases when developers are used to a particular folder structure. This directory can be stored anywhere on the server, but it should not be in a web accessible location. You can place it in the /usr/local or in your home folder.  Like creating the project in a folder named HelloSlim, it could be located at /usr/local/HelloSlim or ~/HelloSlim or the location you like. Below is an example of how the files can be arranged:

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

You can create this folder by executing the following commands:

mkdir /usr/local/HelloSlim

mkdir /usr/local/HelloSlim/Routes

mkdir /usr/local/HelloSlim/Models

mkdir /usr/local/HelloSlim/Views

mkdir /usr/local/HelloSlim/Class

  1. Document root/Public folder

This folder is accessible on the web (basically located at /var/www). This folder contains only two Slim related files:

  • index.php
  • .htaccess

The folder will contain all the projects scripts, style and image files.for organization purposes , you can divide those into the scripts,styles and images folders respectively.

Here is a sample structure of the document root folder:

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

If your file has the structure above , you will have to fill the .htaccess and index.php files ( in the document root ) with the following contents respectively:

 .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

SlimSlim::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 SlimSlim(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

To finish this tutorial assuming that the project has been arranged as per the folder structure defined in the previous section, the routes.php and includes.php files (in the project directory) should have the following contents:

routes.php

 <?php

require ‘/usr/local/HelloSlim/Routes/route1.php’;

require ‘/usr/local/HelloSlim/Routes/route2.php’;

Note: You could create the routes directly in this file instead of including other files containing routes. Even though, defining routes in different, basically grouped files will make your project more maintainable.

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

Now that you know how to set up a Slim application, let’s create a simple application which does the following:

  • Handles static Routes (GET & POST)
  • Handles dynamic Routes
  • Uses views

Note: This sample application will assume that Slim has been deployed as described above.

Let’s map out the requirements for this sample application:

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

The project will require the following files to be created 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 appear like the following:

Document Root (eg. /var/www/)

|- .htaccess

|- index.php

Now populate these files as follows:

  1. /var/www/.htaccess

RewriteEngine On 

RewriteCond %{REQUEST_FILENAME} !-f 

RewriteRule ^ index.php [QSA,L]

  1. /var/www/index.php

<?php

 

require ‘/usr/local/Slim/Slim.php’;     //include the framework in the project

SlimSlim::registerAutoloader();       //register the autoloader

 

$projectDir = ‘/usr/local/HelloSlim’;   //define the directory containing the project files

 

$app = new SlimSlim(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

  1. /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));

});

  1. /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

    ));

});

  1. /usr/local/HelloSlim/Views/footer.php

       <small>Copyright notice…</small>

       </body>

       </html>

  1. /usr/local/HelloSlim/Views/header.php

<!DOCTYPE html>

<html>

<head>

<title>Sample Slim Application</title>

</head<

<body>

  1. /usr/local/HelloSlim/Views/hello.php

***

<?php include(‘header.php’); ?>

 

***

<h1>Hello <?php echo isset($name)?$name:”; ?></h1>

<!– The above line handles both the dynamic and the static GET routes that we implemented in the getRoutes.php file.

 

***

 

<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’); ?>

  1. /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’);

  1. /usr/local/HelloSlim/routes.php

<?php

 

    include ‘Routes/getRoutes.php’;

    include ‘Routes/postRoutes.php’;

Share on
Facebook
Twitter
LinkedIn
Pinterest
More posts

Dedicated Servers Quick Guide

What is a Dedicated Servers? Why bother using a dedicated server over a VPS or Shared Hosting?A dedicated server is a server 100% dedicated to your website/project or business needs.

Why 247Rack Is Recommended

Only 247Rack can give you most flexible and 100% customizable VMware Solution. We have given our customers the freedom to configure every single part as their choice. Our scalable cloud

Software Defined Single Sign On Database

Software Defined Single Sign On Database. One difficult task since the release of vSphere 5.1 has been the creation of SSO (Single Sign On) databases.  Creating an SSO database is

Setup Nginx Website Easy Simple Guide

What is needed for a quick Nginx server and website setup? A Dedicated or VPS Server A compatible operating system 247Rack recommends: Centos OS A domain name pointed to the

Live Help

Get 90% Discount

First 3 People gets the Bonus!
Don't Miss Out Our Big Sale

Get 0-90% On All
247Rack Services

247Rack

The Sale Is Until The End Of March