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 rich set of features and tools to help developers efficiently build scalable, high-quality websites. Yii 2 is widely favored for its exceptional performance, flexible architecture, and robust built-in features such as caching, security, and support for RESTful API development.
Key Features and Advantages of Yii 2
- High Performance: Yii 2 is meticulously optimized to handle high-concurrency requests, ideal for building performance-sensitive applications.
- Modular Design: The framework is highly modular, enabling developers to organize code and reuse components easily.
- Security: Comes with multiple security features including input validation, output filtering, CSRF/XSS protection, and authentication/authorization frameworks.
- Ease of Use: Provides a concise, intuitive API and thorough documentation, lowering the learning curve for developers getting started.
- Strong Community Support: Maintains an active developer community and a wealth of third-party extensions for quick problem-solving.
- Integrated Tools: Offers command-line tools for tasks such as database migration and code generation to boost development efficiency.
Yii 2 is the ideal choice for building enterprise-level applications, RESTful APIs, portals, and diverse web projects.
Running Yii 2 Projects with ServBay
ServBay is a “ready-to-use” local web development environment built for both macOS and Windows. It integrates PHP, various databases (such as MySQL, PostgreSQL, MongoDB, and Redis), web servers (Caddy, Nginx), and other development tools (Composer, Node.js, Python, Go, Java, etc.), providing developers with a convenient and powerful platform.
This guide walks you through creating and running a Yii 2 basic application project using ServBay’s built-in PHP environment, Composer tool, and database services. You'll use ServBay’s "Websites" feature to configure the local web server and demonstrate how to access and use basic project functionality in just a few steps.
Prerequisites
Before you begin, ensure that you have:
- Successfully installed and are running ServBay on macOS or Windows.
- Installed and enabled the desired PHP version in ServBay (e.g., PHP 8.3 or above).
- Installed and enabled your target database service (e.g., MySQL or PostgreSQL) and caching services (Memcached and Redis) in ServBay.
You can manage installed packages and monitor their status directly from ServBay’s main interface.
Creating a Yii 2 Project
TIP
ServBay recommends storing your project files in the following directories. This helps keep your file structure organized and facilitates site management using ServBay’s “Websites” feature:
- macOS:
/Applications/ServBay/www
- Windows:
C:\ServBay\www
Composer: ServBay comes with Composer pre-installed, so you don’t need to install it separately. You can run the
composer
command directly from your terminal.Create Project Directory: Open a terminal, navigate to ServBay’s default web root, and create a new project folder.
macOS:
bashcd /Applications/ServBay/www mkdir servbay-yii2-app cd servbay-yii2-app
1
2
3Windows:
cmdcd C:\ServBay\www mkdir servbay-yii2-app cd servbay-yii2-app
1
2
3Create Yii 2 Project with Composer: In the
servbay-yii2-app
directory, run the Composer command to initialize a new Yii 2 basic application template.bashcomposer create-project --prefer-dist yiisoft/yii2-app-basic .
1This command will download the Yii 2 template and its dependencies into the current directory (
.
). Wait for Composer to finish downloading and installing.Navigate to Project Directory: Ensure your terminal is in the project root directory for subsequent commands.
macOS:
bashcd /Applications/ServBay/www/servbay-yii2-app
1Windows:
cmdcd C:\ServBay\www\servbay-yii2-app
1
Initial Configuration
After creating your Yii 2 project, configure basic settings, particularly the database connection and caching components.
Configure Database Connection: Edit the
config/db.php
file in your project’s root directory. Update the database connection settings based on your selected database service in ServBay (MySQL or PostgreSQL) and its configuration (default user is usuallyroot
, default password ispassword
, unless changed).First, create a new database for your project in ServBay, such as
servbay_yii2_app
. You can use ServBay’s built-in Adminer tool or your preferred database client (e.g., Sequel Ace, TablePlus). Adminer is accessible from the database section of the ServBay application.For MySQL:
php<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=127.0.0.1;dbname=servbay_yii2_app', // dbname: the database you created 'username' => 'root', // your database username 'password' => 'password', // your database password 'charset' => 'utf8mb4', // utf8mb4 is recommended for broad 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: your database name; port is usually 5432 'username' => 'root', // your database username 'password' => 'password', // your database password 'charset' => 'utf8', 'schemaMap' => [ 'pgsql' => [ 'class' => 'yii\pgsql\Schema', 'defaultSchema' => 'public', // PostgreSQL default schema ], ], ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15Choose and modify the
config/db.php
file according to your setup.Configure Cache and Redis Components: Edit the
config/web.php
file in your project root. Add or update thecomponents
section to configure Memcached and Redis. By default, Memcached uses port11211
and Redis uses6379
in ServBay.php<?php // ... other config 'components' => [ // ... other existing components like request, cache, user, errorHandler, log, urlManager 'cache' => [ 'class' => 'yii\caching\MemCache', 'servers' => [ [ 'host' => '127.0.0.1', 'port' => 11211, // Memcached default port 'weight' => 100, ], ], ], 'redis' => [ 'class' => 'yii\redis\Connection', 'hostname' => '127.0.0.1', 'port' => 6379, // Redis default port 'database' => 0, // Redis database index ], // ... other components ], // ... other config
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 Memcached and Redis services are running in ServBay. Note: Using Redis as cache requires the
yiisoft/yii2-redis
package (the basic template will install base dependencies; if you need more, you may need to runcomposer require yiisoft/yii2-redis
manually). Memcached typically usesyiisoft/yii2-memcached
. The template may already provide these dependencies.
Configuring the Web Server (ServBay Website)
Use ServBay’s “Websites” feature to configure your 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, look for and click “Websites” or a similar menu.
- Add a New Website: Click the button to add a new website (usually a
+
orAdd
). - Fill in Website Info:
- Name: Enter a recognizable name such as
My First Yii 2 Dev Site
. - Domain: Enter your desired local development domain, e.g.,
servbay-yii2-test.local
. ServBay will configure local DNS to point this domain to127.0.0.1
. - Site Type: Select
PHP
. - PHP Version: Choose your desired PHP version (e.g.,
8.3
). Make sure this version is installed and enabled in ServBay. - Document Root: This is crucial. For Yii 2 basic apps, the public entry point is the
web
directory inside your project root:- macOS:
/Applications/ServBay/www/servbay-yii2-app/web
- Windows:
C:\ServBay\www\servbay-yii2-app\web
- macOS:
- Name: Enter a recognizable name such as
- Save and Apply: Save your website configuration. ServBay will automatically reload the web server setup to apply changes.
See ServBay official documentation for detailed website setup steps: Add Your First Website.
ServBay will issue and trust SSL certificates for your local development domain (via ServBay User CA or ServBay Public CA), allowing you to access your website securely via HTTPS.
Add Example Code to Demonstrate Functionality
To demonstrate database and caching usage, add some example actions in Yii 2’s default controller.
Edit the controllers/SiteController.php
file in your project root and add the following methods inside the SiteController
class:
php
<?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', // Use brand-related demo name
'email' => 'demo-user@servbay.test', // Use brand-related demo email
])->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 direct exposure of sensitive fields or messy output
$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 may add separate action methods, but the db component is usually shared
// 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;
}
}
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
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
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: Error handling and output formatting have been added to actionMysqlAdd
and actionMysql
for clarity. Demo user names and emails use the ServBay branding.
Next, edit the views/site/index.php
file in your project root—the view for actionIndex
. You can keep the default content or update it as follows:
php
<?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>
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
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
This adds useful links for testing the new controller actions.
Relational Database: Creating Table Structure (Migration)
To run the database examples (actionMysqlAdd
, actionMysql
), you must create a users
table in your database. Yii recommends managing schema changes with database migrations.
Create Migration File with Gii Tool: Open a terminal, make sure you’re in the project root, then run the Yii console to generate a migration file.
Project root path:
- macOS:
/Applications/ServBay/www/servbay-yii2-app
- Windows:
C:\ServBay\www\servbay-yii2-app
bashphp yii migrate/create create_users_table
1The system will prompt you for confirmation; type
yes
. This creates a new PHP file in themigrations
directory—for example,mYYYYMMDD_HHMMSS_create_users_table.php
.- macOS:
Edit Migration File: Open the newly created migration file and define the
users
table schema in theup()
method.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 table prefixes 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 faster queries $this->createIndex( 'idx-users-email', '{{%users}}', 'email', true // true means a unique index ); } /** * {@inheritdoc} */ public function down() { // Drop the index $this->dropIndex( 'idx-users-email', '{{%users}}' ); // Drop the 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 your actual file name.Run Migration: In the terminal, from the project root, run the Yii console command to execute the migration, creating the
users
table as defined inup()
.bashphp yii migrate
1When prompted, type
yes
. If successful, you’ll see confirmation that the table was created.
Accessing the Website and Testing
Now open your browser and visit the domain you configured in ServBay, e.g., https://servbay-yii2-test.local
.
- Visit
https://servbay-yii2-test.local
: You should see the Yii 2 basic app welcome page and the demonstration links added toviews/site/index.php
. - Click "Test Memcached" or go to
https://servbay-yii2-test.local/index.php?r=site/memcached
: If Memcached is running and configured properly, you’ll see "Memcached set successfully..." text output. - Click "Test Redis" or go to
https://servbay-yii2-test.local/index.php?r=site/redis
: If Redis is operational and configured, you’ll see "Redis set successfully..." text. - Click "Add a user to DB" or visit
https://servbay-yii2-test.local/index.php?r=site/mysql-add
: If your database service is running, set up, and theusers
table is created, you’ll see "User added successfully..." output. Each visit tries to insert a new user (unless the email has a unique constraint and already exists). - Click "Fetch users from DB" or go to
https://servbay-yii2-test.local/index.php?r=site/mysql
: If everything is configured and theusers
table exists, you’ll see a list of users from the database.
If you have issues, check that the relevant services in ServBay (PHP, web server, database, Memcached, Redis) are running; confirm your Yii 2 configuration in config/db.php
and config/web.php
; and ensure the database table was created successfully.
Frequently Asked Questions (FAQ)
- Why do I get “Site can’t be reached” or certificate errors when accessing my domain? Make sure you’ve correctly added the domain in ServBay’s “Websites” settings and that the ServBay app is running. ServBay automatically sets up local DNS and SSL certificates. For certificate errors, ensure you’ve trusted the ServBay User CA or ServBay Public CA as per ServBay’s documentation.
- Composer command isn’t working? Confirm Composer is enabled in the ServBay interface and that you’re running commands from your macOS terminal. ServBay adds the built-in Composer to your PATH automatically.
- Database connection fails? Check that the relevant database service (MySQL/PostgreSQL) is running in ServBay, and ensure the
dsn
,username
, andpassword
inconfig/db.php
match ServBay’s configuration. Also, verify theservbay_yii2_app
database exists, using ServBay’s Adminer tool if necessary. - Memcached/Redis connection issues? Ensure the Memcached/Redis services are running in ServBay, and check the
host
andport
inconfig/web.php
(defaults are127.0.0.1
and the service’s default port). - Database migration (
php yii migrate
) fails? Confirm yourconfig/db.php
is correctly configured, the database service is running, and the database is created. Migration needs database connectivity. actionMysqlAdd
/actionMysql
reports that table doesn’t exist? Run the database migration commandphp yii migrate
to create theusers
table first.- Where can I view PHP error logs? ServBay manages PHP, web server, and other logs centrally. View detailed logs in ServBay’s “Logs” section in the interface to help diagnose issues.
Summary
With ServBay, you can easily set up a feature-rich local development environment for Yii 2 projects on macOS and Windows. ServBay’s preinstalled Composer, PHP version management, built-in databases, caching services, and intuitive website configuration greatly streamline Yii 2 project setup and development. By following this guide, you’ll be able to quickly launch your Yii 2 development journey and leverage ServBay’s tools for enhanced productivity.
Happy coding!