RU beehive logo ITEC dept promo banner
ITEC 325
2013spring
ibarland

homelectsexamshws
D2Lbreeze (snow day)

lect09a-includes-nesting-requires
nesting includes
php, javascript, and in general

Suppose main.php includes header.php which needs main-validate.js which uses utils.js.
But, main.php also requires utils.js in its own right. (Moreover, other other .php files will include javascript which includes utils.js.) How do we handle multiple includes?

  1. Nest includes: A's code would just require B; then in turn B's code would require C.
    However, if A itself needed some of the functions inside B, it would re-include that file.

    Advantage: simple to maintain — if you want to use a function defined in my-utils, you only need to require that one file, and you don't have to worry about what pre-requisites my-utils has.

    Disadvantage: Underlying files may get included many times (perhaps you require files D, E, and F, and each of those requires my-utils.

    Here is an example where require-master.php requires both require-util.php and require-helper.php ; in turn, require-helper.php also requires require-util.php.

    A more difficult disadvantage: You can't always use relative paths: if require-master.php does a require('someOtherDir/my-utils.php'), and then require-helper.php happens to require('../../my-utils.php'), note that second relative path is relative to require-master.php, not relative to require-helper.php! [Solution: use require(dirname(__FILE__)."/".relative/Path], as mentioned below

  2. Alternately, Don't nest any includes; if file A requires B which requires C, then A's code would require both C and B (in that order).

    Advantage: No file ever gets included more than once.
    Disadvantage: The programmer needs to be aware of (or frequently re-read documentation of) which other files include'd file needs

Clearly, the first option is preferred, from the programmer's point of view. But what language issues are there?

Language-specific issues


1Of course, if the file contains content — like a navbar — that you want to appear multiple times, then you'd avoid the “_once” version.      

2Taken from forums.digitalpoint.com/showthread.php?t=146094      

3Taken from www.cryer.co.uk/resources/javascript/script17_include_js_from_js.htm      

homelectsexamshws
D2Lbreeze (snow day)


©2012, Ian Barland, Radford University
Last modified 2013.Mar.27 (Wed)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Powered by PLT Scheme