yiisoft/yii2
Yii 2 is a fast, secure, and extensible PHP framework for building modern web apps. It includes powerful MVC architecture, ORM (ActiveRecord), caching, RBAC, REST APIs, code generation, and excellent performance for large-scale projects.
Installation
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
Navigate to the project directory and run:
composer install
First Use Case: Basic CRUD
config/web.php:
'enableGii' => true,
http://your-app.dev/gii and generate a CRUD for a model (e.g., Post).Key Files to Review
config/web.php: Core application configuration (routes, middleware, components).models/: Business logic and database interactions.controllers/: HTTP request handling.views/: Presentation layer (Twig or PHP templates).MVC Integration
yii\base\Model or yii\db\ActiveRecord for database interactions.
namespace app\models;
use yii\db\ActiveRecord;
class Post extends ActiveRecord { /* ... */ }
public function actionView($id) {
$post = Post::findOne($id);
return $this->render('view', ['post' => $post]);
}
GridView, Url::to()).Database Operations
$post = new Post();
$post->title = 'Hello Yii';
$post->save();
$posts = Post::find()->where(['status' => 1])->all();
Routing and URL Handling
config/web.php:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'posts/<id:\d+>' => 'post/view',
],
],
Url::to() in views/controllers for dynamic links.Middleware and Filters
public function behaviors() {
return [
'access' => ['class' => \yii\filters\AccessControl::class],
];
}
beforeAction for pre-processing:
public function beforeAction($action) {
if ($action->id === 'index' && !$this->user->isGuest) {
return $this->redirect(['site/index']);
}
return parent::beforeAction($action);
}
Asset Management
AssetBundle:
namespace app\assets;
use yii\web\AssetBundle;
class AppAsset extends AssetBundle {
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = ['css/site.css'];
public $js = ['js/site.js'];
}
AppAsset::register($this);
Authentication and Authorization
yii\web\User for sessions/auth:
if (Yii::$app->user->isGuest) {
return $this->goHome();
}
yii\rbac\PhpManager:
$auth = Yii::$app->authManager;
$auth->addRole('admin');
$auth->addPermission('createPost');
$auth->addChild('admin', 'createPost');
API Development
yii\rest\ActiveController:
namespace app\controllers;
use yii\rest\ActiveController;
class PostController extends ActiveController {
public $modelClass = 'app\models\Post';
}
config/web.php:
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'rules' => [
'api/v1/posts' => 'post/index',
],
],
],
Case Sensitivity in Routes
lowercaseUrl in UrlManager if needed:
'urlManager' => [
'lowercaseUrl' => true,
],
Session Configuration
session component is properly configured in config/web.php:
'components' => [
'session' => [
'class' => 'yii\web\CookieSession',
'timeout' => 120,
],
],
'session' => [
'class' => 'yii\redis\Session',
'timeout' => 120,
],
ActiveRecord Caching
Yii::$app->db->enableQueryCache = true;
Yii::$app->cache = [
'class' => 'yii\caching\FileCache',
];
Gii Security
'modules' => [
'gii' => [
'class' => 'yii\gii\Module',
'allowedIPs' => ['127.0.0.1', '::1'],
],
],
Event Handling
public function init() {
parent::init();
$this->on('eventName', function($event) {
// Handle event
});
}
Translation Quirks
sourceLanguage and translations are set in i18n:
'i18n' => [
'sourceLanguage' => 'en-US',
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@app/messages',
],
],
],
Yii::t() for translations:
Yii::t('app', 'Hello {name}', ['name' => 'World']);
Asset Publishing
Yii::$app->assetManager->publish($assetBundle);
php yii asset/index
Error Handling
config/web.php:
'components' => [
'errorHandler' => [
'errorAction' => 'site/error',
],
],
Yii::error() and Yii::warning() for logging.Logging
log component:
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
Database Debugging
'components' => [
'db' => [
'enableProfiling' => true,
'enableLogging' => true,
],
],
Yii::$app->db->getLogger()->logs.Common Issues
urlManager rules and web.php base URL.Csrf::validate() is called in forms.session component timeout and cookie settings.Custom Components
yii\db\Connection) for reusable logic:
namespace app\components;
use yii\db\Connection;
class CustomDb extends Connection {
public function customQuery() { /* ... */ }
}
config/web.php:
'components' => [
'db' => ['class' => 'app\components\CustomDb'],
],
Behaviors
public function behaviors() {
return [
'timestamp' => [
'class' => 'yii\
How can I help you explore Laravel packages today?