dframe/router

路由组件 Dframe

v4.2.0 2022-10-28 13:54 UTC

This package is auto-updated.

Last update: 2024-09-05 13:21:57 UTC


README

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

php framework dframe logo

文档 - Router PHP

Composer

$ composer require dframe/router

简单的 PHP 路由器

创建应用程序时,值得注意它们的友好链接。这在 SEO 中的位置起着很大作用。链接路由器的工作方式类似于网络路由器。它负责从控制器中调用方法。

$this->router->addRoute([
'page/:method' => [
'page/[method]/',
'task=page&action=[method]'
]
]);
$this->router->makeUrl('page/:action?action=index'); // Return: https://example.php/page/index
$this->router->isActive('page/:action?action=index'); // Current Website true/false

配置

我们在配置文件中定义了应用程序的地址表

  • |https| - 强制 https

  • |NAME_CONTROLLER| - 默认控制器的名称

  • |NAME_METHOD| - 在 NAME_CONTROLLER 中的默认方法名称

  • |publicWeb| - 主要文件夹,从中读取文件(js、css)

  • |assetsPath| - 动态文件夹

  • |docs/docsId| - 使用 |docsId| 变量的示例路由,其中包含 |docs/[docsId]/| 地址定义和分配给 |task| 参数的 |task| 参数。

  • |error/404| - 与上面类似

  • |default| - 默认定义,加载控制器/方法。|params| 定义了出现额外参数的可能性,而

'_params' => [
'[name]/[value]/',
'[name]=[value]'
]

定义了额外 foo=bar 参数的解释方式。

Config/router.php

 
 return [
     'https' => false,
     'NAME_CONTROLLER' => 'page',    // Default Controller for router
     'NAME_METHOD' => 'index',       // Default Action for router
     'publicWeb' => '',              // Path for public web (web or public_html)
 
     'assets' => [
         'minifyCssEnabled' => true,
         'minifyJsEnabled' => true,
         'assetsDir' => 'assets',
         'assetsPath' => APP_DIR.'View/',
         'cacheDir' => 'cache',
         'cachePath' => APP_DIR.'../web/',
         'cacheUrl' => HTTP_HOST.'/',
     ],
 
     'routes' => [
         'docs/:page' => [
             'docs/[page]/', 
             'task=Page&action=[page]&type=docs'
         ],
         
         'methods/example/:exampleId' => [
            'methods/example/[exampleId]',
            'methods' => [
                'GET' => 'task=Methods,Example&action=get&exampleid=[exampleId]',
                'POST' => 'task=Methods,Example&action=post&exampleid=[exampleId]',
            ]
         ],
         
         'error/:code' => [
             'error/[code]/', 
             'task=Page&action=error&type=[code]',
             'code' => '([0-9]+)',
             'args' => [
                 'code' => '[code]'
             ],
         ],
         
        ':task/:action' => [
            '[task]/[action]/[params]',
            'task=[task]&action=[action]',
            'params' => '(.*)',
            '_params' => [
                '[name]/[value]/',
                '[name]=[value]'
            ]
        ],

         'default' => [
             '[task]/[action]/[params]',
             'task=[task]&action=[action]',
             'params' => '(.*)',
             '_params' => [
                 '[name]/[value]/', 
                 '[name]=[value]'
             ]
         ]
     ] 
 
 ];

控制器

  • makeUrl - 用于生成完整地址。例如 |makeurl| - 用于重定向的方法,相当于 |header|,但参数来自 Config/router.php 表的键。如果使用 docs/:docsld,它看起来像以下 |redirect|

Controller/Page.php

 namespace Controller;
 
 use Dframe\Controller;
 use Dframe\Router\Response;
 
 class PageController extends Controller
 {
 
     /**
      * @return bool
      */
     public function index()
     {
         echo $this->router->makeUrl('docs/:docsId?docsId=23');
         return;
     }
 
     /**
      * @return mixed
      */
     public function docs()
     {
 
         if (!isset($_GET['docsId'])) {
             return $this->router->redirect('error/:code?code=404');
         }
     }
 
     /**
      * @param string $status
      *
      * @return mixed
      */
     public function error($status = '404')
     {
         $routerCodes = $this->router->response();
 
         if (!array_key_exists($status, $routerCodes::$code)) {
             return $this->router->redirect('error/:code?code=500');
         }
 
         $view = $this->loadView('index');
         $smartyConfig = Config::load('view/smarty');
 
         $patchController = $smartyConfig->get('setTemplateDir', APP_DIR . 'View/templates') . '/errors/' . htmlspecialchars($status) . $smartyConfig->get('fileExtension', '.html.php');
 
         if (!file_exists($patchController)) {
             return $this->router->redirect('error/:code?code=404');
         }
 
         $view->assign('error', $routerCodes::$code[$status]);
         return Response::create($view->fetch('errors/' . htmlspecialchars($status)))->headers(['refresh' => '4;' . $this->router->makeUrl(':task/:action?task=page&action=index')]);
     }
 
 }

视图

assign - 这是模板引擎的一个方法,用于将值分配给在模板文件中使用的变量。

View/templates/index.html.php

https://

仅使用 PHP

  • |router| 所有已使用的方法,如 |page/index|

View/index.php

namespace View;

use Dframe\Asset\Assetic;

class IndexView extends \View\View
{

     /**
      * @return bool
      */
     public function init()
     {
         $this->router->assetic = new Assetic();
         $this->assign('router', $this->router);
     }
}

Dframe\Router\Response;

Dframe\Router 的扩展是 Dframe\Router\Response,增加了设置响应状态(404、500 等)及其头部的功能。

return Response::create('Hello Word!')
    ->status(200)
    ->headers([
                  'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
                  'Cache-Control' => 'no-cache',
                  'Pragma',
                  'no-cache'
              ]);

用于生成 html。

渲染 json

return Response::renderJSON(['code' => 200, 'data' => []]);

带有回调的渲染 json

return Response::renderJSONP(['code' => 200, 'data' => []]);

重定向

return Response::redirect(':task/:action?task=page&action=login');