Meet Yii
Yii is a framework: a ready-made skeleton of a PHP site where common tasks such as database access, validated forms and sortable tables are already solved. This course covers Yii 2 (version 2.0.x) and the basic project template, the simplest option for a single site.
Installation
You need PHP 8 and Composer, the program that downloads PHP libraries. A project is created with one command:
composer create-project --prefer-dist yiisoft/yii2-app-basic blog
cd blog
php yii serveThe first command downloads the template into the blog folder, the last one starts the built-in server. Open http://localhost:8080 and you will see the start page with the Home, About, Contact and Login menu.
Project folders
blog/
├── config/ settings: web.php, db.php, console.php, params.php
├── controllers/ controllers, the code of the pages
├── models/ models, the data and its validation rules
├── views/ page templates
├── web/ the site root: index.php, css, images
├── migrations/ changes to the database structure
├── commands/ console commands
├── assets/ descriptions of style and script bundles
├── mail/ email templates
├── runtime/ logs and cache, created while the site runs
├── vendor/ libraries installed by Composer
└── yii the file that runs console commandsMost of the time you will work in controllers, models and views. The vendor and runtime folders are not edited by hand.
The app namespace
All project classes live in the app namespace, and it repeats the file path: the file controllers/SiteController.php contains the class app\controllers\SiteController, the file models/ContactForm.php contains app\models\ContactForm. This is how Yii finds classes on its own, so you never include files manually.
The first page
Create the file controllers/HelloController.php by hand:
// controllers/HelloController.php
namespace app\controllers;
use yii\web\Controller;
class HelloController extends Controller
{
public function actionIndex(): string
{
return 'Hello, Yii!';
}
}Open http://localhost:8080/index.php?r=hello/index and the page shows the line "Hello, Yii!". The r parameter is the route: the controller name and the method name without the action prefix. The page did not have to be registered anywhere.
The debug toolbar
At the bottom of every page there is a bar with the Yii logo: the debug toolbar. It shows the execution time, database queries and log records. A click opens the details. The toolbar works only in development mode.
About versions
There is also Yii 3, a set of separate packages built differently. Most working projects are written in Yii 2, so everything below is about it.
Common mistake
The php yii ... commands are run inside the project folder, where the yii file is. Started from another folder, PHP answers Could not open input file: yii. Go to the project first with cd blog.