简体   繁体   English

用php创建动态页面

[英]Create dynamic page with php

I'm writing a small routing system for a project. 我正在为项目编写小型路由系统。 It's not perfect and it's a custom solution that will map the url to their templates if requested from the user. 这不是完美的,它是一个自定义解决方案,如果用户要求,它将URL映射到其模板。 I want to generate a dynamic page based on an unique id for each event inserted inside the database from the user. 我想根据用户为数据库中插入的每个事件的唯一ID生成一个动态页面。 So if the user request the event 1234 it will get a page with the event detail at the url https://mysitedomain.com/event/1234 . 因此,如果用户请求事件1234,它将在URL https://mysitedomain.com/event/1234获得一个包含事件详细信息的页面。 I need to understand how to achieve this with my code, I'm using a front controller and red bean as ORM to access the database. 我需要了解如何使用我的代码来实现此目的,我使用前端控制器和Red bean作为ORM来访问数据库。 Here is the code of my router. 这是我的路由器的代码。 Any suggestion will be appreciated. 任何建议将不胜感激。 for now I'm only able to serve the templates. 目前,我只能提供模板。

<?php
namespace Router;

define('TEMPLATE_PATH', dirname(__DIR__, 2).'/assets/templates/');

class Route {

  private static $assets = ['bootstrap' => 'assets/css/bootstrap.min.css',
    'jquery' => 'assets/js/jquery.min.js',
    'bootstrapjs' => 'assets/js/bootstrap.min.js',
  ];

    public static function init()
    {
      if( isset($_SERVER['REQUEST_URI']) ){
        $requested_uri = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH);
          if( $requested_uri === '/' ){
            echo self::serveTemplate('index', self::$assets);
          }
          elseif( $requested_uri != '/' ){
            $requested_uri = explode('/', $_SERVER['REQUEST_URI']);
            if( $requested_uri[1] === 'event' ){
              echo self::serveTemplate('event', self::$assets, ['event_id' => 001] );
            }
            else{
              echo self::serveTemplate($view, self::$assets);
            }
          }
      }
    }

    private static function serveTemplate(string $template, array $data, array $event_id = null)
    {
      if( !is_null($event_id) ){
        $data[] = $event_id;
        ob_start();
        extract($data);
        require_once TEMPLATE_PATH."$template.php";
        return ob_get_clean();
      }
      else{
        ob_start();
        extract($data);
        require_once TEMPLATE_PATH."$template.php";
        return ob_get_clean();
      }
    }

}

?>

Writing a router from scratch is a little complex, you have to play a lots with regular expression to accommodate various scenario of requested url and your router should handle HTTP methods like POST, GET, DELETE, PUT and PATCH. 从头开始编写路由器有点复杂,您必须使用正则表达式进行大量操作以适应请求的url的各种情况,并且路由器应处理HTTP方法,例如POST,GET,DELETE,PUT和PATCH。

You may want to use existing libraries like Fast Route , easy to use and it's simplicity could give you idea how it is created. 您可能要使用易于使用的现有库,例如Fast Route ,它的简单性可以让您了解如何创建它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM