yllumi/ci4pageroute

基于页面的CodeIgniter 4路由

1.0.4 2021-10-23 14:31 UTC

This package is auto-updated.

Last update: 2024-09-23 22:04:37 UTC


README

使用基于页面的路由来加速开发。它就像Nextjs或Nuxtjs在CodeIgniter 4中一样。

安装

  • 安装CodeIgniter 4
  • 运行composer composer require yllumi/ci4pageroute
  • 在CodeIgniter的Config/Routes.php中更改2行,如下所示
    $routes->set404Override('\Yllumi\Pager\Controllers\Page::index');
    $routes->get('/', '\Yllumi\Pager\Controllers\Page::index');
  • 运行composer run -d vendor/yllumi/ci4pageroute add-sample-page来放置示例页面
  • 祝您开发愉快!

创建页面

基于页面的路由使用Latte模板引擎来构建页面结构。

默认情况下,页面放置在项目根目录下的pages/文件夹中。

project/
  app/
  pages/
    index.html
    meta.yml
  public/
  test/
  vendor/
  writable/

为了使页面工作,您必须至少创建两个文件,meta.ymlindex.htmlmeta.yml用于定义页面属性,而index.html是页面本身的模板。

例如,在pages/文件夹中创建meta.yml如下所示

page_title: Home

并在同一位置创建index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>{$page_title}</title>
</head>
<body>
  <h1>Welcome!</h1>
</body>
</html>

然后您可以在浏览器中调用您的应用,根主页将显示这些页面文件。

编写PHP操作

您也可以通过在同一位置创建Action.php文件,像在控制器中一样编写任何PHP代码。

<?php

class PageAction {

  // This method handle get request
  public function run()
  {
    $data['intro'] = '<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquam voluptate error laboriosam ullam odio quasi repellendus minus provident. Amet dolores repellat doloremque, nemo similique officia molestias quaerat sequi, voluptates rerum.</p>';

    return $data; 
  }


  // This method handle POST request
  public function process(){

  }

}

您返回的$data变量内部的所有数据都可以在页面模板中调用,就像您从meta.yml中调用任何属性一样。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>{$page_title}</title>
</head>
<body>
  <h1>Welcome!</h1>
  <p>{$intro|noescape}</p>
</body>
</html>

PageAction类中至少有两个方法,run()process()。方法run()用于编写处理页面GET请求的代码,而process()用于处理对页面的POST请求。

创建子页面

您也可以通过在pages/内部创建子文件夹来创建任何子页面。然后您可以在该子文件夹中放置meta.ymlindex.htmlAction.php

pages/
  about/
    index.html
    meta.yml
  index.html
  meta.yml

上述页面结构产生页面http://domain.test/http://domain.test/about