Пример #1
0
$app->group('/post', function () {
    $this->get('/new', function () {
        return view('post.php');
    });
    $this->post('/new', function () {
        $title = request()->filter('trim', 'strip_tags')->input('title');
        $content = request()->filter('trim', 'strip_tags')->input('content');
        $error = '';
        if (empty($title)) {
            $error = '标题不能为空';
        } elseif (empty($content)) {
            $error = '内容不能为空';
        } else {
            $pid = (new \Model\Post())->add($title, $content);
            if ($pid) {
                response()->redirect(url_base() . '/post/' . $pid);
            } else {
                $error = '添加文章失败';
            }
        }
        return view('post.php', ['error' => $error]);
    });
    // 为多种请求注册路由
    $this->map(['GET', 'POST'], '/edit/<pid>', function () {
        $error = '';
        $pid = request()->filter('intval')->params('pid');
        $post = (new \Model\Post())->get($pid);
        if (!$post) {
            // Not found 异常
            throw new \Lime\Exception\NotFoundException("Post not found");
        }
        if (request()->isPost() && request()->input('edit')) {
            $title = request()->filter('trim', 'strip_tags')->input('title');
            $content = request()->filter('trim', 'strip_tags')->input('content');
            if (empty($title)) {
                $error = '标题不能为空';
            } elseif (empty($content)) {
                $error = '内容不能为空';
            } else {
                (new \Model\Post())->update($pid, $title, $content);
                response()->redirect(url_base() . '/post/' . $pid);
            }
        }
        return view('post-edit.php', ['post' => $post, 'error' => $error]);
    })->conditions(['pid' => '[0-9]+'])->name('post-edit');
}, function () {
    // 路由分组的过滤
    if (empty($_SESSION['uid'])) {
        response()->redirect(url_base() . '/login');
    }
});