Hello World - MVC 控制器

知识库
知识库文档
/tech-stacks/phalcon/examples/Hello World - MVC 控制器.md

文档

Hello World:Phalcon 5 MVC 控制器

目标

创建 Phalcon 5 控制器,展示 MVC 路由和 JSON API 端点。

完整代码

1. 路由配置 public/index.php

<?php

use Phalcon\Autoload\Loader;
use Phalcon\Mvc\Application;
use Phalcon\Di\Di;
use Phalcon\Mvc\Router;

// 自动加载
$loader = new Loader();
$loader->setDirectories(['../app/controllers/']);
$loader->register();

// DI 容器
$di = new Di();

$di->set('router', function () {
    $router = new Router();
    $router->add('/hello', ['controller' => 'hello', 'action' => 'index']);
    $router->add('/hello/{name}', ['controller' => 'hello', 'action' => 'greet']);
    return $router;
});

$di->set('response', function () {
    return new \Phalcon\Http\Response();
});

$app = new Application($di);
$app->handle($_SERVER['REQUEST_URI'])->send();

2. 控制器 app/controllers/HelloController.php

<?php

use Phalcon\Http\Response;
use Phalcon\Mvc\Controller;

class HelloController extends Controller
{
    /**
     * GET /hello — JSON API 端点
     */
    public function indexAction(): Response
    {
        return $this->response
            ->setContentType('application/json')
            ->setJsonContent([
                'message' => 'Hello, Vibe!',
                'framework' => 'Phalcon',
                'php_version' => PHP_VERSION,
                'timestamp' => date('c'),
            ]);
    }

    /**
     * GET /hello/{name} — 带参数端点
     */
    public function greetAction(string $name): Response
    {
        return $this->response
            ->setContentType('application/json')
            ->setJsonContent([
                'message' => "Hello, {$name}!",
                'powered_by' => 'Phalcon Framework',
            ]);
    }

    /**
     * 原生视图渲染
     */
    public function viewAction(): Response
    {
        $this->view->message = 'Hello from Phalcon View!';
        $this->view->framework = 'Phalcon';
        // 渲染 app/views/hello/view.phtml
        return $this->response;
    }
}

3. 视图 app/views/hello/view.phtml

<!DOCTYPE html>
<html>
<head><title>Phalcon Hello</title></head>
<body>
    <h1><?= $message ?></h1>
    <p>Powered by <strong><?= $framework ?></strong></p>
    <p>PHP <?= PHP_VERSION ?></p>
</body>
</html>

运行步骤

php -S localhost:8080 -t public/ .htrouter.php

预期输出

curl http://localhost:8080/hello
# {"message":"Hello, Vibe!","framework":"Phalcon","php_version":"8.2.15","timestamp":"..."}

curl http://localhost:8080/hello/Vibe
# {"message":"Hello, Vibe!","powered_by":"Phalcon Framework"}

# 浏览器访问 http://localhost:8080/hello/view
# 渲染 HTML 视图

注意:Phalcon 路由匹配不同于传统框架,需在 .htrouter.php 中处理重写规则。`

信息

路径
/tech-stacks/phalcon/examples/Hello World - MVC 控制器.md
更新时间
2026/5/31