开发者

Having includes with variables in two places at once

I have a small situaton here. I'm building a custom CMS for one of my websites.

Below is the code for the main index page:

<?php
require("includes/config.php");   
include("includes/header.php");  
 if(empty($_GET['page'])) {     
     include('pages/home.php'); 
     } else {
      if(!empty($_GET['page'])){ 
$app = mysqli_real_escape_string($db,$_GET['page']);
$content = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM pages_content WHERE htmltitle = '$app'")) or die(mysqli_error($db));
$title = $content['title'];
$metakeywords = $content['htmlkeywords'];
$metadesc = $content['htmldesc'];
?>
<h1><?php echo $content['title']; ?></h1><hr /><br />
<div id="content"><?php echo $content['content']; ?></div>              
<? } else { include('includes/error/404.php');} }
include('includes/footer.php'); ?>

The file, includes/header.php contains code to echo variables, such as, page title and meta stuff.

The issue is that when the include("includes/header.php"); is where it is, outside of the if conditions, it will not echo the varables, obviously, however, I can't put the include in the if condition otherwise, the home page, which does not require any url variables will show without these conditions.

开发者_开发百科

What do I do?


You can't really write code like this for too long. It's ok to for start, but you will soon realize it's hard to maintain. The usual way is to split it into a few steps.

  • First check input and determine on which page are you
  • If you know you are on the homepage, include something like includes/templates/homepage.php
  • Otherwise try to load the page from the database
    • If it worked, include includes/templates/page.php
    • Otherwise include includes/templates/404.php

Each of the files in includes/templates will output the whole page, i.e. they all include the header, do something and include the footer. You can use for example Smarty templates instead of PHP files, which will make the approach obvious.

Once you have this, you can split the code even more. Instead of loading the page directly from index.php, include another file which defines a function like load_page($name) and returns the page details.

Then a few more changes and you realize you are using the MVC approach. :) The functions that load data from the database are your Models, the Smary templates are Views and the PHP files that put them together are Controllers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