[STARTER] Slim framework complete example

In this short tutorial, I will show how to create a complete Slim framework starter application with the use of database and a service layer.
The code can be found here:

1. Installation (http://docs.slimframework.com/)

Install composer in your project:

Create a composer.json file in your project root:

Install via composer:

This will be your application’s index.php file:


require ‘vendor/autoload.php’;
require ‘services/CategoryService.php’;

$catService = new ServiceCategoryService();
$app = new SlimSlim();
$app->response->headers->set(‘Content-Type’, ‘application/json’);
$app->get(‘/category/:name’, ‘getCategory’);


function getCategory($name) {
global $catService;
$namez = $catService->getCategory($name);
echo json_encode($namez);


CategoryService is a php class that resides under the services folder:

namespace Service;
require ‘services/DatabaseService.php’;

class CategoryService {
private $dbService = null;
public function __construct() {
$this->dbService = new ServiceDatabaseService();

public function getCategory($name) {
$sql = "select * FROM category where name = ‘$name’";
$results = $this->dbService->executeQuery($sql);
return $results;

And finally DatabaseService under the same services folder (change the DB connection settings):


namespace Service;

use PDO;

class DatabaseService {

private static $connection = null;

private static function initConnection() {
$dbhost = "localhost";
$dbuser = "yourusername";
$dbpass = "yourpassword";
$dbname = "testing";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
self::$connection = $dbh;

public static function getConnection() {
if (self::$connection == null) {
return self::$connection;

public function executeQuery($sql) {
try {
$db = self::getConnection();
$stmt = $db->query($sql);
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
return $results;
} catch (PDOException $e) {
echo ‘{"error":{"text":’ . $e->getMessage() . ‘}}’;



A request to:
will show all your categories.

Leave a Reply

Your email address will not be published. Required fields are marked *