在 ServBay 中创建并运行 Slim 项目
本文将指导您如何在 ServBay 这个强大的本地 Web 开发环境中,快速创建、配置并运行一个基于 PHP 的 Slim Framework 项目。ServBay 提供了集成的 PHP、Web 服务器(Caddy/Nginx/Apache)和多种数据库软件包,是进行 Slim 开发的理想平台。
什么是 Slim?
Slim 是一个轻量级的 PHP 微框架,专为快速构建简单但功能强大的 Web 应用程序和 API 而设计。它提供了核心的路由、请求处理和响应处理功能,非常适合那些需要快速开发和部署的项目,或者作为构建更复杂应用的基础。
Slim 的主要特性和优势
- 轻量级: Slim 框架的核心代码库非常小巧,资源占用低,启动速度快,适用于构建小型到中型应用程序或微服务。
- 灵活性: Slim 设计为可插拔,可以与任何第三方组件或库(如模板引擎、ORM、认证库等)轻松集成,提供极大的灵活性来选择最适合您项目需求的工具。
- 易于使用: 凭借简洁的 API 和清晰的文档,开发者可以快速理解其核心概念并上手开发。
- 强大的路由功能: 支持多种 HTTP 方法(GET, POST, PUT, DELETE 等)和复杂的路由配置,包括路由分组、中间件和参数捕获。
- 中间件支持: Slim 的中间件层允许您在请求到达应用程序逻辑之前或响应发送回客户端之前执行任务,例如身份验证、日志记录、CORS 处理等。
Slim 是构建 RESTful API、快速原型开发以及处理特定、独立功能的理想选择。
使用 ServBay 创建并运行 Slim 项目
本指南将利用 ServBay 预配置的 PHP 环境和网站功能来设置 Web 服务器,并通过简单的配置实现 Slim 项目的访问。
前提条件
在开始之前,请确保您已完成以下准备:
- 安装并运行 ServBay: 请确保 ServBay 已经成功安装在您的 macOS 系统上,并且 ServBay 应用程序正在运行。
- ServBay 包含 Composer: ServBay 默认集成了 Composer,无需单独安装。
创建 Slim 项目
ServBay 建议开发者将所有网站项目统一存放在 /Applications/ServBay/www
目录下,这有助于 ServBay 对项目进行管理和配置。
- 进入 ServBay 的网站根目录:bash
cd /Applications/ServBay/www
1 - 创建项目目录: 创建一个新的目录用于存放 Slim 项目。bash
mkdir servbay-slim-app
1 - 进入项目目录:bash
cd servbay-slim-app
1 - 使用 Composer 安装 Slim: 在项目目录中使用 Composer 安装 Slim 框架及其 PSR-7 实现。bash此命令会下载 Slim 框架和
composer require slim/slim "^4.0" slim/psr7 -W
1slim/psr7
库到项目的vendor
目录,并生成composer.json
和composer.lock
文件。
初始化 Slim 应用
- 创建入口文件: Slim 项目通常使用一个单一的入口文件(例如
public/index.php
)来处理所有请求。在项目根目录下创建public
目录,并在其中创建index.php
文件。bashmkdir public touch public/index.php
1
2 - 编辑入口文件: 打开
public/index.php
文件,添加以下基本的 Slim 应用代码:php这段代码设置了一个最简单的 Slim 应用,它定义了一个处理根 URL (<?php // 载入 Composer 自动加载文件 require __DIR__ . '/../vendor/autoload.php'; // 导入必要的 PSR-7 接口和 Slim 工厂类 use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; // 创建 Slim 应用实例 $app = AppFactory::create(); // 添加一个基本的路由:处理 GET 请求到根路径 '/' $app->get('/', function (Request $request, Response $response, $args) { // 向响应体写入内容 $response->getBody()->write("Hello ServBay!"); // 返回响应对象 return $response; }); // 运行 Slim 应用 $app->run();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22/
) GET 请求的路由,并返回一个包含 "Hello ServBay!" 文本的响应。
配置 ServBay 网站
要通过浏览器访问您的 Slim 项目,您需要在 ServBay 中配置一个网站(在旧版本中称为“主机”)。
- 打开 ServBay 应用程序界面。
- 导航到网站 (Websites) 功能模块。
- 点击添加新的网站。
- 根据您的项目信息填写配置:
- 名字 (Name):
My First Slim Dev Site
(或者您喜欢的任何名称) - 域名 (Domain):
servbay-slim-test.local
(建议使用.local
或.test
结尾的域名用于本地开发) - 网站类型 (Website Type):
PHP
- PHP 版本 (PHP Version): 选择一个您需要的 PHP 版本,例如
8.3
。 - 网站根目录 (Document Root): 点击浏览按钮,选择您项目中的
public
目录,即/Applications/ServBay/www/servbay-slim-app/public
。这是因为 Slim 的入口文件index.php
位于public
目录中,Web 服务器应该将请求指向这个目录。
- 名字 (Name):
- 保存网站配置。ServBay 会自动更新 Web 服务器配置并使其生效。
详细的 ServBay 网站配置步骤,请参考 添加第一个网站。
访问您的 Slim 网站
配置完成后,打开您的 Web 浏览器,访问您设置的域名 https://servbay-slim-test.local
。
如果一切顺利,您应该会看到浏览器页面上显示 Hello ServBay!
文本。这表明您的 Slim 项目已成功通过 ServBay 的 Web 服务器运行。
数据库集成示例
Slim 框架本身不包含数据库抽象层,但可以轻松集成各种 PHP 数据库库。这里我们以 Laravel 的 Eloquent ORM (通过 illuminate/database
组件) 为例,演示如何连接 MySQL 和 PostgreSQL,并提供 Memcached 和 Redis 的集成示例。
前提条件: 创建数据库和运行迁移
在进行数据库集成之前,您需要先在 ServBay 中创建相应的数据库,并为您的应用创建必要的数据库表结构。
- 创建数据库:
- 打开 ServBay 应用程序界面,导航到您使用的数据库软件包(如 MySQL 或 PostgreSQL)。
- 使用 ServBay 提供的管理工具(如 phpMyAdmin for MySQL/MariaDB, pgAdmin for PostgreSQL)或命令行客户端,创建一个新的数据库,例如命名为
servbay_slim_app
。 - ServBay 默认的数据库 root 用户密码通常是
password
,您可以在 ServBay 界面中查看或修改。
- 安装和配置 Phinx (数据库迁移工具): Phinx 是一个流行的 PHP 数据库迁移工具,可以帮助您版本控制数据库结构。
- 在您的 Slim 项目根目录
/Applications/ServBay/www/servbay-slim-app
中,使用 Composer 安装 Phinx:bashcomposer require robmorgan/phinx
1 - 初始化 Phinx 配置:bash这会在项目根目录创建一个
vendor/bin/phinx init
1phinx.yml
配置文件。编辑此文件,配置您的数据库连接信息,例如:yamlpaths: migrations: '%%PHINX_CONFIG_DIR%%/db/migrations' seeds: '%%PHINX_CONFIG_DIR%%/db/seeds' environments: default_migration_table: phinxlog default_environment: development # 或您配置的环境名称 development: # 根据您的数据库类型配置 adapter: mysql # 或 pgsql host: 127.0.0.1 name: servbay_slim_app # 您创建的数据库名 user: root pass: password # 您的数据库密码 port: 3306 # MySQL 默认端口,PostgreSQL 默认 5432 charset: utf8mb4 # MySQL 建议使用 collation: utf8mb4_unicode_ci # MySQL 建议使用 version_order: creation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- 在您的 Slim 项目根目录
- 创建迁移文件: 使用 Phinx 命令创建一个新的迁移文件。bash这会在
vendor/bin/phinx create CreateUsersTable
1db/migrations
目录下创建一个新的 PHP 文件。打开该文件,编辑change()
方法来定义users
表结构: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() // 添加 created_at 和 updated_at 字段 ->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 - 运行迁移: 在项目根目录运行 Phinx 命令来执行迁移,创建
users
表。bash重要: 在运行下面的数据库示例代码之前,请务必先完成数据库创建和迁移步骤。vendor/bin/phinx migrate
1
使用 illuminate/database 组件
我们将使用 Laravel 的数据库组件 (illuminate/database
) 作为 ORM/查询构建器。
安装 illuminate/database: 在项目根目录
/Applications/ServBay/www/servbay-slim-app
中安装依赖。bashcomposer require illuminate/database
1在
public/index.php
中初始化数据库连接: 在index.php
文件的require __DIR__ . '/../vendor/autoload.php';
之后,Slim 应用$app = AppFactory::create();
之前,添加以下代码来配置数据库连接。php// ... 其他 require 和 use 语句 ... use Illuminate\Database\Capsule\Manager as Capsule; // 导入 Capsule 管理器 // 初始化 Eloquent ORM $capsule = new Capsule; // 添加数据库连接配置 (根据您使用的数据库修改 driver 和其他参数) $capsule->addConnection([ 'driver' => 'mysql', // 或 'pgsql' 'host' => '127.0.0.1', 'database' => 'servbay_slim_app', // 您的数据库名 'username' => 'root', // 您的数据库用户名 'password' => 'password', // 您的数据库密码 'charset' => 'utf8mb4', // MySQL 建议 'collation' => 'utf8mb4_unicode_ci', // MySQL 建议 'prefix' => '', // PostgreSQL 需要 schema 参数 // 'schema' => 'public', ]); // 设置全局可访问 $capsule->setAsGlobal(); // 启动 Eloquent $capsule->bootEloquent(); // ... 创建 Slim 应用实例 ($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 示例
假设您已在 ServBay 中启动了 MySQL 软件包,创建了 servbay_slim_app
数据库,并运行了 Phinx 迁移创建了 users
表。
在 public/index.php
中,在 $app->run();
之前添加以下路由:
php
// ... 前面的初始化代码和 '/' 路由 ...
use Illuminate\Database\Capsule\Manager as Capsule; // 确保已导入
// 添加用户数据的路由
$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', // 使用 time() 确保邮箱唯一
'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;
});
// 获取用户数据的路由
$app->get('/mysql-get-users', function (Request $request, Response $response, $args) {
try {
$users = Capsule::table('users')->get();
$response->getBody()->write($users->toJson()); // 将结果转换为 JSON 输出
$response = $response->withHeader('Content-Type', 'application/json'); // 设置 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
访问:
- 访问
https://servbay-slim-test.local/mysql-add-user
会向users
表添加一个新用户。 - 访问
https://servbay-slim-test.local/mysql-get-users
会从users
表获取所有用户并以 JSON 格式输出。
PostgreSQL 示例
假设您已在 ServBay 中启动了 PostgreSQL 软件包,创建了 servbay_slim_app
数据库,并运行了 Phinx 迁移创建了 users
表 (确保 Phinx 配置中的 adapter
和 port
正确设置为 pgsql
和 5432
)。
修改 public/index.php
中的数据库连接配置,将 driver
改为 pgsql
并添加 schema
参数:
php
$capsule->addConnection([
'driver' => 'pgsql', // 改为 pgsql
'host' => '127.0.0.1',
'database' => 'servbay_slim_app',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8', // PostgreSQL 常用 utf8
'prefix' => '',
'schema' => 'public', // PostgreSQL 需要指定 schema
]);
// ... 其他 Eloquent 初始化代码保持不变 ...
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
在 public/index.php
中,在 $app->run();
之前添加以下路由:
php
// ... 前面的初始化代码和 '/' 路由 ...
// ... MySQL 路由 (如果需要) ...
use Illuminate\Database\Capsule\Manager as Capsule; // 确保已导入
// 添加用户数据的路由
$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', // 使用 time() 确保邮箱唯一
'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;
});
// 获取用户数据的路由
$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
访问:
- 访问
https://servbay-slim-test.local/pgsql-add-user
会向 PostgreSQL 的users
表添加一个新用户。 - 访问
https://servbay-slim-test.local/pgsql-get-users
会从 PostgreSQL 的users
表获取所有用户并以 JSON 格式输出。
Memcached 示例
ServBay 提供了 Memcached 软件包和 PHP 的 ext-memcached
扩展。您只需要安装一个 PHP 客户端库来与之交互。我们将使用 memcached/memcached
。
安装 Memcached 客户端库: 在项目根目录
/Applications/ServBay/www/servbay-slim-app
中安装依赖。bashcomposer require memcached/memcached
1在
public/index.php
中添加 Memcached 路由: 在$app->run();
之前添加以下路由:php// ... 前面的初始化代码和数据库路由 ... // 使用 Memcached 的路由 $app->get('/memcached-example', function (Request $request, Response $response, $args) { // 创建 Memcached 客户端实例 $memcached = new Memcached(); // 添加 Memcached 服务器 (ServBay 默认运行在 127.0.0.1:11211) $memcached->addServer('127.0.0.1', 11211); $cacheKey = 'my_servbay_cache_key'; // 尝试从缓存获取数据 $cachedData = $memcached->get($cacheKey); if ($cachedData === false) { // 如果缓存中没有数据,则生成数据并存入缓存 $cachedData = 'Hello Memcached from ServBay! This was not cached.'; // 将数据存入缓存,ttl (time to live) 为 60 秒 $memcached->set($cacheKey, $cachedData, 60); $response->getBody()->write($cachedData); } else { // 如果缓存中有数据,则直接使用缓存数据 $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
访问: 访问 https://servbay-slim-test.local/memcached-example
。第一次访问会显示 "This was not cached.",后续访问(在缓存过期前)会显示 "This was served from cache."。
Redis 示例
ServBay 提供了 Redis 软件包和 PHP 的 ext-redis
扩展。您只需要安装一个 PHP 客户端库来与之交互。我们将使用 predis/predis
。
安装 Redis 客户端库: 在项目根目录
/Applications/ServBay/www/servbay-slim-app
中安装依赖。bashcomposer require predis/predis
1在
public/index.php
中添加 Redis 路由: 在$app->run();
之前添加以下路由:php// ... 前面的初始化代码和数据库路由 ... // ... Memcached 路由 (如果需要) ... use Predis\Client as RedisClient; // 导入 Predis 客户端类 // 使用 Redis 的路由 $app->get('/redis-example', function (Request $request, Response $response, $args) { try { // 创建 Redis 客户端实例 (ServBay 默认运行在 127.0.0.1:6379) $redis = new RedisClient([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]); $cacheKey = 'my_servbay_redis_cache_key'; // 尝试从缓存获取数据 $cachedData = $redis->get($cacheKey); if ($cachedData === null) { // 如果缓存中没有数据,则生成数据并存入缓存 $cachedData = 'Hello Redis from ServBay! This was not cached.'; // 将数据存入缓存,设置过期时间为 60 秒 $redis->setex($cacheKey, 60, $cachedData); // SETEX key seconds value $response->getBody()->write($cachedData); } else { // 如果缓存中有数据,则直接使用缓存数据 $response->getBody()->write('Hello Redis from ServBay! This was served from cache.'); } } catch (\Exception $e) { // 捕获连接或操作异常 $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
40
访问: 访问 https://servbay-slim-test.local/redis-example
。第一次访问会显示 "This was not cached.",后续访问(在缓存过期前)会显示 "This was served from cache."。
总结
通过以上步骤,您已经成功地在 ServBay 本地开发环境中创建了一个 Slim Framework 项目,并配置了 ServBay 的网站功能来托管和访问该项目。您还学会了如何利用 ServBay 提供的各种软件包(如 MySQL, PostgreSQL, Memcached, Redis)以及相应的 PHP 扩展,将数据库和缓存集成到您的 Slim 应用中。ServBay 简化了本地环境的搭建和管理,让您可以更专注于 Slim 应用的开发本身。