php框架模板_一个简单PHP主模板框架

本文介绍了如何构建一个基于PHP的简单主模板框架,利用Foundation响应式框架,并详细阐述了主模板文件、路由、页面渲染、基类以及安装过程。通过创建.htaccess文件和调整内部链接,实现更友好的URL结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

php框架模板

总览 (Overview)

本文讨论如何为多页网站创建一个简单PHP主模板框架。 模板包含站点的容器,导航,页脚等,即所有常见元素,并根据请求的页面提取特定内容。

To make things a bit more intersting lets also base the template on a responsive framework - my preference is foundation so I will use that.

为了使事情更加有趣,让我们也将模板基于响应框架-我的偏好是基础,因此我将使用它。

主模板文件 (The Master Template File)

我们从index.php文件开始。 让我们从一个标准HTML文档开始,并添加一些标记

index.php

index.php

<!doctype html>
<html>
<head>
<title>The Title</title>
</head>
<body>
</body>
</html>

To be backwardly compatible with the unmentionable browser we will add the modernizr shim as well.

为了与不易提及的浏览器向后兼容,我们还将添加modernizr填充程序。

Here is a full source listing for a sample index.php file - we will go through it in detail later on in the article.

这是一个示例index.php文件的完整源代码清单-我们将在本文后面的部分中详细介绍它。

index.php

index.php

<?php
  require_once('includes/common.php');
  $page = empty($_REQUEST['page']) ? 'home' : preg_replace('/[^a-zA-Z0-9\-_]/', '', $_REQUEST['page']);
  $pagepath = "includes/$page.class.php";
  if (file_exists($pagepath)) {
    require_once($pagepath);
    $pageclass = $page . 'Class';
  }
  else {
    $pageclass = 'BasePage';
  }
  $mainframe = new $pageclass($page);
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><?php $mainframe->title();?></title>
    <link rel="stylesheet" href="css/foundation.css" />
    <link rel="stylesheet" href="css/custom.css" />
    <script src="js/vendor/modernizr.js"></script>
</head>
<body id="<?php echo $page;?>_page">
  <div id="wrapper">
    <div id="topbar" class="small bottomShadow">
      <div class="row">
        <div class="large-2 columns"><a href="index.html" id="logo"><img id="logo" src="css/images/logo.png" alt="Experts Exchange"/></a></div>
        <div class="large-10 columns" style="margin-top: 10px; text-align: right">
          <a href="login.html" class="login">Login</a>
          <nav>
            <ul>
              <li><a href="index.php?page=home">Home</a></li>
              <li><a href="index.php?page=aboutus">About US</a></li>
              <li><a href="index.php?page=products">Products</a></li>
              <li><a href="index.php?page=contact">Contact US</a></li>
            </ul>
          </nav>
        </div>
      </div>
    </div>
    <div class="mainContent">
  <!-- CONTENT AREA STARTS HERE -->
  <?php $mainframe->render();?>
  <!-- CONTENT AREA ENDS HERE -->
    </div>
  </div>
  <div id="footer">
    <div class="row">
      <div class="large-9 columns">
        <div class="row">
          <div class="large-4 columns">
            <h6>NAVIGATE<h6>
            <ul>
              <li><a href="/" data-ga-label="Footer" data-ga-action="MasterPage" data-ga-category="HomePage" class="track-click" id="Body_lnkHome">Home</a></li>
              <li><a href="/" data-ga-label="Footer" data-ga-action="MasterPage" data-ga-category="HomePage" class="track-click" id="Body_lnkHome">Home</a></li>
              <li><a href="/" data-ga-label="Footer" data-ga-action="MasterPage" data-ga-category="HomePage" class="track-click" id="Body_lnkHome">Home</a></li>
              <li><a href="/" data-ga-label="Footer" data-ga-action="MasterPage" data-ga-category="HomePage" class="track-click" id="Body_lnkHome">Home</a></li>
            </ul>
          </div>
          <div class="large-4 columns">
            <h6>EVENTS<h6>
            <ul>
              <li><a href="/" data-ga-label="Footer" data-ga-action="MasterPage" data-ga-category="HomePage" class="track-click" id="Body_lnkHome">Home</a></li>
              <li><a href="/" data-ga-label="Footer" data-ga-action="MasterPage" data-ga-category="HomePage" class="track-click" id="Body_lnkHome">Home</a></li>
              <li><a href="/" data-ga-label="Footer" data-ga-action="MasterPage" data-ga-category="HomePage" class="track-click" id="Body_lnkHome">Home</a></li>
              <li><a href="/" data-ga-label="Footer" data-ga-action="MasterPage" data-ga-category="HomePage" class="track-click" id="Body_lnkHome">Home</a></li>
            </ul>
          </div>
          <div class="large-4 columns">
            <h6>NETWORK<h6>
            <ul>
              <li><a href="/" data-ga-label="Footer" data-ga-action="MasterPage" data-ga-category="HomePage" class="track-click" id="Body_lnkHome">Home</a></li>
              <li><a href="/" data-ga-label="Footer" data-ga-action="MasterPage" data-ga-category="HomePage" class="track-click" id="Body_lnkHome">Home</a></li>
              <li><a href="/" data-ga-label="Footer" data-ga-action="MasterPage" data-ga-category="HomePage" class="track-click" id="Body_lnkHome">Home</a></li>
              <li><a href="/" data-ga-label="Footer" data-ga-action="MasterPage" data-ga-category="HomePage" class="track-click" id="Body_lnkHome">Home</a></li>
            </ul>
          </div>
        </div>
      </div>
      <div class="large-4 columns"></div>
    </div>
  </div>
  
    <script src="js/vendor/jquery.js"></script>
    <script src="js/foundation.min.js"></script>
  <script src="js/scripts.js"></script>
    <script>
      $(document).foundation();
    </script>
  <?php $mainframe->dump_scripts();?>
