Hello World - Bake 脚手架

知识库
知识库文档
/tech-stacks/cakephp/examples/Hello World - Bake 脚手架.md

文档

Hello World:CakePHP 控制器与 Bake

目标

创建 CakePHP 控制器,展示手动和 Bake 两种方式。

完整代码

1. 手动创建 src/Controller/HelloController.php

<?php

namespace App\Controller;

use Cake\Http\Response;

class HelloController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        // 允许未认证访问
        $this->Authentication->allowUnauthenticated(['index', 'greet']);
    }

    public function index(): Response
    {
        $data = [
            'message' => 'Hello, Vibe!',
            'framework' => 'CakePHP',
            'php_version' => PHP_VERSION,
            'timestamp' => date('c'),
        ];

        return $this->response
            ->withType('application/json')
            ->withStringBody(json_encode($data, JSON_PRETTY_PRINT));
    }

    public function greet(string $name): Response
    {
        $data = [
            'message' => "Hello, {$name}!",
            'powered_by' => 'CakePHP',
        ];

        return $this->response
            ->withType('application/json')
            ->withStringBody(json_encode($data));
    }
}

2. 路由(config/routes.php

$routes->scope('/', function (RouteBuilder $builder) {
    $builder->connect('/hello', ['controller' => 'Hello', 'action' => 'index']);
    $builder->connect('/hello/{name}', ['controller' => 'Hello', 'action' => 'greet'])
        ->setPass(['name']);
});

3. 使用 Bake 快速生成(可选)

# 先创建数据库表
bin/cake bake controller Hello
bin/cake bake template Hello

运行步骤

bin/cake server

预期输出

curl http://localhost:8765/hello
# {"message":"Hello, Vibe!","framework":"CakePHP","php_version":"8.2.0","timestamp":"..."}

curl http://localhost:8765/hello/World
# {"message":"Hello, World!","powered_by":"CakePHP"}

信息

路径
/tech-stacks/cakephp/examples/Hello World - Bake 脚手架.md
更新时间
2026/5/31