PHP include best practices question

2020-01-27 00:39发布

I have been learning syntax for PHP and practicing it. I come from a .NET background so masterpages always made things pretty easy for me when it came to headers and footers.

So far I have a mainHeader.php and mainFooter.php which have my head menu and my footer html. I created a mainBody.php and at the top I put

<?php include "mainHeader.php" ?>

and for the footer I put

<?php include "mainFooter.php" ?>

This worked perfectly and made me smile because my pages all came together nicely. the mainHeader has my <html> and <body> and my mainFooter has my closing tags for those.

Is this good practice?

标签: php include
9条回答
SAY GOODBYE
2楼-- · 2020-01-27 01:11

I include my views from my controllers. I also define file locations to make maintenance easier.

config.php

define('DIR_BASE',      dirname( dirname( __FILE__ ) ) . '/');
define('DIR_SYSTEM',    DIR_BASE . 'system/');
define('DIR_VIEWS',     DIR_SYSTEM . 'views/');
define('DIR_CTLS',      DIR_SYSTEM . 'ctls/');
define('DIR_MDLS',      DIR_SYSTEM . 'mdls/');
define('VIEW_HEADER',   DIR_VIEWS . 'header.php');
define('VIEW_NAVIGATION',   DIR_VIEWS . 'navigation.php');
define('VIEW_FOOTER',   DIR_VIEWS . 'footer.php');

Now i have all the info i need just by including config.php.

controller.php

require( '../config.php' );
include( DIR_MDLS . 'model.php' );

$model = new model();
if ( $model->getStuff() ) {
    $page_to_load = DIR_VIEWS . 'page.php';
}
else {
    $page_to_load = DIR_VIEWS . 'otherpage.php';
}

include( VIEW_HEADER );
include( VIEW_NAVIGATION );
include( DIR_VIEWS . $page_to_load );
include( VIEW_FOOTER );
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-01-27 01:14

For small sites, include/include_once and require/require_once are great, I haven't built a site without them in years. I would, however, recommend making sure each of your include files is a discrete code block that is valid XML. What I mean is don't open a tag in one include and close it in another, or vice versa - it will make changes complex and more prone to break things because you have dependencies between files. Happy coding!

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-01-27 01:15

I like using functions to print headers and footers instead of includes. You can fine tune the variable scope better that way.

查看更多
登录 后发表回答