</body>
</html>

路由 (Routing)

为了使框架可扩展,它需要具有路由功能,即将请求路由到可以处理该请求并呈现正确页面的代码的方法。 下面的代码是如何实现路由的非常简单的示例。

Extract from index.php

从index.php中提取

<?php
  // INCLUDE OUR COMMON LIBRARY CODE - WE WILL DEFINE THIS A BIT LATER */
  require_once('includes/common.php');
  
  // GET OUR PAGE VARIABLE FROM THE URL (OR POST IF IT WAS POSTED). 
  // IF THE $page PARAMETER EXISTS THEN SANITIZE IT i.e. STRIP IT OF
  // INVALID CHARS. IF THE PARAMETER DOES NOT EXIST DEFAULT IT TO home
  $page = empty($_REQUEST['page']) ? 'home' : preg_replace('/[^a-zA-Z0-9\-_]/', '', $_REQUEST['page']);
  
  // CREATE A PATH TO THE FILE THAT CONTAINS THE CODE FOR THIS PAGE
  $pagepath = "includes/$page.class.php";
  
  // IF IT DOES EXIST SET THE PAGECLASS TO THE PAGE NAME
  if (file_exists($pagepath)) {
    require_once($pagepath);
    $pageclass = $page . 'Class';
  }
  // OTHERWISE DEFAULT IT TO THE BASE
  else {
    $pageclass = 'BasePage';
  }
  
  // AND INSTANTIATE THE CLASS
  $mainframe = new $pageclass($page);
?>

渲染特定页面 (Rendering Specific Pages)

每个页面都可能具有一个类来扩展该页面所需的功能-但是,如果未找到类,则框架将故障转移到默认(BasePage)功能。

Why are we using classes here - that will become apparent in the next section but to give a spoiler - the reason is we want to put generic functionality in a parent class (contained in common) and then we want to override that for our specific page.

我们为什么在这里使用类-在下一节中将变得显而易见,但会给人造成困扰-原因是我们想将泛型功能放在父类中(包含在公共类中),然后在特定页面中覆盖它。

Actual content is stored in a view - which is plain old HTML - potentially with some script to popupluate the page with variables. You set these variables in the render() method of the page. Confused? Continue reading for a description of how the classes hang together.

