Create and run Yii 2 project
What is Yii 2?
Yii 2 is a high-performance PHP framework suitable for developing modern web applications. It follows the MVC (Model-View-Controller) design pattern and provides a complete set of rich features and tools, allowing developers to quickly build high-quality web applications. Yii 2 is efficient, flexible, and extendable, making it a preferred framework for many developers.
Key Features and Benefits of Yii 2
- High Performance: Yii 2 is a high-performance framework capable of handling high concurrent requests.
- Modular: Offers rich modules and plugins for easy extension and customization of features.
- Security: Built-in security features like input validation, output filtering, CSRF protection, etc.
- Easy to Use: Simplified APIs and rich documentation make it easy for developers to get started quickly.
- Strong Community Support: Active developer community and numerous third-party extensions.
Yii 2 helps developers quickly build high-performance, high-quality web applications suitable for projects of various scales.
Create and Run Yii 2 Project Using ServBay
In this article, we will use the PHP environment provided by ServBay to create and run a Yii 2 project. We will utilize ServBay's 'Host' feature to set up a web server and access the project through simple configuration.
Note: If you were a NGINX or Apache user
ServBay uses Caddy as the default web server. There are some key changes to note for users migrating from NGINX or Apache to ServBay:
Caddy Configuration
ServBay comes with built-in Caddy, and the default configuration has been optimized and debugged. Developers can manage the site using ServBay's 'Host' feature without manually modifying the Caddy configuration file.
Rewrite Rules and .htaccess
In NGINX and Apache, developers often need to write their own Rewrite rules and .htaccess files to handle URL rewriting and other configurations. However, ServBay comes pre-configured with Caddy's rules, so unless there are special needs, developers do not need to write these rules themselves.
Learn More
For more related information, refer to Rewrite and htaccess, How to Migrate Apache Website to ServBay, How to Migrate NGINX Website to ServBay.
Create Yii 2 Project
TIP
ServBay suggests developers place websites in the /Applications/ServBay/www
directory for easy management.
Install Composer
Composer is pre-installed with ServBay, so no separate installation is needed.
Create Yii 2 Project
Use Composer to create a new Yii 2 basic application template project:
bashcd /Applications/ServBay/www mkdir servbay-yii2-app cd servbay-yii2-app composer create-project --prefer-dist yiisoft/yii2-app-basic .
1
2
3
4Enter the Project Directory
Enter the newly created Yii 2 project directory:
bashcd /Applications/ServBay/www/servbay-yii2-app
1
Initialize Configuration
Configure Database Connection
Configure the database connection information in the
config/db.php
file:phpreturn [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=127.0.0.1;dbname=servbay_yii2_app', 'username' => 'root', 'password' => 'password', 'charset' => 'utf8', ];
1
2
3
4
5
6
7Configure Cache and Redis Components
Add cache and Redis component configuration in the
config/web.php
file:php'components' => [ 'cache' => [ 'class' => 'yii\caching\MemCache', 'servers' => [ [ 'host' => '127.0.0.1', 'port' => 11211, 'weight' => 100, ], ], ], 'redis' => [ 'class' => 'yii\redis\Connection', 'hostname' => '127.0.0.1', 'port' => 6379, 'database' => 0, ], // ... ],
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Configure Web Server
Use ServBay's 'Host' feature to access the Yii 2 project through the web server. In ServBay's 'Host' settings, add a new host:
- Name:
My First Yii 2 Dev Site
- Domain:
servbay-yii2-test.local
- Site Type:
PHP
- PHP Version: Select
8.3
- Site Root Directory:
/Applications/ServBay/www/servbay-yii2-app/web
For detailed setup steps, refer to Add Your First Website.
Add Sample Code
Add the following code in the controllers/SiteController.php
file:
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\web\Response;
class SiteController extends Controller
{
public function actionIndex()
{
return $this->render('index');
}
public function actionMemcached()
{
$cache = Yii::$app->cache;
$cache->set('key', 'Hello Memcached!', 60);
$value = $cache->get('key');
return $this->asText($value);
}
public function actionRedis()
{
$redis = Yii::$app->redis;
$redis->set('key', 'Hello Redis!');
$value = $redis->get('key');
return $this->asText($value);
}
public function actionMysqlAdd()
{
Yii::$app->db->createCommand()->insert('users', [
'name' => 'ServBay',
'email' => '[email protected]',
])->execute();
return $this->asText('User added');
}
public function actionMysql()
{
$users = Yii::$app->db->createCommand('SELECT * FROM users')->queryAll();
return $this->asJson($users);
}
}
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
Add the following code in the views/site/index.php
file:
<?php
/* @var $this yii\web\View */
$this->title = 'My Yii2 Application';
?>
<div class="site-index">
<div class="jumbotron">
<h1>Congratulations!</h1>
<p class="lead">You have successfully created your Yii2 application.</p>
</div>
</div>
2
3
4
5
6
7
8
9
10
Access the Website
Open your browser and visit the following URL:
https://servbay-yii2-test.local
: You will see the default Yii 2 welcome page.
NoSQL Database Examples
Memcached Example
Install Memcached Extension
The Memcached extension is already pre-installed in ServBay, so no additional installation is needed.
Configure Memcached
Configure Memcached connection information in the
config/web.php
file:php'components' => [ 'cache' => [ 'class' => 'yii\caching\MemCache', 'servers' => [ [ 'host' => '127.0.0.1', 'port' => 11211, 'weight' => 100, ], ], ], // ... ],
1
2
3
4
5
6
7
8
9
10
11
12
13Use Memcached
Use cache in the controller:
phppublic function actionMemcached() { $cache = Yii::$app->cache; $cache->set('key', 'Hello Memcached!', 60); $value = $cache->get('key'); return $this->asText($value); }
1
2
3
4
5
6
7
Redis Example
Install Redis Extension
The Redis extension is already pre-installed in ServBay, so no additional installation is needed.
Configure Redis
Configure Redis connection information in the
config/web.php
file:php'components' => [ 'redis' => [ 'class' => 'yii\redis\Connection', 'hostname' => '127.0.0.1', 'port' => 6379, 'database' => 0, ], // ... ],
1
2
3
4
5
6
7
8
9Use Redis
Use cache in the controller:
phppublic function actionRedis() { $redis = Yii::$app->redis; $redis->set('key', 'Hello Redis!'); $value = $redis->get('key'); return $this->asText($value); }
1
2
3
4
5
6
7
Relational Database Examples
Create Database Structure and Migration Files
Create Migration File
Use Yii 2's Gii tool to create a migration file:
bashphp yii migrate/create create_users_table
1Edit Migration File
Find the newly created migration file in the
migrations
directory and edit it to define the database table structure:phppublic function up() { $this->createTable('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'), ]); }
1
2
3
4
5
6
7
8
9
10Run Migration
Use Yii 2's migration command to run the migration and create the database table:
bashphp yii migrate
1
MySQL Example
Configure MySQL
Configure MySQL connection information in the
config/db.php
file:phpreturn [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=127.0.0.1;dbname=servbay_yii2_app', 'username' => 'root', 'password' => 'password', 'charset' => 'utf8', ];
1
2
3
4
5
6
7Write User Data
Write user data in the controller:
phppublic function actionMysqlAdd() { Yii::$app->db->createCommand()->insert('users', [ 'name' => 'ServBay', 'email' => '[email protected]', ])->execute(); return $this->asText('User added'); }
1
2
3
4
5
6
7
8Use MySQL
Call the database in the controller:
phppublic function actionMysql() { $users = Yii::$app->db->createCommand('SELECT * FROM users')->queryAll(); return $this->asJson($users); }
1
2
3
4
5
PostgreSQL Example
Configure PostgreSQL
Configure PostgreSQL connection information in the
config/db.php
file:phpreturn [ 'class' => 'yii\db\Connection', 'dsn' => 'pgsql:host=127.0.0.1;dbname=servbay_yii2_app', 'username' => 'root', 'password' => 'password', 'charset' => 'utf8', ];
1
2
3
4
5
6
7Write User Data
Write user data in the controller:
phppublic function actionPgsqlAdd() { Yii::$app->db->createCommand()->insert('users', [ 'name' => 'ServBay', 'email' => '[email protected]', ])->execute(); return $this->asText('User added'); }
1
2
3
4
5
6
7
8Use PostgreSQL
Call the database in the controller:
phppublic function actionPgsql() { $users = Yii::$app->db->createCommand('SELECT * FROM users')->queryAll(); return $this->asJson($users); }
1
2
3
4
5
Through the above steps, you have successfully created and run a Yii 2 project, managed it using the functionalities provided by ServBay, connected various databases, and called the data. Hope this article helps you quickly get started with Yii 2 and apply it to your projects.