Creating and Running a Yii 2 Project in ServBay
Overview: What is Yii 2?
Yii 2 is a high-performance, component-based PHP framework designed for rapid development of modern web applications. It follows the MVC (Model-View-Controller) design pattern and offers a comprehensive set of powerful features and tools to help developers efficiently build scalable, high-quality web applications. Yii 2 is well-regarded for its exceptional performance, flexible architecture, and robust built-in features such as caching, security, and RESTful API development support.
Key Features and Advantages of Yii 2
- High Performance: Yii 2 is carefully optimized to handle high concurrency, making it suitable for building performance-sensitive applications.
- Modular Architecture: The framework is designed to be highly modular, allowing developers to organize code and reuse components conveniently.
- Security: Built-in security features include input validation, output filtering, CSRF/XSS protection, authentication, and authorization frameworks.
- Ease of Use: With its clean and intuitive API and thorough documentation, Yii 2 lowers the learning curve and enables developers to get started quickly.
- Strong Community Support: Boasts an active developer community and an extensive library of third-party extensions, making it easy to find help when needed.
- Integrated Tools: Includes command-line tools for database migrations, code generation, and other tasks to boost development efficiency.
Yii 2 is an ideal choice for building a range of web projects, including enterprise-level applications, RESTful APIs, and portals.
Running a Yii 2 Project with ServBay
ServBay is a local web development environment designed specifically for macOS, integrating PHP, multiple databases (such as MySQL, PostgreSQL, MongoDB, Redis), web servers (Caddy, Nginx), and other developer tools (like Composer, Node.js, Python, Go, Java, etc.). Its goal is to provide developers with a ready-to-use, hassle-free development platform.
This guide will walk you through creating and running a basic Yii 2 application using ServBay's built-in PHP environment, Composer, and database services. We’ll use the ServBay “Website” feature to configure the local web server and demonstrate project access and core functionalities in a few simple steps.
Prerequisites
Before you begin, make sure you have:
- Successfully installed and launched ServBay on your macOS system.
- Installed and enabled your desired version of PHP in ServBay (e.g., PHP 8.3 or later).
- Installed and enabled the database service (e.g., MySQL or PostgreSQL) and cache services (Memcached and Redis) you plan to use in ServBay.
You can view and manage installed packages and their status on the main screen of ServBay.
Creating a Yii 2 Project
TIP
It is recommended by ServBay to store your project files under the /Applications/ServBay/www
directory. This helps keep your file structure organized and makes it easier to manage projects with the ServBay “Website” feature.
Composer: ServBay already includes the Composer tool, so there’s no need to install it separately. You can use the
composer
command directly in your terminal.Create a Project Directory: Open your terminal, navigate to ServBay’s default web root, and create a new project directory.
bashcd /Applications/ServBay/www mkdir servbay-yii2-app cd servbay-yii2-app
1
2
3Create a Yii 2 Project with Composer: Inside the
servbay-yii2-app
directory, run the Composer command to create a new Yii 2 basic application template.bashcomposer create-project --prefer-dist yiisoft/yii2-app-basic .
1This command will download the Yii 2 Basic Application Template and all its dependencies into the current directory (
.
). Please wait patiently while Composer completes the download and installation.Enter the Project Directory: Make sure your terminal is in the project root directory,
/Applications/ServBay/www/servbay-yii2-app
. All subsequent commands should be executed here.bashcd /Applications/ServBay/www/servbay-yii2-app
1
Initial Configuration
After creating your Yii 2 project, you'll need to perform some basic configuration, particularly regarding database connection and component settings.
Configure Database Connection: Edit the
config/db.php
file in your project root. According to the database service you are running in ServBay (MySQL or PostgreSQL) and its configuration (by default, the user is usuallyroot
and the password ispassword
, unless you’ve changed it), update the connection details.First, create a new database for this project (e.g., named
servbay_yii2_app
) in ServBay's database service. You can use the built-in Adminer tool or your preferred database client (like Sequel Ace, TablePlus, etc.). Adminer is accessible from the database section in the ServBay application.For MySQL:
php<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=127.0.0.1;dbname=servbay_yii2_app', // dbname should match your created database 'username' => 'root', // Your database username 'password' => 'password', // Your database password 'charset' => 'utf8mb4', // utf8mb4 recommended for wide character support ];
1
2
3
4
5
6
7
8
9For PostgreSQL:
php<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'pgsql:host=127.0.0.1;port=5432;dbname=servbay_yii2_app', // dbname should match your created database, port is usually 5432 'username' => 'root', // Your database username 'password' => 'password', // Your database password 'charset' => 'utf8', 'schemaMap' => [ 'pgsql' => [ 'class' => 'yii\pgsql\Schema', 'defaultSchema' => 'public', // Default PostgreSQL schema ], ], ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15Please modify
config/db.php
according to your actual setup.Configure Cache and Redis Components: Edit the
config/web.php
file in your project root. Add or modify thecomponents
section to configure Memcached and Redis. ServBay’s default Memcached port is11211
, and Redis port is6379
.php<?php // ... other configuration items 'components' => [ // ... existing components such as request, cache, user, errorHandler, log, urlManager 'cache' => [ 'class' => 'yii\caching\MemCache', 'servers' => [ [ 'host' => '127.0.0.1', 'port' => 11211, // Default Memcached port 'weight' => 100, ], ], ], 'redis' => [ 'class' => 'yii\redis\Connection', 'hostname' => '127.0.0.1', 'port' => 6379, // Default Redis port 'database' => 0, // Redis DB index ], // ... other components ], // ... other configuration items
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
28Ensure you have started Memcached and Redis services within ServBay. Note: To use Redis as a cache, you need the
yiisoft/yii2-redis
package (Composer will install basic dependencies duringcreate-project
; for extras, you may need tocomposer require yiisoft/yii2-redis
manually). Memcached typically usesyiisoft/yii2-memcached
. The basic template may already include these dependencies.
Configuring the Web Server (ServBay Website Feature)
Utilize ServBay’s “Website” feature to configure a local web server (Caddy or Nginx) to point to your Yii 2 project.
- Open ServBay App: Launch the ServBay application.
- Navigate to Website Settings: In the ServBay interface, locate and click on “Websites” or the equivalent section.
- Add a New Website: Click the button to add a new website (usually marked as
+
orAdd
). - Fill in Website Details:
- Name: Enter a recognizable name, e.g.,
My First Yii 2 Dev Site
. - Domain: Enter a local development domain to access in your browser, such as
servbay-yii2-test.local
. ServBay will automatically configure local DNS to point this domain to127.0.0.1
. - Website Type: Select
PHP
. - PHP Version: Choose your preferred PHP version (e.g.,
8.3
). Make sure it’s installed and enabled in ServBay. - Web Root Directory: This step is crucial. For Yii 2’s basic application template, the web root is the
web
directory inside your project root. So, set the website root directory to:/Applications/ServBay/www/servbay-yii2-app/web
.
- Name: Enter a recognizable name, e.g.,
- Save and Apply: Save your website configuration. ServBay will automatically reload the web server config to apply your changes.
For detailed steps on website configuration, refer to the ServBay official documentation: Adding Your First Website.
ServBay will automatically issue and trust SSL certificates (via ServBay User CA or ServBay Public CA) for your local development domains, enabling you to access your site via HTTPS.
Adding Sample Code for Functionality Demonstration
To demonstrate database and cache usage, you can add sample actions to Yii 2's default controller.
Edit the controllers/SiteController.php
file in your project root and add the following methods to the SiteController
class:
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\web\Response;
use yii\db\Exception as DbException; // Import database exception class
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', // Demo name with branding
'email' => '[email protected]', // Demo email with branding
])->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();
// Format output to avoid returning sensitive fields or messy formatting
$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.");
}
}
// If you use PostgreSQL, you can add separate action methods, but usually the db component suffices.
// 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
Note: The actionMysqlAdd
and actionMysql
methods include error handling and improved output formatting. The sample username and email have also been updated to reflect ServBay branding.
Edit your project’s views/site/index.php
file, which corresponds to the actionIndex
method. You can leave the default content or modify as below:
<?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'; // Update title
?>
<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
Links have been added to the view to help you quickly test the new controller actions.
Relational Database: Creating Table Structure (Migrations)
To run the database examples (actionMysqlAdd
, actionMysql
), you need to create a users
table in your database. Yii recommends using database migrations to manage schema changes.
Generate a Migration File Using Gii or Console: Open the terminal, ensure you’re in the project root (
/Applications/ServBay/www/servbay-yii2-app
), and run the Yii console command to create a new migration.bashphp yii migrate/create create_users_table
1The system will prompt for confirmation; type
yes
and press Enter. This will create a new PHP file under themigrations
directory, named something likemYYYYMMDD_HHMMSS_create_users_table.php
.Edit the Migration File: Open the newly created migration file and edit the
up()
method to define the structure of theusers
table.php<?php use yii\db\Migration; /** * Handles the creation of table `{{%users}}`. */ class mXXXXXXXXXXXXXX_create_users_table extends Migration // XXXXXXXXXXXXXX is the timestamp { /** * {@inheritdoc} */ public function up() { $this->createTable('{{%users}}', [ // {{%users}} supports prefix usage if configured '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'), ]); // Optional: Add index for efficient querying $this->createIndex( 'idx-users-email', '{{%users}}', 'email', true // true for unique index ); } /** * {@inheritdoc} */ public function down() { // Drop index $this->dropIndex( 'idx-users-email', '{{%users}}' ); // Drop table $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
46Replace
mXXXXXXXXXXXXXX_create_users_table
with the actual filename generated for you.Run the Migration: In the terminal, still within your project root, execute the Yii command to run the migration, which will create the
users
table as defined in theup()
method.bashphp yii migrate
1Confirm when prompted. If successful, you will see a message stating the table was created.
Access the Site and Test
You can now open your browser and visit the domain you configured in ServBay, e.g., https://servbay-yii2-test.local
.
- Go to
https://servbay-yii2-test.local
: You should see the Yii 2 Basic Application Welcome page and the demonstration links you added toviews/site/index.php
. - Click the "Test Memcached" link or navigate to
https://servbay-yii2-test.local/index.php?r=site/memcached
: If Memcached is running and configured correctly, you should see the message "Memcached set successfully...". - Click "Test Redis" or go to
https://servbay-yii2-test.local/index.php?r=site/redis
: If Redis is running and configured correctly, you’ll see "Redis set successfully...". - Click "Add a user to DB" or visit
https://servbay-yii2-test.local/index.php?r=site/mysql-add
: If your database is running, properly configured, and theusers
table exists, you'll get "User added successfully...". Each visit attempts to add a new user (unless the email field is unique and already exists). - Click "Fetch users from DB" or visit
https://servbay-yii2-test.local/index.php?r=site/mysql
: This should display a list of users found in theusers
table, provided the service and configuration are correct.
If issues arise, check that the relevant services (PHP, web server, database, Memcached, Redis) are running in ServBay, and ensure your Yii 2 project configuration files (config/db.php
, config/web.php
) are correct, and your database tables were successfully created.
Frequently Asked Questions (FAQ)
- Why do I get “Site can’t be reached” or certificate errors when accessing the domain? Make sure you have added the domain correctly under ServBay’s “Websites” section and that ServBay itself is running. ServBay auto-configures local DNS and SSL certificates. If you encounter certificate errors, make sure you have trusted the ServBay User CA or ServBay Public CA. For details, refer to the relevant ServBay documentation.
- Composer command not working? Ensure that the Composer package is enabled in the ServBay application and that you’re running the commands in the macOS terminal. ServBay automatically adds its built-in Composer to your PATH.
- Database connection fails? Check that your database service (MySQL/PostgreSQL) is running in ServBay. Make sure the
dsn
,username
, andpassword
inconfig/db.php
match your actual setup. Also, confirm that theservbay_yii2_app
database exists. Use ServBay’s built-in Adminer tool to check your database connection and view databases. - Memcached/Redis connection fails? Check that the respective Memcached/Redis service is running in ServBay. Ensure the
host
andport
for Memcached/Redis inconfig/web.php
are correct (127.0.0.1
and the corresponding default port). - Database migration (
php yii migrate
) fails? Confirm thatconfig/db.php
is correctly configured, the database service is running, and the database has been created. The migration command needs a working database connection. - Why do I get “table not found” errors from
actionMysqlAdd
/actionMysql
? You need to run the migration commandphp yii migrate
to create theusers
table first. - How can I view PHP error logs? ServBay consolidates PHP error logs, web server logs, and more in one place. Use the "Logs" section in the ServBay application for detailed logs, which help with troubleshooting.
Summary
With ServBay, you can easily set up a comprehensive local development environment on macOS for running Yii 2 projects. ServBay’s built-in Composer, PHP version management, integrated database and cache services, and straightforward website configuration greatly simplify the process of bootstrapping and developing Yii 2 applications. By following this guide, you can quickly kickstart your Yii 2 development journey and take advantage of all ServBay’s productivity features.
Happy coding!