实际内容存储在一个视图中-它是普通的旧HTML-可能带有一些脚本来使用变量弹出页面。 您可以在页面的render()方法中设置这些变量。 困惑? 继续阅读以获取有关各类如何组合在一起的描述。

基类 (The Base Class)

首先,让我们看一下页面的基类。 基类处理所有页面上的所有通用功能。 扩展基类取决于您的要求。 基类旨在用作任何项目中的通用类。 如果您要为给定项目实现特定的通用功能,则最好创建基类的子类,然后将通用功能添加到该子类中。 然后,可以为您的页面子类化此新类。 这样,您可以为项目提供通用功能,而不会损害基础的通用(跨项目)结构。

includes/common.php

包括/ common.php

<?php
// OUR DEFAULT TITLE TO USE IF WE DON'T SPECIFICALLY SET ONE
define('gb_title', 'DEFAULT TITLE');

// THE BasePage CLASS THAT CONTAINS THE DEFUALT FUNCTIONALITY
// FOR OUR PAGES.
class BasePage 
{
  // THE TITLE PROPERTY THAT CAN BE OVERWRITTEN IN THE
  // PAGE CLASS. REFER TO THE ProductClass FOR EXAMPLE
  protected $title = gb_title;
  
  // PUBLIC PROPERTY TO STORE THE CURRENT PAGE
  public $page;
  
  function __construct($page)
  {
    $this->page = $page;
  }
  
  function title()
  {
    echo $this->title;
  }
  // METHOD TO RETURN A PATH TO OUR VIEW FILE
  // OR THE ERROR VIEW IF PAGE NOT FOUND
  function get_view()
  {
    $view = "view/" . $this->page . '.view.php';
    if (file_exists($view)) {
      return $view;
    }
    return 'view/error.view.php';
  }
  
  // DEFAULT RENDER METHOD TO OUTPUT THE 
  // HTML CONTAINED IN THE VIEW FILE
  function render()
  {
    $view = $this->get_view();
    require_once($view);
  }
}
?>

充实它 (Fleshing it out)

对于此示例,我们将仅定义“主页”视图,即没有控制器类,以演示框架如何在没有页面具有控制器类的情况下返回视图。 我们将使用“产品页面”来演示如何构建页面控制器类。

主页 (The Home Page)

一个非常简单的html代表我们的主页内容。 由于此内容已插入模板中,因此其余页面详细信息(导航,页脚,脚本)将得到有效处理

view/home.view.php

查看/home.view.php

<div class="row">
  <div class="large-12 columns">
    <div class="row">
      <div class="small-6 large-2 columns">&nbsp;</div>
      <div class="small-6 large-8 columns">
        <h1>Home Page</h1>
      </div>
      <div class="small-12 large-2 columns">&nbsp;</div>
    </div>      
  </div>
</div>

产品页面 (The Products Page)

如上所述,产品页面具有控制器类和视图。 控制器类定义如下。

includes/products.class.php

包括/products.class.ph p

<?php
class ProductsClass extends BasePage
{
  // DEMONSTRATE HOW TO OVERRIDE THE TITLE
  // WE CAN ALSO MAKE THIS DYNAMIC BY SETTING
  // THIS PROPERTY IN THE CONSTRUCTOR
  protected $title = "Products Page";
  
  // CUSTOM RENDER FUNCTION DEMONSTRATING 
  // HOW TO SET A VARIABLE FOR USE IN THE VIEW
  function render()
  {
    $view = $this->get_view();
    $pagevariable = "Products Page";
    require_once($view);
  }
}
?>

产品页面视图 (The Products Page View)

该代码与“主页”视图非常相似,不同之处在于,我们使用脚本在渲染的内容中输出变量。
<div class="row">
  <div class="large-12 columns">
    <div class="row">
      <div class="small-6 large-2 columns">&nbsp;</div>
      <div class="small-6 large-8 columns">
        <h1><?php echo $pagevariable;?></h1>
      </div>
      <div class="small-12 large-2 columns">&nbsp;</div>
    </div>      
  </div>
