Hello World - 控制器与视图

知识库
知识库文档
/tech-stacks/yii/examples/Hello World - 控制器与视图.md

文档

Hello World:Yii2 控制器与视图

目标

创建 Yii2 控制器,展示两种响应方式:JSON API 和 HTML 视图。

完整代码

1. 使用 Gii 生成控制器(可选)

访问 http://localhost:8080/gii,使用 Controller Generator。

2. 手动创建 controllers/HelloController.php

<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Response;

class HelloController extends Controller
{
    /**
     * JSON API 端点
     */
    public function actionIndex(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        return [
            'message' => 'Hello, Vibe!',
            'framework' => 'Yii2',
            'php_version' => PHP_VERSION,
            'timestamp' => date('c'),
        ];
    }

    /**
     * HTML 视图
     */
    public function actionView(string $name = 'World'): string
    {
        return $this->render('view', [
            'name' => $name,
            'framework' => 'Yii2',
        ]);
    }

    /**
     * 带参数 JSON
     */
    public function actionGreet(string $name): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        return [
            'message' => "Hello, {$name}!",
            'powered_by' => 'Yii Framework',
        ];
    }
}

3. 创建视图 views/hello/view.php

<?php

/** @var string $name */
/** @var string $framework */
?>
<h1>Hello, <?= htmlspecialchars($name) ?>!</h1>
<p>Powered by <strong><?= htmlspecialchars($framework) ?></strong></p>
<p>PHP Version: <?= PHP_VERSION ?></p>

运行步骤

php yii serve

预期输出

# JSON 端点
curl http://localhost:8080/index.php?r=hello/index
# {"message":"Hello, Vibe!","framework":"Yii2","php_version":"8.2.0","timestamp":"..."}

# 带参数
curl http://localhost:8080/index.php?r=hello/greet\&name=Vibe
# {"message":"Hello, Vibe!","powered_by":"Yii Framework"}

# HTML 视图
# 浏览器访问 http://localhost:8080/index.php?r=hello/view&name=Vibe
# 渲染 "Hello, Vibe! Powered by Yii2"

提示:Yii2 可用 URL 美化消除 index.php?r=,在 config/web.php 中启用 urlManager 组件。`

信息

路径
/tech-stacks/yii/examples/Hello World - 控制器与视图.md
更新时间
2026/5/31