ChronicFatigue wrote:
Thanks for the response...
Are there are other 'fundamental tips' you may have regarding how you
should code now to avoid potential difficulties when changing servers in
the future?
a) avoid the use of paths in your code. e.g., include(
"dir/anotherdir/something.inc.php" );
b) instead of using include() and require(), write classloader-like
replacements for them and use those to find your files for you. This is not
as hard as it sounds: 1 hour of work or so. Contact me off-list if you'd
like some sample code.
old style:
include( 'path/to/foo.inc.php' );
more generic approach:
my_include( 'foo' );
c) if you make heavy use of classes, write a classloader (they're EASY to
implement in PHP). Again, contact me off-list if you'd like some sample
code for this.
old style:
include( '/path/to/Foo.class.php' );
$foo = new Foo();
with classloader:
$foo =& classload( 'Foo' );
if( ! $foo ) { /* it didn't find the class */ }
d) avoid global vars at all costs. For example, i use the following function
to get at global vars:
################################################## ##############################
# r_find_var():
# i was sick of trying to figure out if a var was in GLOBALS or one of
# HTTP_xxx_VARS, so i wrote this laziness fixer.
# Looks in GLOBALS, HTTP_(POST,GET,SERVER,COOKIE)_VARS (in that order)
# for the given var, or returns a reference to $defaultval.
function & r_find_var( $var, $defaultval = null ) {
global $HTTP_COOKIE_VARS, $_r_flags;
foreach( array(
$GLOBALS,
$_GET,
$_POST,
$_SERVER,
$_COOKIES
)
as $ar ) {
if( isset( $ar[$var] ) ) return $ar[$var];
}
return $defaultval;
}
Then all of your global lookups look like:
$foo =& r_find_var( 'field_from_form', 42 );
if( $foo == 42 ) { /* it wasn't set */ }
This saves you from the primacy of things like:
$foo = $_POST['foo'];
if( ! $foo ) { $foo = $_GET['foo']; }
if( ! $foo ) { $foo = $GLOBALS['foo']; }
// ad nauseum...
i really think those are the most important bits. i cannot over-state the
maintenance benefits of using a classloader and classloader-like
replacements for include() and require(). They make your code much more
mobile and much easier to maintain. With those you can move your included
files whereever you like, update one config file (which is part of your
app, not part of the PHP setup) and you don't have to change any other
code.
:)
About the sample code: you can find it buried in the source tarball
available here if you like:
http://stephan.rootonfire.org/radioaqtiph/
the more generic bits are in classes/core/*.class.php
but some of those classes aren't useful and may be downright bogus
(TypedList.class.php comes to mind).
There you can also find an example of a classloader which CREATES classes on
the fly from a mysql database.
--
----- stephan beal
Registered Linux User #71917
http://counter.li.org
I speak for myself, not my employer. Contents may
be hot. Slippery when wet. Reading disclaimers makes
you go blind. Writing them is worse. You have been Warned.