</div>

变得更好 (Making it better)

尽管上面的作品有一些小的修改,但我们可以做出一些小的修改,使它变得更好。 一种这样的修改是摆脱脚本化的URL,并使我们的URL更人性化。

To do this we need to create an .htaccess file with some routing rules and we will need to make a few changes to our master template.

为此,我们需要创建一个带有某些路由规则的.htaccess文件,并且需要对主模板进行一些更改。

.htaccess文件 (The .htaccess file)

尽管.htaccess文件可用于路由以外的许多其他功能,但我们仅在此处介绍路由。
AddType x-mapp-php5 .php
Options +FollowSymLinks

RewriteEngine on
RewriteBase /
# REDIRECT REQUESTS FOR index.html TO OUR TEMPLATE
RewriteRule index\.html$ index.php [L,NC,QSA]

#IF THE REQUESTED FILE DOES NOT EXIST PASS THIS
#TO index.php WITH THE PAGENAME AS A PARAMETER
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*)\.html$ index.php?page=$1 [L,NC,QSA]

index.php?page=products

index.php?page =产品

All we need to do is modify our internal links to be html pages instead of index.php requests. This means we need to update our <nav> section in our master template. While we are at it we might as well add some functionality to be able to mark which of our menu links is active so we can style active links separately from inactive ones.

我们需要做的就是将内部链接修改为html页面而不是index.php请求。 这意味着我们需要更新主模板中的<nav>部分。 在此过程中,我们不妨添加一些功能来标记我们的哪个菜单链接处于活动状态,以便我们可以分别将活动链接和非活动链接设置样式。

          <nav>
            <ul>
              <li<?php echo ($page=='home') ? ' class="active"' : '';?>><a href="index.html">Home</a></li>
              <li<?php echo ($page=='aboutus') ? ' class="active"' : '';?>><a href="aboutus.html">About US</a></li>
              <li<?php echo ($page=='products') ? ' class="active"' : '';?>><a href="products.html">Products</a></li>
              <li<?php echo ($page=='contact') ? ' class="active"' : '';?>><a href="contact.html">Contact US</a></li>
            </ul>
          </nav>
route_link that renders the <li> menu items for us complete with class and href values. route_link包含class和href值。
  function route_link($page, $class, $text) 
  {
    $classtext = ($this->page == $page) ? ' class="' . $class . '"' : '';
    echo '<li' . $classtext . '><a href="' . $page . '.html">' . $text . '</a></li>';
  }
          <nav>
            <ul>
            <?php 
              $mainframe->route_link('home','active','Home');
              $mainframe->route_link('About Us','active','About Us');
              $mainframe->route_link('products','active','Products');
              $mainframe->route_link('contact','active','Contact');
            ?>
            </ul>
          </nav>

安装 (Installation)

要测试此代码,请下载并安装基础框架,然后将附件复制到所示位置

/root

/根

      .htaccess [rename .txt]

.htaccess [重命名.txt]

    index.php

index.php

      /css

/ css

            custom.css

custom.css

      /includes

/包括

            common.php

common.php

            products.class.php

products.class.php

      /view

/视图

            error.view.php

error.view.php

            home.view.php

home.view.php

            products.view.php

products.view.php

The foundation installation should create the following structure

基础安装应创建以下结构

/root

/根

      /js

/ js

            foundation.min.js

foundation.min.js

            /vendor

/供应商

                  jquery.js

jquery.js

                  mondernizr.js

mondernizr.js

      /css

/ css

            foundation.css

foundation.css

            normalize.css

normalize.css

That's all there is to it. Hopefully this has been informative in how to setup a simple master template framework.

这里的所有都是它的。 希望这对如何设置简单的主模板框架有所帮助。

index.php index.php common.php common.php products.class.php products.class.php error.view.php error.view.php home.view.php home.view.php products.view.php products.view.php custom.css custom.css htaccess.txt htaccess.txt

翻译自: https://www.experts-exchange.com/articles/13095/A-simple-PHP-master-Template-framework.html

php框架模板

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值