[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:
https://github.com/vladimirvs/slim-example

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:

[code]
<?php

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

$app->run();

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

[/code]

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

[code]
<?php
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;
}
}
[/code]

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

[code]
<?php

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);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$connection = $dbh;
}

public static function getConnection() {
if (self::$connection == null) {
self::initConnection();
}
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() . ‘}}’;
}
}

}

[/code]

A request to:
yourhost/category/main
will show all your categories.

Leave a Reply

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