Yii2 provides a modular structure, allowing developers to create independent, reusable, and self-contained modules. A module in Yii2 is like a mini-application, having its own controllers, models, views, and configurations.
In this tutorial, we will cover:
1. Run Gii by visiting:
http://your-app.com/index.php?r=gii2 Select Module Generator.
3. Set:
adminapp\modules\admin4. Click Generate to create the module.
Alternatively, create the module manually under modules/admin:
modules/
admin/
controllers/
DefaultController.php
models/
views/
default/
index.php
AdminModule.phpIn modules/admin/AdminModule.php:
namespace app\modules\admin;
class AdminModule extends \yii\base\Module
{
public $controllerNamespace = 'app\modules\admin\controllers';
public function init()
{
parent::init();
// Custom initialization code
}
}In modules/admin/controllers/DefaultController.php:
namespace app\modules\admin\controllers;
use yii\web\Controller;
class DefaultController extends Controller
{
public function actionIndex()
{
return $this->render('index');
}
}In modules/admin/views/default/index.php:
<h1>Welcome to Admin Module</h1>config/web.php'modules' => [
'admin' => [
'class' => 'app\modules\admin\AdminModule',
],
],Now, visit:
http://your-app.com/index.php?r=admin/default/indexYou should see "Welcome to Admin Module".
Yii2 allows modules to have their own console commands for tasks like database migrations, cron jobs, and batch processing.
Modify AdminModule.php to set a separate namespace for console commands:
namespace app\modules\admin;
use Yii;
class AdminModule extends \yii\base\Module
{
public $controllerNamespace = 'app\modules\admin\controllers';
public function init()
{
parent::init();
// If the request is coming from the console (CLI)
if (Yii::$app->request->isConsoleRequest) {
\Yii::configure($this, [
'controllerNamespace' => 'app\modules\admin\commands'
]);
}
}
}Inside the admin module, create a commands directory:
modules/
admin/
commands/
TestController.phpIn modules/admin/commands/TestController.php:
namespace app\modules\admin\commands;
use yii\console\Controller;
class TestController extends Controller
{
public function actionIndex()
{
echo "Admin module console command is working!\n";
}
}Navigate to your Yii2 project root and run:
php yii admin/testOutput:
Admin module console command is working!This allows each module to have isolated CLI functionalities, making it useful for background jobs and scheduled tasks.
main-local.phpInstead of hardcoding database configurations inside the module, we can use an external configuration file (main-local.php).
AdminModule.phpModify AdminModule.php to include the external config file if it exists:
namespace app\modules\admin;
use Yii;
class AdminModule extends \yii\base\Module
{
public $controllerNamespace = 'app\modules\admin\controllers';
public function init()
{
parent::init();
// Load local database config if available
if (file_exists(__DIR__ . '/config/main-local.php')) {
Yii::configure($this, require(__DIR__ . '/config/main-local.php'));
}
}
}main-local.php Configuration FileInside modules/admin/config/main-local.php:
<?php
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=admin_db',
'username' => 'root',
'password' => 'Password#3',
'charset' => 'utf8',
],
],
];Modify User.php in modules/admin/models/:
namespace app\modules\admin\models;
use Yii;
use yii\db\ActiveRecord;
class User extends ActiveRecord
{
public static function getDb()
{
return \yii::$app->getModule('admin')->db;
}
public static function tableName()
{
return 'users';
}
}Modify DefaultController.php in modules/admin/controllers/:
use app\modules\admin\models\User;
public function actionUsers()
{
$users = User::find()->all();
return $this->render('users', ['users' => $users]);
}Now, visit:
http://your-app.com/index.php?r=admin/default/usersThis method ensures that database configurations are environment-specific and easier to manage.
Each module can have its own theme, ensuring a separate UI layout and styling.
AdminModule.phpModify AdminModule.php to configure the theme dynamically:
namespace app\modules\admin;
use Yii;
class AdminModule extends \yii\base\Module
{
public $controllerNamespace = 'app\modules\admin\controllers';
public function init()
{
parent::init();
// Apply module-specific theme
Yii::$app->view->theme = new \yii\base\Theme([
'pathMap' => ['@app/views' => dirname(__FILE__) . '/themes/views'],
'baseUrl' => dirname(__FILE__) . '/themes/views',
]);
}
}Inside modules/admin/themes/, create the structure:
modules/
admin/
themes/
views/
layouts/
main.php
views/
default/
index.phpCreate modules/admin/themes/views/layouts/main.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<link rel="stylesheet" href="/css/admin.css">
</head>
<body>
<header><h1>Admin Panel</h1></header>
<div class="content">
<?= $content ?>
</div>
</body>
</html>Modify modules/admin/themes/views/default/index.php:
<h2>Welcome to the Admin Dashboard</h2>Now, visit:
http://your-app.com/index.php?r=adminYour module will now use the custom theme and layout.
Restrict access to the admin module using Yii2 Access Control Filter (ACF).
Modify AdminModule.php:
use yii\filters\AccessControl;
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::class,
'only' => ['*'],
'rules' => [
[
'allow' => true,
'roles' => ['@'], // Only logged-in users
],
],
],
];
}main-local.php – Making database settings environment-specificThis approach makes the Yii2 module more modular, scalable, and reusable.
Sign in to join the discussion and post comments.
Sign in