Create and Run a Slim Project
What is Slim?
Slim is a lightweight PHP micro-framework designed for quickly building simple yet powerful web applications and APIs. It provides basic routing, request handling, and response handling functionality, making it suitable for projects that need to be developed and deployed quickly.
Main Features and Advantages of Slim
- Lightweight: Slim is very small and is suitable for building small to medium-sized applications.
- Flexibility: It can integrate with any third-party component or library, offering great flexibility.
- Easy to Use: With a simple API and clear documentation, developers can quickly get started.
- Powerful Routing: Supports various HTTP methods and complex routing configurations.
- Middleware Support: Allows easy addition of middleware to handle requests and responses.
Slim is ideal for building RESTful APIs and rapid prototyping.
Create and Run a Slim Project Using ServBay
In this article, we will use ServBay's PHP environment to create and run a Slim project. We'll use ServBay's 'Host' feature to set up the web server and access the project through simple configuration.
Note: If you have previously used NGINX or Apache
ServBay defaults to using Caddy as the web server. For users migrating from NGINX and Apache to ServBay, there are some key changes to note:
Caddy Configuration
ServBay has built-in Caddy, optimized, and debugged by default. Developers just need to manage sites through ServBay's 'Host' feature without manually modifying Caddy configuration files.
Rewrite Rules and .htaccess
In NGINX and Apache, developers typically write their own rewrite rules and .htaccess files to handle URL rewriting and other configurations. However, ServBay comes pre-configured with Caddy rules, so developers generally don't need to write these rules themselves unless there's a special requirement.
Learn More
For more information, refer to Rewrite and htaccess, How to Migrate an Apache Website to ServBay, How to Migrate an NGINX Website to ServBay.
Create a Slim Project
TIP
ServBay recommends placing websites in the /Applications/ServBay/www
directory for easier management.
Install Composer
ServBay comes with Composer pre-installed, so no separate installation is needed.
Create a Slim Project
Use Composer to create a new Slim project:
bashcd /Applications/ServBay/www mkdir servbay-slim-app cd servbay-slim-app composer require slim/slim "^4.0" composer require slim/psr7 -W
1
2
3
4
5Enter the Project Directory
Enter the newly created Slim project directory:
bashcd /Applications/ServBay/www/servbay-slim-app
1
Initialize Configuration
Create Entry File
Create the file
public/index.php
in the project root directory and add the following code:php<?php require __DIR__ . '/../vendor/autoload.php'; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; $app = AppFactory::create(); $app->get('/', function (Request $request, Response $response, $args) { $response->getBody()->write("Hello ServBay!"); return $response; }); $app->run();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Configure Web Server
Use ServBay's 'Host' feature to access the Slim project via the web server. In the ServBay 'Host' settings, add a new host:
- Name:
My First Slim Dev Site
- Domain:
servbay-slim-test.local
- Site Type:
PHP
- PHP Version: Choose
8.3
- Website Root Directory:
/Applications/ServBay/www/servbay-slim-app/public
For detailed steps, refer to Adding Your First Website.
Add Sample Code
Add the following code to the public/index.php
file to output "Hello ServBay!":
$app->get('/', function (Request $request, Response $response, $args) {
$response->getBody()->write("Hello ServBay!");
return $response;
});
2
3
4
Access the Website
Open the browser and visit https://servbay-slim-test.local
, you will see the page output Hello ServBay!
.
NoSQL Database Example
Memcached Example
Install Memcached Extension
Memcached extension is already pre-installed in ServBay, no additional installation is needed.
Configure Memcached
Add Memcached dependency to
composer.json
file:json{ "require": { "slim/slim": "^4.0", "memcached/memcached": "^3.1" } }
1
2
3
4
5
6Then run
composer update
to install the dependencies.Configure Route
Add the following code to the
public/index.php
file:php$app->get('/memcached', function (Request $request, Response $response, $args) { $memcached = new Memcached(); $memcached->addServer('127.0.0.1', 11211); $cacheKey = 'my_cache_key'; $cachedData = $memcached->get($cacheKey); if ($cachedData === false) { $cachedData = 'Hello Memcached!'; $memcached->set($cacheKey, $cachedData); } $response->getBody()->write($cachedData); return $response; });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15Use Memcached
Open the browser and visit
https://servbay-slim-test.local/memcached
Redis Example
Install Redis Extension
Redis extension is already pre-installed in ServBay, no additional installation is needed.
Configure Redis
Add Redis dependency to
composer.json
file:json{ "require": { "slim/slim": "^4.0", "predis/predis": "^1.1" } }
1
2
3
4
5
6Then run
composer update
to install the dependencies.Configure Route
Add the following code to the
public/index.php
file:php$app->get('/redis', function (Request $request, Response $response, $args) { $redis = new Predis\Client([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]); $cacheKey = 'my_cache_key'; $cachedData = $redis->get($cacheKey); if ($cachedData === null) { $cachedData = 'Hello Redis!'; $redis->set($cacheKey, $cachedData); } $response->getBody()->write($cachedData); return $response; });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18Use Redis
Open the browser and visit
https://servbay-slim-test.local/redis
Relational Database Example
Creating Database Schema and Migration File
Create Migration File
Use Phinx to create a migration file:
bashcomposer require robmorgan/phinx vendor/bin/phinx init
1
2Edit Migration File
Create a new migration file in the
db/migrations
directory and edit it to define the database table structure:phpuse Phinx\Migration\AbstractMigration; class CreateUsersTable extends AbstractMigration { public function change() { $table = $this->table('users'); $table->addColumn('name', 'string') ->addColumn('email', 'string', ['unique' => true]) ->create(); } }
1
2
3
4
5
6
7
8
9
10
11
12Run Migration
Use the Phinx command to run the migration and create the database table:
bashvendor/bin/phinx migrate
1
MySQL Example
Configure MySQL
Add MySQL dependency to
composer.json
file:json{ "require": { "slim/slim": "^4.0", "illuminate/database": "^8.0" } }
1
2
3
4
5
6Then run
composer update
to install the dependencies.Configure Route
Add the following code to the
public/index.php
file:phpuse Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule; $capsule->addConnection([ 'driver' => 'mysql', 'host' => '127.0.0.1', 'database' => 'servbay_slim_app', 'username' => 'root', 'password' => 'password', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ]); $capsule->setAsGlobal(); $capsule->bootEloquent(); $app->get('/mysql-add', function (Request $request, Response $response, $args) { $user = Capsule::table('users')->insert([ 'name' => 'ServBay', 'email' => '[email protected]' ]); $response->getBody()->write('User added'); return $response; }); $app->get('/mysql', function (Request $request, Response $response, $args) { $users = Capsule::table('users')->get(); $response->getBody()->write($users->toJson()); return $response; });
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
32Insert User Data
Open the browser and visit
https://servbay-slim-test.local/mysql-add
andhttps://servbay-slim-test.local/mysql
PostgreSQL Example
Configure PostgreSQL
Add PostgreSQL dependency to
composer.json
file:json{ "require": { "slim/slim": "^4.0", "illuminate/database": "^8.0" } }
1
2
3
4
5
6Then run
composer update
to install the dependencies.Configure Route
Add the following code to the
public/index.php
file:phpuse Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule; $capsule->addConnection([ 'driver' => 'pgsql', 'host' => '127.0.0.1', 'database' => 'servbay_slim_app', 'username' => 'root', 'password' => 'password', 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', ]); $capsule->setAsGlobal(); $capsule->bootEloquent(); $app->get('/pgsql-add', function (Request $request, Response $response, $args) { $user = Capsule::table('users')->insert([ 'name' => 'ServBay', 'email' => '[email protected]' ]); $response->getBody()->write('User added'); return $response; }); $app->get('/pgsql', function (Request $request, Response $response, $args) { $users = Capsule::table('users')->get(); $response->getBody()->write($users->toJson()); return $response; });
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
32Insert User Data
Open the browser and visit
https://servbay-slim-test.local/pgsql-add
andhttps://servbay-slim-test.local/pgsql
By following the above steps, you have successfully created and run a Slim project, managed and accessed your project using ServBay's features, while connecting multiple databases and calling data.