# 控制器

新建控制器文件 app/controller/FooController.php

<?php

declare(strict_types=1);
/**
 * This file is part of monda-worker.
 *
 * @contact  mondagroup_php@163.com
 */

namespace app\controller;

use herosphp\annotation\Controller;
use herosphp\annotation\Get;
use herosphp\core\BaseController;

#[Controller(name: FooController::class, desc: 'Say Hello')]
class FooController extends BaseController
{
    #[Get(uri: '/foo', desc: 'index')]
    public function index(): String
    {
        return "hello world";
    }

    #[Get(uri: '/foo/hello', desc: 'say Hello')]
    public function herosphp(): String
    {
        return "hello herosphp";
    }
}

当访问 http://127.0.0.1:2345/foo 时,页面返回 hello world

当访问 http://127.0.0.1:8787/foo/hello 时,页面返回 hello herosphp

当然你可以通过路由配置来更改路由规则,参见路由

# 说明

  • 所有的Controller 必须继承 BaseController,在Controller中,可以调用json() xml() html()等函数返回。
  • 框架会自动向控制器的路由第一个参数传递herosphp\core\HttpRequest 对象,通过它可以获取用户输入数据(get post header cookie 等数据),参见请求
  • 控制器里可以返回数字、字符串或者herosphp\core\HttpResponse 对象或者实现了JsonAble接口的对象,但是不能返回其它类型的数据。
  • 可以通过 GF::response(int $code = 200, array $headers = [], mixed $body = '') 或者 GF::redirect(string $url, int $code = 301)等助手函数进行返回值。

注意

在控制器__construct()构造函数中 return 数据不会有任何效果。

当然,我们也有考虑到在控制器需要初始化部分数据需求后,我们也增加了钩子__init()代替__construct()

上次更新: 10/27/2022, 11:18:25 AM