开发者

Is it okay to put a lot of PHP includes on a site?

So far I have about 3 PH开发者_如何学PythonP includes on my site.

<?php include("includes/header.html"); ?>

Is there any reason why I shouldn't add a ton of these?


Not really. They're used quite often and liberally—though more often than not, to include other PHP files. Those PHP files then often include other ones, so there's really no concern.

By the way, if you do use this technique to include other PHP files (e.g. library files with functions you're using), it's a good idea to use require_once (there's also include_once, as well as plain require); require will cause an error if its argument cannot be found, and won't continue trying to render the page. require_once (and include_once) will not include the same file more than once, even if you call require_once (or include_once) from different places.


I suspect that you are doing something like this:

<?php
  include("session_and_headers.php");
  include("top_nav.html")
  include("right_sidebar.html");
?>

 ... actual content generation code ...

<?php
  include("footer.html");
  include("js_loader.php");
?>

There is nothing inherently wrong with that for simple static sites, or situations where users will have only several distinct views.

But, what happens if you want to use a slightly different side bar on only certain types of pages? Where do you put the logic to determine that so it is obvious to the next person who inherits your code?

If you get into those kinds of complexities, I recommend going with the MVC approach (even if you mostly use the view/controller aspects of it).

If you're doing a nn page site in PHP that just needs to share common elements, then there is no reason to avoid simply including the files as needed.

Don't look at this so much as is it bad for PHP, look at it more as is it hard to maintain?


There's one advantage to writing object-oriented code and upgrading to PHP 5: you can avoid a "ton of includes" using class autoloading.


Only downside is performance - each include costs you system calls. With 3 or 10 it's all small change unless your traffic is huge, but about 100 may be a problem. The solution is to use a bytecode cache (like apc) and set your realpath_cache_size variable to higher value (default is enough for about 100-200 files, depending on the path lengths). Other than that - not much of a problem.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