Creating and Running a Slim Project in ServBay
This article provides a step-by-step guide on how to quickly create, configure, and run a PHP-based Slim Framework project within ServBay—a powerful local web development environment. ServBay offers integrated PHP, web servers (Caddy/Nginx/Apache), and a variety of database packages, making it an ideal platform for Slim development.
What is Slim?
Slim is a lightweight PHP micro-framework designed for rapidly building simple yet powerful web applications and APIs. It offers core features such as routing, request handling, and response processing, making it perfect for projects that require speedy development and deployment or serve as the foundation for more complex applications.
Key Features and Benefits of Slim
- Lightweight: Slim's core codebase is very small, making it resource-efficient and fast to start. It's suitable for building small to medium-sized apps or microservices.
- Flexibility: Slim is designed to be pluggable, allowing seamless integration with any third-party component or library (such as template engines, ORMs, authentication libraries, etc.), giving you the freedom to choose the best tools for your project.
- Easy to Use: With its clean API and clear documentation, developers can quickly grasp Slim's core concepts and start building.
- Powerful Routing: Supports various HTTP methods (GET, POST, PUT, DELETE, etc.) and advanced routing configurations, including route groups, middleware, and parameter capturing.
- Middleware Support: Slim’s middleware layer lets you execute tasks before requests reach application logic or before responses are sent back to the client—for example, authentication, logging, CORS handling, and more.
Slim is especially suited for building RESTful APIs, rapid prototyping, and handling dedicated, standalone functionalities.
Creating and Running a Slim Project in ServBay
This guide utilizes ServBay’s pre-configured PHP environment and Website feature for web server setup, enabling easy access to your Slim project.
Prerequisites
Before you begin, make sure you have completed the following:
- Install and Run ServBay: Ensure ServBay is successfully installed on your macOS or Windows system and the ServBay application is running.
- Composer Bundled with ServBay: ServBay comes with Composer integrated by default—no need for separate installation.
Creating a Slim Project
ServBay recommends storing all website projects in the following directories for easier management and configuration:
- macOS:
/Applications/ServBay/www - Windows:
C:\ServBay\www
Navigate to ServBay’s Website Root Directory:
macOS:
bashcd /Applications/ServBay/www1Windows:
cmdcd C:\ServBay\www1Create a Project Directory: Make a new directory for your Slim project.
bashmkdir servbay-slim-app1Enter the Project Directory:
bashcd servbay-slim-app1Install Slim Using Composer: In your project directory, use Composer to install Slim and its PSR-7 implementation.
bashcomposer require slim/slim "^4.0" slim/psr7 -W1This will download the Slim framework and the
slim/psr7library into thevendorfolder, generatingcomposer.jsonandcomposer.lockfiles.
Initializing the Slim Application
- Create the Entry File: Slim projects normally use a single entry file (like
public/index.php) to handle all requests. In your project root, create apublicdirectory and create theindex.phpfile inside it.bashmkdir public touch public/index.php1
2 - Edit the Entry File: Open
public/index.phpand add the following basic Slim application code:phpThis sets up the most basic Slim app: a route that handles GET requests to the root URL (<?php // Load Composer's autoloader require __DIR__ . '/../vendor/autoload.php'; // Import necessary PSR-7 interfaces and Slim factory class use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; // Create the Slim app instance $app = AppFactory::create(); // Add a basic route to handle GET requests to root path '/' $app->get('/', function (Request $request, Response $response, $args) { // Write output to response body $response->getBody()->write("Hello ServBay!"); // Return the response object return $response; }); // Run the Slim app $app->run();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22/), returning a response with "Hello ServBay!" text.
Configuring Your ServBay Website
To access your Slim project in the browser, you'll need to configure a Website (formerly known as "Host" in older versions) in ServBay.
- Open the ServBay application interface.
- Navigate to the Websites module.
- Click to add a new website.
- Fill out the configuration according to your project:
Name:
My First Slim Dev Site(or any name you like)Domain:
servbay-slim-test.local(it’s recommended to use.localor.testdomains for local development)Website Type:
PHPPHP Version: Choose your required PHP version, e.g.,
8.3.Document Root: Click Browse and select your project's
publicdirectory:- macOS:
/Applications/ServBay/www/servbay-slim-app/public - Windows:
C:\ServBay\www\servbay-slim-app\public
This is because Slim's entry file
index.phpis located inpublic, so the web server should point to this directory.- macOS:
- Save the website configuration. ServBay will automatically update the web server settings and apply them.
For a detailed walkthrough, see Adding Your First Website.
Accessing Your Slim Website
Once configuration is complete, open your browser and go to https://servbay-slim-test.local.
If everything is set up correctly, you should see the page displaying Hello ServBay!. This confirms your Slim project is running successfully via ServBay’s web server.
Database Integration Examples
Slim itself doesn’t include a database abstraction layer, but it can easily integrate with various PHP database libraries. Here we'll use Laravel’s Eloquent ORM (via the illuminate/database component) to demonstrate connections to MySQL and PostgreSQL, along with integration examples for Memcached and Redis.
Prerequisites: Creating Databases and Running Migrations
Before integrating databases, you'll need to create the database in ServBay and set up the necessary table structure for your app.
- Create the Database:
- Open the ServBay application and navigate to your chosen database package (e.g., MySQL or PostgreSQL).
- Use ServBay's management tools (e.g., phpMyAdmin for MySQL/MariaDB, pgAdmin for PostgreSQL) or the command-line client to create a new database, such as
servbay_slim_app. - The ServBay default root user password for databases is usually
password; you can check or change this in the ServBay interface.
- Install and Configure Phinx (Database Migration Tool): Phinx helps version-control your database structure.
- In your Slim project root, use Composer to install Phinx:
- macOS:
/Applications/ServBay/www/servbay-slim-app - Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require robmorgan/phinx1 - macOS:
- Initialize Phinx configuration:bashThis creates a
vendor/bin/phinx init1phinx.ymlconfig file in your project root. Edit this file to set your database connection info, e.g.:yamlpaths: migrations: '%%PHINX_CONFIG_DIR%%/db/migrations' seeds: '%%PHINX_CONFIG_DIR%%/db/seeds' environments: default_migration_table: phinxlog default_environment: development # or your configured environment development: # configure according to your database type adapter: mysql # or pgsql host: 127.0.0.1 name: servbay_slim_app # your database name user: root pass: password # your database password port: 3306 # default for MySQL, PostgreSQL default is 5432 charset: utf8mb4 # recommended for MySQL collation: utf8mb4_unicode_ci # recommended for MySQL version_order: creation1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- In your Slim project root, use Composer to install Phinx:
- Create Migration File: Use Phinx to create a new migration file.bashThis will create a new PHP file under
vendor/bin/phinx create CreateUsersTable1db/migrations. Open it and edit thechange()method to define theuserstable structure:php<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class CreateUsersTable extends AbstractMigration { /** * Change Method. * * Write your reversible migrations using this method. * * More information on writing migrations is available here: * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method * * Remember to call "create()" or "update()" and NOT "save()" when working * with the Table class. */ public function change(): void { $table = $this->table('users'); $table->addColumn('name', 'string') ->addColumn('email', 'string', ['unique' => true]) ->addTimestamps() // Adds created_at and updated_at fields ->create(); } }1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 - Run the Migration: In the project root, run Phinx to create the
userstable.bashImportant: Be sure to complete the database creation and migration steps before running the database example code below.vendor/bin/phinx migrate1
Using the illuminate/database Component
We’ll use Laravel’s database package (illuminate/database) as the ORM and query builder.
Install illuminate/database: In your project root, add the dependency:
- macOS:
/Applications/ServBay/www/servbay-slim-app - Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require illuminate/database1- macOS:
Initialize the Database Connection in
public/index.php: Add the following afterrequire __DIR__ . '/../vendor/autoload.php';and before creating the Slim app with$app = AppFactory::create();.php// ... Other require and use statements ... use Illuminate\Database\Capsule\Manager as Capsule; // Import Capsule manager // Initialize Eloquent ORM $capsule = new Capsule; // Add database connection configuration (change driver/params as needed) $capsule->addConnection([ 'driver' => 'mysql', // Or 'pgsql' 'host' => '127.0.0.1', 'database' => 'servbay_slim_app', // Your database name 'username' => 'root', // Your DB username 'password' => 'password', // Your DB password 'charset' => 'utf8mb4', // Recommended for MySQL 'collation' => 'utf8mb4_unicode_ci', // Recommended for MySQL 'prefix' => '', // PostgreSQL requires the schema parameter // 'schema' => 'public', ]); // Make the Capsule instance globally accessible $capsule->setAsGlobal(); // Boot Eloquent $capsule->bootEloquent(); // ... Create Slim app instance ($app = AppFactory::create();) ...1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
MySQL Example
Assuming you have started the MySQL package in ServBay, created the servbay_slim_app database, and run the migration to create the users table.
Add the following routes in public/index.php before $app->run();:
php
// ... Earlier initialization and '/' route ...
use Illuminate\Database\Capsule\Manager as Capsule; // Ensure imported
// Route to add a user
$app->get('/mysql-add-user', function (Request $request, Response $response, $args) {
try {
Capsule::table('users')->insert([
'name' => 'ServBay Demo User',
'email' => 'servbay-demo-' . time() . '@servbay.test', // Use time() to ensure unique email
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
$response->getBody()->write('User added to MySQL');
} catch (\Exception $e) {
$response->getBody()->write('Error adding user: ' . $e->getMessage());
$response = $response->withStatus(500); // Return error status code
}
return $response;
});
// Route to get users
$app->get('/mysql-get-users', function (Request $request, Response $response, $args) {
try {
$users = Capsule::table('users')->get();
$response->getBody()->write($users->toJson()); // Output results as JSON
$response = $response->withHeader('Content-Type', 'application/json'); // Set Content-Type
} catch (\Exception $e) {
$response->getBody()->write('Error fetching users: ' . $e->getMessage());
$response = $response->withStatus(500);
}
return $response;
});
// ... $app->run();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
How to access:
- Visit
https://servbay-slim-test.local/mysql-add-userto add a new user into theuserstable. - Visit
https://servbay-slim-test.local/mysql-get-usersto fetch all users as JSON from theuserstable.
PostgreSQL Example
Assuming you have started the PostgreSQL package in ServBay, created the servbay_slim_app database, and run the migration to create the users table (ensure Phinx config uses adapter as pgsql and port as 5432).
Update the database connection settings in public/index.php—change driver to pgsql and add the schema parameter:
php
$capsule->addConnection([
'driver' => 'pgsql', // Change to pgsql
'host' => '127.0.0.1',
'database' => 'servbay_slim_app',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8', // PostgreSQL generally uses utf8
'prefix' => '',
'schema' => 'public', // PostgreSQL needs schema specified
]);
// ... Other Eloquent initialization remains unchanged ...1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
Then add the following routes before $app->run(); in public/index.php:
php
// ... Earlier initialization and '/' route ...
// ... MySQL routes (if needed) ...
use Illuminate\Database\Capsule\Manager as Capsule; // Ensure imported
// Route to add a user
$app->get('/pgsql-add-user', function (Request $request, Response $response, $args) {
try {
Capsule::table('users')->insert([
'name' => 'ServBay PG Demo User',
'email' => 'servbay-pg-demo-' . time() . '@servbay.test', // Use time() for unique email
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
$response->getBody()->write('User added to PostgreSQL');
} catch (\Exception $e) {
$response->getBody()->write('Error adding user: ' . $e->getMessage());
$response = $response->withStatus(500);
}
return $response;
});
// Route to get users
$app->get('/pgsql-get-users', function (Request $request, Response $response, $args) {
try {
$users = Capsule::table('users')->get();
$response->getBody()->write($users->toJson());
$response = $response->withHeader('Content-Type', 'application/json');
} catch (\Exception $e) {
$response->getBody()->write('Error fetching users: ' . $e->getMessage());
$response = $response->withStatus(500);
}
return $response;
});
// ... $app->run();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
How to access:
- Visit
https://servbay-slim-test.local/pgsql-add-userto add a user to PostgreSQL'suserstable. - Visit
https://servbay-slim-test.local/pgsql-get-usersto fetch all users as JSON from PostgreSQL'suserstable.
Memcached Example
ServBay bundles the Memcached package and PHP ext-memcached extension. You just need to install a PHP client library—here, we'll use memcached/memcached.
Install Memcached Client Library: In your project root:
- macOS:
/Applications/ServBay/www/servbay-slim-app - Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require memcached/memcached1- macOS:
Add Memcached Route in
public/index.php: Add before$app->run();:php// ... Earlier initialization and database routes ... // Memcached example route $app->get('/memcached-example', function (Request $request, Response $response, $args) { // Create Memcached client instance $memcached = new Memcached(); // Add Memcached server (ServBay default runs on 127.0.0.1:11211) $memcached->addServer('127.0.0.1', 11211); $cacheKey = 'my_servbay_cache_key'; // Try to get data from cache $cachedData = $memcached->get($cacheKey); if ($cachedData === false) { // If not in cache, generate data and store to cache $cachedData = 'Hello Memcached from ServBay! This was not cached.'; // Store data in cache with a TTL of 60 seconds $memcached->set($cacheKey, $cachedData, 60); $response->getBody()->write($cachedData); } else { // If cached, serve directly $response->getBody()->write('Hello Memcached from ServBay! This was served from cache.'); } return $response; }); // ... $app->run();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
How to access: Visit https://servbay-slim-test.local/memcached-example. The first visit shows "This was not cached."; subsequent visits (before cache expires) show "This was served from cache."
Redis Example
ServBay includes the Redis package and PHP ext-redis extension. You only need a PHP client library—here, we use predis/predis.
Install Redis Client Library: In your project root:
- macOS:
/Applications/ServBay/www/servbay-slim-app - Windows:
C:\ServBay\www\servbay-slim-app
bashcomposer require predis/predis1- macOS:
Add Redis Route in
public/index.php: Add before$app->run();:php// ... Earlier initialization and database routes ... // ... Memcached route (if needed) ... use Predis\Client as RedisClient; // Import Predis client class // Redis example route $app->get('/redis-example', function (Request $request, Response $response, $args) { try { // Create Redis client (ServBay default runs on 127.0.0.1:6379) $redis = new RedisClient([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]); $cacheKey = 'my_servbay_redis_cache_key'; // Try to get data from cache $cachedData = $redis->get($cacheKey); if ($cachedData === null) { // If not in cache, generate data and store in Redis $cachedData = 'Hello Redis from ServBay! This was not cached.'; // Store data in Redis with 60s expiry $redis->setex($cacheKey, 60, $cachedData); // SETEX key seconds value $response->getBody()->write($cachedData); } else { // If cached, serve directly $response->getBody()->write('Hello Redis from ServBay! This was served from cache.'); } } catch (\Exception $e) { // Catch connection or operation exceptions $response->getBody()->write('Error connecting to Redis or performing operation: ' . $e->getMessage()); $response = $response->withStatus(500); } return $response; }); // ... $app->run();1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
How to access: Visit https://servbay-slim-test.local/redis-example. The first visit shows "This was not cached."; subsequent visits (before cache expiry) show "This was served from cache."
Summary
By following these steps, you’ve successfully created a Slim Framework project within the ServBay local development environment and used ServBay's Website feature to host and access your project. You’ve also learned how to integrate various ServBay packages (MySQL, PostgreSQL, Memcached, Redis) and corresponding PHP extensions, bringing database and caching support to your Slim app. ServBay simplifies local server setup and management so you can focus on developing your Slim application.
