在 ServBay 中创建并运行 Yii 2 项目
概述:什么是 Yii 2?
Yii 2 是一个高性能、基于组件的 PHP 框架,用于快速开发现代 Web 应用程序。它遵循 MVC(Model-View-Controller)设计模式,提供了一整套丰富的功能和工具,帮助开发者高效地构建可伸缩、高质量的 Web 应用。Yii 2 因其出色的性能、灵活的架构和强大的内置功能(如缓存、安全性、RESTful API 开发支持等)而受到广泛欢迎。
Yii 2 的主要特性和优势
- 高性能: Yii 2 经过精心优化,能够处理高并发请求,适用于构建性能敏感的应用。
- 模块化: 框架设计为高度模块化,方便开发者组织代码和重用组件。
- 安全性: 内置多种安全功能,包括输入验证、输出过滤、CSRF/XSS 防护、认证授权框架等。
- 易于使用: 提供简洁直观的 API 和详尽的文档,降低学习曲线,使开发者能够快速上手。
- 强大的社区支持: 拥有一个活跃的开发者社区和丰富的第三方扩展库,遇到问题可以方便地获取帮助。
- 集成工具: 提供命令行工具用于数据库迁移、代码生成等任务,提升开发效率。
Yii 2 是构建企业级应用、RESTful API、门户网站等多种类型 Web 项目的理想选择。
使用 ServBay 运行 Yii 2 项目
ServBay 是一款专为 macOS 设计的本地 Web 开发环境,它集成了 PHP、各种数据库(如 MySQL, PostgreSQL, MongoDB, Redis)、Web 服务器(Caddy, Nginx)以及其他开发者工具(如 Composer, Node.js, Python, Go, Java 等),旨在为开发者提供一个“开箱即用”的便捷开发平台。
本文将指导您如何利用 ServBay 提供的 PHP 环境、Composer 工具和数据库服务来创建并运行一个 Yii 2 基础应用项目。我们将使用 ServBay 的“网站”功能来配置本地 Web 服务器,并通过简单的步骤实现项目的访问和基本功能的演示。
前提条件
在开始之前,请确保您已经:
- 在 macOS 系统上成功安装并运行了 ServBay。
- ServBay 中已安装并启用了所需的 PHP 版本(例如 PHP 8.3 或更高版本)。
- ServBay 中已安装并启用了您打算使用的数据库服务(例如 MySQL 或 PostgreSQL)以及缓存服务(Memcached 和 Redis)。
您可以在 ServBay 的主界面中查看和管理已安装的软件包及运行状态。
创建 Yii 2 项目
TIP
ServBay 建议将您的项目文件存放在 /Applications/ServBay/www
目录下。这样做有助于保持文件结构的整洁,并方便 ServBay 的“网站”功能进行管理。
Composer: ServBay 已经内置了 Composer 工具,您无需单独安装。您可以直接在终端中使用
composer
命令。创建项目目录: 打开终端,进入 ServBay 的默认网站根目录,并创建一个新的项目目录。
bashcd /Applications/ServBay/www mkdir servbay-yii2-app cd servbay-yii2-app
1
2
3使用 Composer 创建 Yii 2 项目: 在
servbay-yii2-app
目录下,运行 Composer 命令来创建一个新的 Yii 2 基础应用模板项目。bashcomposer create-project --prefer-dist yiisoft/yii2-app-basic .
1此命令会下载 Yii 2 基础应用模板及其所有依赖到当前目录 (
.
)。请耐心等待 Composer 完成下载和安装过程。进入项目目录: 确保您当前终端所在的目录是项目的根目录
/Applications/ServBay/www/servbay-yii2-app
。后续的命令都将在此目录下执行。bashcd /Applications/ServBay/www/servbay-yii2-app
1
初始化配置
Yii 2 项目创建后,需要进行一些基本的配置,特别是关于数据库连接和组件设置。
配置数据库连接: 编辑项目根目录下的
config/db.php
文件。根据您在 ServBay 中运行的数据库服务(MySQL 或 PostgreSQL)以及其配置(默认用户通常是root
,默认密码通常是password
,除非您修改过),更新数据库连接信息。首先,您需要在 ServBay 对应的数据库服务中创建一个新的数据库供此项目使用,例如命名为
servbay_yii2_app
。您可以使用 ServBay 自带的 Adminer 工具或您偏好的数据库客户端(如 Sequel Ace, TablePlus 等)来创建数据库。Adminer 可以通过 ServBay 应用界面的数据库部分访问。对于 MySQL:
php<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=127.0.0.1;dbname=servbay_yii2_app', // dbname 应为您创建的数据库名称 'username' => 'root', // 您的数据库用户名 'password' => 'password', // 您的数据库密码 'charset' => 'utf8mb4', // 建议使用 utf8mb4 支持更广泛的字符集 ];
1
2
3
4
5
6
7
8
9对于 PostgreSQL:
php<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'pgsql:host=127.0.0.1;port=5432;dbname=servbay_yii2_app', // dbname 应为您创建的数据库名称,port 通常为 5432 'username' => 'root', // 您的数据库用户名 'password' => 'password', // 您的数据库密码 'charset' => 'utf8', 'schemaMap' => [ 'pgsql' => [ 'class' => 'yii\pgsql\Schema', 'defaultSchema' => 'public', // PostgreSQL 默认 schema ], ], ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15请根据您的实际情况选择并修改
config/db.php
文件。配置缓存和 Redis 组件: 编辑项目根目录下的
config/web.php
文件。添加或修改components
部分,以配置 Memcached 和 Redis。ServBay 默认的 Memcached 端口是11211
,Redis 端口是6379
。php<?php // ... 其他配置项 'components' => [ // ... 其他已有的组件配置 (如 request, cache, user, errorHandler, log, urlManager) 'cache' => [ 'class' => 'yii\caching\MemCache', 'servers' => [ [ 'host' => '127.0.0.1', 'port' => 11211, // Memcached 默认端口 'weight' => 100, ], ], ], 'redis' => [ 'class' => 'yii\redis\Connection', 'hostname' => '127.0.0.1', 'port' => 6379, // Redis 默认端口 'database' => 0, // Redis 数据库索引 ], // ... 其他组件 ], // ... 其他配置项
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确保您已在 ServBay 中启动了 Memcached 和 Redis 服务。请注意,使用 Redis 作为缓存需要安装
yiisoft/yii2-redis
包(Composer 会在create-project
时安装基础依赖,如果需要更多,可能需要手动composer require yiisoft/yii2-redis
)。Memcached 通常使用yiisoft/yii2-memcached
。基础模板可能已包含这些依赖。
配置 Web 服务器 (ServBay 网站)
使用 ServBay 的“网站”功能来配置本地 Web 服务器(Caddy 或 Nginx)以指向您的 Yii 2 项目。
- 打开 ServBay 应用: 启动 ServBay 应用。
- 导航到网站设置: 在 ServBay 界面中,找到并点击“网站”或类似的导航项。
- 添加新网站: 点击添加新网站的按钮(通常是
+
或添加
)。 - 填写网站信息:
- 名字: 输入一个易于识别的名称,例如
My First Yii 2 Dev Site
。 - 域名: 输入您希望在浏览器中访问的本地开发域名,例如
servbay-yii2-test.local
。ServBay 会自动配置本地 DNS 将此域名指向127.0.0.1
。 - 网站类型: 选择
PHP
。 - PHP 版本: 选择您希望使用的 PHP 版本(例如
8.3
)。确保该版本已在 ServBay 中安装并启用。 - 网站根目录: 这是非常关键的一步。对于 Yii 2 基础应用模板,网站的公共入口点是项目根目录下的
web
目录。因此,网站根目录应设置为:/Applications/ServBay/www/servbay-yii2-app/web
。
- 名字: 输入一个易于识别的名称,例如
- 保存并应用: 保存您的网站配置。ServBay 会自动重新加载 Web 服务器配置以使其生效。
详细的网站设置步骤可以参考 ServBay 的官方文档:添加第一个网站。
ServBay 会为您的本地开发域名自动签发并信任 SSL 证书(通过 ServBay User CA 或 ServBay Public CA),因此您可以使用 HTTPS 访问您的网站。
添加示例代码以演示功能
为了演示数据库和缓存的使用,我们可以在 Yii 2 的默认控制器中添加一些示例操作。
编辑项目根目录下的 controllers/SiteController.php
文件,添加以下方法到 SiteController
类中:
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\web\Response;
use yii\db\Exception as DbException; // 导入数据库异常类
class SiteController extends Controller
{
/**
* Displays homepage.
*
* @return string
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Demonstrates Memcached usage.
*
* @return Response
*/
public function actionMemcached()
{
$cache = Yii::$app->cache;
$key = 'my_memcached_test_key';
$data = 'Hello Memcached from ServBay!';
$duration = 60; // Cache for 60 seconds
if ($cache->set($key, $data, $duration)) {
$value = $cache->get($key);
return $this->asText("Memcached set successfully. Retrieved value: " . $value);
} else {
return $this->asText("Failed to set data in Memcached. Please check Memcached service and configuration.");
}
}
/**
* Demonstrates Redis usage.
*
* @return Response
*/
public function actionRedis()
{
$redis = Yii::$app->redis;
$key = 'my_redis_test_key';
$data = 'Hello Redis from ServBay!';
try {
if ($redis->set($key, $data)) {
$value = $redis->get($key);
return $this->asText("Redis set successfully. Retrieved value: " . $value);
} else {
return $this->asText("Failed to set data in Redis. Please check Redis service and configuration.");
}
} catch (\yii\base\Exception $e) {
return $this->asText("Redis error: " . $e->getMessage() . ". Please check Redis service and configuration.");
}
}
/**
* Demonstrates adding a user to the database.
* Assumes a 'users' table exists.
*
* @return Response
*/
public function actionMysqlAdd() // Can be used for PostgreSQL as well with correct config
{
try {
$count = Yii::$app->db->createCommand()->insert('users', [
'name' => 'ServBay Demo User', // 使用品牌相关的演示名称
'email' => '[email protected]', // 使用品牌相关的演示邮箱
])->execute();
return $this->asText("User added successfully. Rows affected: " . $count);
} catch (DbException $e) {
return $this->asText("Failed to add user to database. Error: " . $e->getMessage() . ". Please check database service, configuration, and ensure 'users' table exists.");
}
}
/**
* Demonstrates fetching users from the database.
* Assumes a 'users' table exists.
*
* @return Response
*/
public function actionMysql() // Can be used for PostgreSQL as well with correct config
{
try {
$users = Yii::$app->db->createCommand('SELECT id, name, email FROM users')->queryAll();
// 格式化输出,避免直接返回敏感字段或格式混乱
$output = "Fetched Users:\n";
foreach ($users as $user) {
$output .= "- ID: {$user['id']}, Name: {$user['name']}, Email: {$user['email']}\n";
}
return $this->asText($output);
} catch (DbException $e) {
return $this->asText("Failed to fetch users from database. Error: " . $e->getMessage() . ". Please check database service, configuration, and ensure 'users' table exists.");
}
}
// 如果您使用 PostgreSQL,可以添加单独的 action 方法,但通常共用 db 组件即可
// public function actionPgsqlAdd() { ... }
// public function actionPgsql() { ... }
/**
* Formats output as plain text.
* @param string $text
* @return Response
*/
protected function asText($text)
{
Yii::$app->response->format = Response::FORMAT_RAW;
Yii::$app->response->getHeaders()->add('Content-Type', 'text/plain');
return $text;
}
/**
* Formats output as JSON.
* @param mixed $data
* @return Response
*/
protected function asJson($data)
{
Yii::$app->response->format = Response::FORMAT_JSON;
return $data;
}
}
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
请注意,我在 actionMysqlAdd
和 actionMysql
中添加了错误处理,并稍微修改了输出格式,使其更清晰。同时,修改了示例用户名和邮箱以符合 ServBay 品牌示例规范。
编辑项目根目录下的 views/site/index.php
文件,这是 actionIndex
对应的视图文件。您可以保留默认内容或进行修改:
<?php
/* @var $this yii\web\View */
/* @var $name string */
/* @var $message string */
/* @var $exception Exception */
use yii\helpers\Html;
$this->title = 'My Yii2 Application on ServBay'; // 更新标题
?>
<div class="site-index">
<div class="jumbotron">
<h1>Congratulations!</h1>
<p class="lead">You have successfully created your Yii2 application and configured it with ServBay!</p>
<p><a class="btn btn-lg btn-success" href="https://www.yiiframework.com">Get started with Yii</a></p>
</div>
<div class="body-content">
<h2>Demonstrations</h2>
<ul>
<li><a href="<?= Html::toRoute('site/memcached') ?>">Test Memcached</a></li>
<li><a href="<?= Html::toRoute('site/redis') ?>">Test Redis</a></li>
<li><a href="<?= Html::toRoute('site/mysql-add') ?>">Add a user to DB</a> (Requires 'users' table)</li>
<li><a href="<?= Html::toRoute('site/mysql') ?>">Fetch users from DB</a> (Requires 'users' table)</li>
</ul>
<p>Please ensure Memcached, Redis, and your chosen database (MySQL/PostgreSQL) services are running in ServBay and configured correctly in `config/web.php` and `config/db.php`.</p>
<p>For database examples, you need to create the 'users' table using Yii migrations (see below).</p>
</div>
</div>
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
我在视图中添加了链接,方便您测试新添加的控制器动作。
关系型数据库:创建表结构 (迁移)
要运行数据库相关的示例 (actionMysqlAdd
, actionMysql
),您需要在数据库中创建 users
表。Yii 框架推荐使用数据库迁移 (Migrations) 来管理数据库 schema 的变更。
运行 Gii 工具创建迁移文件: 打开终端,确保在项目根目录
/Applications/ServBay/www/servbay-yii2-app
下,运行 Yii 控制台命令来创建一个新的迁移文件。bashphp yii migrate/create create_users_table
1系统会提示您确认,输入
yes
并回车。这会在项目的migrations
目录下创建一个新的 PHP 文件,文件名类似于mYYYYMMDD_HHMMSS_create_users_table.php
。编辑迁移文件: 打开刚刚创建的迁移文件,编辑其
up()
方法来定义users
表的结构。php<?php use yii\db\Migration; /** * Handles the creation of table `{{%users}}`. */ class mXXXXXXXXXXXXXX_create_users_table extends Migration // XXXXXXXXXXXXXX 是时间戳 { /** * {@inheritdoc} */ public function up() { $this->createTable('{{%users}}', [ // 使用 {{%users}} 支持表前缀(如果配置了) 'id' => $this->primaryKey(), 'name' => $this->string()->notNull(), 'email' => $this->string()->notNull()->unique(), 'created_at' => $this->timestamp()->defaultExpression('CURRENT_TIMESTAMP'), 'updated_at' => $this->timestamp()->defaultExpression('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), ]); // 可选:创建索引以提高查询效率 $this->createIndex( 'idx-users-email', '{{%users}}', 'email', true // true 表示是唯一索引 ); } /** * {@inheritdoc} */ public function down() { // 删除索引 $this->dropIndex( 'idx-users-email', '{{%users}}' ); // 删除表 $this->dropTable('{{%users}}'); } }
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
41
42
43
44
45
46请将
mXXXXXXXXXXXXXX_create_users_table
替换为您实际生成的文件名。运行迁移: 在终端中,确保仍在项目根目录,运行 Yii 控制台命令来执行迁移,这将根据
up()
方法的定义在数据库中创建users
表。bashphp yii migrate
1系统会提示您确认,输入
yes
并回车。如果一切顺利,您将看到表创建成功的提示。
访问网站并测试
现在,您可以打开浏览器,访问您在 ServBay 中配置的域名 https://servbay-yii2-test.local
。
- 访问
https://servbay-yii2-test.local
:您应该看到 Yii 2 基础应用模板的欢迎页面,以及我们添加到views/site/index.php
中的演示链接。 - 点击 "Test Memcached" 链接或访问
https://servbay-yii2-test.local/index.php?r=site/memcached
:如果 Memcached 服务正常运行且配置正确,您应该看到 "Memcached set successfully..." 的文本输出。 - 点击 "Test Redis" 链接或访问
https://servbay-yii2-test.local/index.php?r=site/redis
:如果 Redis 服务正常运行且配置正确,您应该看到 "Redis set successfully..." 的文本输出。 - 点击 "Add a user to DB" 链接或访问
https://servbay-yii2-test.local/index.php?r=site/mysql-add
:如果数据库服务运行、配置正确且users
表已通过迁移创建,您应该看到 "User added successfully..." 的文本输出。每次访问此链接都会尝试添加一个新用户(除非 email 字段设置为唯一且已存在)。 - 点击 "Fetch users from DB" 链接或访问
https://servbay-yii2-test.local/index.php?r=site/mysql
:如果数据库服务运行、配置正确且users
表存在,您应该看到从users
表中查询到的用户列表。
如果遇到问题,请检查 ServBay 中对应的服务(PHP、Web 服务器、数据库、Memcached、Redis)是否正在运行,检查您的 Yii 2 项目配置 (config/db.php
, config/web.php
) 是否正确,以及数据库表是否已成功创建。
常见问题解答 (FAQ)
- 为什么访问域名时出现“无法访问此网站”或证书错误? 请确保您在 ServBay 的“网站”设置中正确添加了域名,并且 ServBay 应用程序本身正在运行。ServBay 会自动配置本地 DNS 和 SSL 证书。如果证书错误,请确保您已经信任了 ServBay User CA 或 ServBay Public CA。具体步骤请参考 ServBay 的相关文档。
- Composer 命令无法执行? 请确认您在 ServBay 应用界面中启用了 Composer 软件包,并且您是在 macOS 的终端中运行命令。ServBay 会自动将内置的 Composer 添加到您的 PATH 中。
- 数据库连接失败? 请检查 ServBay 中对应的数据库服务(MySQL/PostgreSQL)是否正在运行。检查
config/db.php
中的dsn
,username
,password
是否与 ServBay 中数据库的配置匹配。同时,确认您已经在数据库中创建了servbay_yii2_app
这个数据库。您可以使用 ServBay 自带的 Adminer 工具来验证数据库连接和查看数据库列表。 - Memcached/Redis 连接失败? 请检查 ServBay 中对应的 Memcached/Redis 服务是否正在运行。检查
config/web.php
中 Memcached/Redis 组件配置的host
和port
是否正确(默认应为127.0.0.1
和对应服务的默认端口)。 - 数据库迁移 (
php yii migrate
) 失败? 请确认您已正确配置config/db.php
文件,并且数据库服务正在运行且数据库已创建。迁移命令需要能够连接到数据库才能执行。 - 为什么
actionMysqlAdd
/actionMysql
提示表不存在? 您需要先运行数据库迁移命令php yii migrate
来创建users
表。 - 如何查看 PHP 错误日志? ServBay 将 PHP 错误日志、Web 服务器日志等都集中管理。您可以在 ServBay 应用界面的“日志”部分查看详细日志,这有助于诊断问题。
总结
通过 ServBay,您可以轻松地在 macOS 上搭建一个功能齐全的本地开发环境来运行 Yii 2 项目。ServBay 预装的 Composer、PHP 版本管理、内置的数据库和缓存服务以及便捷的网站配置功能,极大地简化了 Yii 2 项目的搭建和开发流程。遵循本指南,您应该能够快速启动您的 Yii 2 开发之旅,并利用 ServBay 提供的各种工具来提升效率。
祝您开发愉快!