Creating and Running a Slim Project in ServBay
This guide will walk you through quickly creating, configuring, and running a PHP-based Slim Framework project using ServBay, a powerful local web development environment. ServBay comes pre-packaged with PHP, web servers (Caddy/Nginx/Apache), and various database software, making it the ideal platform for Slim development.
What is Slim?
Slim is a lightweight PHP micro-framework designed for building simple yet robust web applications and APIs at high speed. Its core delivers routing, request handling, and response features, making it perfect for rapid development, deployment, or as the foundation for more complex systems.
Key Features and Advantages of Slim
- Lightweight: The Slim core codebase is minimal, consumes few resources, and launches quickly, making it suitable for small- to medium-sized applications or microservices.
- Flexibility: Slim is built to be pluggable and integrates seamlessly with third-party components or libraries such as template engines, ORMs, authentication packages, etc. You have the flexibility to pick the tools that best suit your project.
- Ease of Use: Its clean API and clear documentation allow developers to easily grasp core concepts and get started quickly.
- Powerful Routing: Supports multiple HTTP methods (GET, POST, PUT, DELETE, etc.) and complex routing configurations, including route grouping, middleware, and parameter capturing.
- Middleware Support: The middleware layer enables you to perform tasks such as authentication, logging, CORS handling, and more, either before requests reach your application logic or before responses are sent to the client.
Slim is an excellent choice for building RESTful APIs, rapid prototyping, or developing specific, standalone functionality.
Creating and Running a Slim Project with ServBay
This guide leverages ServBay’s pre-configured PHP environment and Websites feature to set up the web server, allowing easy access to your Slim project with minimal setup.
Prerequisites
Before you begin, please ensure:
- ServBay is Installed and Running: Make sure ServBay is successfully installed on your macOS system and the application is running.
- Composer Included: ServBay comes with Composer pre-integrated—no separate installation required.
Creating a Slim Project
ServBay recommends storing all projects under /Applications/ServBay/www
for easy project management and configuration.
- Navigate to ServBay's web root:bash
cd /Applications/ServBay/www
1 - Create your project directory:bash
mkdir servbay-slim-app
1 - Enter your project directory:bash
cd servbay-slim-app
1 - Install Slim via Composer: Use Composer to install Slim and its PSR-7 implementation.bashThis command downloads Slim and the
composer require slim/slim "^4.0" slim/psr7 -W
1slim/psr7
library to your project'svendor
directory and generates thecomposer.json
andcomposer.lock
files.
Initializing the Slim Application
- Create the entry file: Slim projects typically use a single entry point such as
public/index.php
to handle all requests. Create apublic
directory in your project and add anindex.php
file inside.bashmkdir public touch public/index.php
1
2 - Edit the entry file: Open
public/index.php
and add the following basic Slim app code:phpThis code sets up a minimal Slim app with a route for the root URL (<?php // Load Composer autoload file 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 Slim app instance $app = AppFactory::create(); // Add a simple route: handles GET requests to root '/' $app->get('/', function (Request $request, Response $response, $args) { // Write to the response body $response->getBody()->write("Hello ServBay!"); // Return the response object return $response; }); // Run the Slim application $app->run();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22/
) that returns a "Hello ServBay!" response.
Configuring Your Website in ServBay
To access your Slim project in the browser, you need to configure a Website (previously called "Host" in older ServBay versions).
- Open the ServBay application interface.
- Navigate to the Websites module.
- Click to add a new website.
- Fill in the configuration according to your project:
- Name:
My First Slim Dev Site
(or any name you prefer) - Domain:
servbay-slim-test.local
(it's recommended to use domains ending in.local
or.test
for local development) - Website Type:
PHP
- PHP Version: Choose your preferred PHP version, e.g.,
8.3
. - Document Root: Browse and select the
public
directory inside your project, i.e.,/Applications/ServBay/www/servbay-slim-app/public
. This is becauseindex.php
—the entry file—is located inpublic
, and the web server should point to this directory.
- Name:
- Save your website configuration. ServBay will automatically reload and update the web server with your new settings.
For detailed ServBay website configuration steps, see Add Your First Website.
Accessing Your Slim Website
Once configuration is done, open your web browser and navigate to https://servbay-slim-test.local
.
If everything is set up correctly, you should see "Hello ServBay!
" displayed. This means your Slim project is now running via ServBay’s web server.
Database Integration Examples
While Slim itself doesn’t include a database abstraction layer, you can easily integrate any PHP database library. Here, we'll use Laravel’s Eloquent ORM (illuminate/database
) to demonstrate connecting to MySQL and PostgreSQL, along with examples for Memcached and Redis integration.
Prerequisite: Creating Databases and Running Migrations
Before integrating databases, you need to create the necessary databases in ServBay and set up database tables for your app.
Create the Database:
- Open ServBay, navigate to your chosen database package (e.g., MySQL or PostgreSQL).
- Use ServBay’s admin tools (phpMyAdmin for MySQL/MariaDB, pgAdmin for PostgreSQL) or the CLI client to create a new database (e.g.,
servbay_slim_app
). - By default, ServBay’s root database password is
password
. You can view or change it in the ServBay UI.
Install and Configure Phinx (Database Migration Tool): Phinx helps version control your database structures.
- In your project root
/Applications/ServBay/www/servbay-slim-app
, install Phinx using Composer:bashcomposer require robmorgan/phinx
1 - Initialize the Phinx configuration:bashThis creates a
vendor/bin/phinx init
1phinx.yml
config file. Edit it to set up your database connection, for example: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 per your DB type adapter: mysql # or pgsql host: 127.0.0.1 name: servbay_slim_app # your DB name user: root pass: password # your DB password port: 3306 # MySQL default, PostgreSQL is 5432 charset: utf8mb4 # for MySQL collation: utf8mb4_unicode_ci # for MySQL version_order: creation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- In your project root
Create a Migration File: Use the Phinx command to generate a migration file.
bashvendor/bin/phinx create CreateUsersTable
1This creates a PHP file under
db/migrations
. Open it and define theusers
table in thechange()
method: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
28Run Migrations: From your project root, run the Phinx command to execute the migration and create the
users
table.bashvendor/bin/phinx migrate
1Important: You must complete database creation and migration steps before running the example code below.
Using the illuminate/database Component
Let's use Laravel’s database component (illuminate/database
) as the ORM/query builder.
Install illuminate/database: In your project root
/Applications/ServBay/www/servbay-slim-app
:bashcomposer require illuminate/database
1Initialize DB in
public/index.php
: Afterrequire __DIR__ . '/../vendor/autoload.php';
and before creating the Slim app instance ($app = AppFactory::create();
), add:php// ... other require and use statements ... use Illuminate\Database\Capsule\Manager as Capsule; // Initialize Eloquent ORM $capsule = new Capsule; // Add DB connection config (modify driver and params as needed) $capsule->addConnection([ 'driver' => 'mysql', // or 'pgsql' 'host' => '127.0.0.1', 'database' => 'servbay_slim_app', // your DB name 'username' => 'root', // your DB username 'password' => 'password', // your DB password 'charset' => 'utf8mb4', // for MySQL 'collation' => 'utf8mb4_unicode_ci', // for MySQL 'prefix' => '', // PostgreSQL requires the schema param // 'schema' => 'public', ]); // Make Capsule available globally $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
Suppose you have MySQL running in ServBay, created the servbay_slim_app
database, and ran Phinx migrations to create the users
table.
In public/index.php
, add the following routes before $app->run();
:
// ... initialization and '/' route ...
use Illuminate\Database\Capsule\Manager as Capsule;
// 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', // 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 $response;
});
// Route to fetch users
$app->get('/mysql-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();
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 use:
- Visit
https://servbay-slim-test.local/mysql-add-user
to add a new user to theusers
table. - Visit
https://servbay-slim-test.local/mysql-get-users
to fetch all users as JSON from theusers
table.
PostgreSQL Example
Suppose PostgreSQL is running in ServBay, servbay_slim_app
database is created, and Phinx migrations created the users
table (ensure Phinx config uses adapter: pgsql
and port: 5432
).
Adjust the DB connection in public/index.php
—change driver
to pgsql
and add schema
:
$capsule->addConnection([
'driver' => 'pgsql',
'host' => '127.0.0.1',
'database' => 'servbay_slim_app',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8', // utf8 for PostgreSQL
'prefix' => '',
'schema' => 'public', // PostgreSQL needs this
]);
// ... rest of Eloquent initialization remains unchanged ...
2
3
4
5
6
7
8
9
10
11
Then add these routes before $app->run();
:
// ... initialization and '/' route ...
// ... MySQL routes if needed ...
use Illuminate\Database\Capsule\Manager as Capsule;
// 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', // 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 PostgreSQL');
} catch (\Exception $e) {
$response->getBody()->write('Error adding user: ' . $e->getMessage());
$response = $response->withStatus(500);
}
return $response;
});
// Route to fetch 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();
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 use:
- Visit
https://servbay-slim-test.local/pgsql-add-user
to add a new user to the PostgreSQLusers
table. - Visit
https://servbay-slim-test.local/pgsql-get-users
to fetch all users as JSON from the PostgreSQLusers
table.
Memcached Example
ServBay provides the Memcached package and the PHP ext-memcached
extension. You just need a PHP client library; here, we use memcached/memcached
.
Install the Memcached client: In your project root:
bashcomposer require memcached/memcached
1Add a Memcached route in
public/index.php
: Before$app->run();
php// ... initialization and DB routes ... // Memcached example route $app->get('/memcached-example', function (Request $request, Response $response, $args) { // Instantiate Memcached $memcached = new Memcached(); // Add the server (ServBay runs on 127.0.0.1:11211 by default) $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 no data cached, generate and store $cachedData = 'Hello Memcached from ServBay! This was not cached.'; // Store data in cache with a 60-second TTL $memcached->set($cacheKey, $cachedData, 60); $response->getBody()->write($cachedData); } else { // If cached data exists, use it $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 use: Visit https://servbay-slim-test.local/memcached-example
. The first visit displays "This was not cached." Subsequent visits (within 60 seconds) show "This was served from cache."
Redis Example
ServBay provides the Redis package and the PHP ext-redis
extension. To interact, install a PHP client library; we’ll use predis/predis
.
Install the Redis client: In your project root:
bashcomposer require predis/predis
1Add a Redis route in
public/index.php
: Before$app->run();
php// ... initialization and DB routes ... // ... Memcached route if present ... use Predis\Client as RedisClient; // Redis example route $app->get('/redis-example', function (Request $request, Response $response, $args) { try { // Instantiate Redis (ServBay runs on 127.0.0.1:6379 by default) $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 no cached data, generate and store $cachedData = 'Hello Redis from ServBay! This was not cached.'; // Store data in cache with a TTL of 60 seconds $redis->setex($cacheKey, 60, $cachedData); $response->getBody()->write($cachedData); } else { // Use the cached data $response->getBody()->write('Hello Redis from ServBay! This was served from cache.'); } } catch (\Exception $e) { // Catch connection or operation errors $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 use: Visit https://servbay-slim-test.local/redis-example
. On your first visit you'll see "This was not cached." Subsequent visits (within 60 seconds) display "This was served from cache."
Summary
By following these steps, you've successfully created a Slim Framework project in the ServBay local development environment, set up the Website feature to host and access your project, and learned how to integrate various packages offered by ServBay (such as MySQL, PostgreSQL, Memcached, Redis) as well as their respective PHP extensions, into your Slim app. ServBay streamlines environment setup and management, letting you focus on building your Slim application.