|[ Team LiB ]|
Using include_once() and include_path to Manage Larger Projects
As your projects grow larger in scope and you find yourself including more and more files, keeping track of your work can be difficult. You can recover control by organizing code into libraries and organizing your libraries into packages.
As you work on a project, you should look for opportunities to create libraries that might also be useful for other projects. Try to create code that is as independent of your wider application as possible. The most reusable classes or functions will require data and perform tasks without relying on global variables. As you add to your stock of code, you can organize it using the file system itself. Let's imagine a programmer named Mary Jones. Mary has created the following range of useful classes in files:
DatabaseLayer.php XmlHelper.php Logger.php
Mary might use directories to organize these libraries, like so:
maryjones/db/DatabaseLayer.php maryjones/xml/XmlHelper.php maryjones/util/Logger.php
When it comes to accessing her libraries, Mary faces a problem. She can use a relative path to reference a library, like so:
include_once( "../lib/maryjones/db/DatabaseLayer.php" );
Or she could use an absolute path, like so:
include_once( "/home/mary/htdocs/lib/maryjones/db/DatabaseLayer.php" );
Both these approaches have their problems. The absolute path ties Mary's project to the current server, so she will not be able to deploy the project on another server without changing the absolute paths throughout. The relative path approach is better, but it forces Mary to include the maryjones packages within the calling project. It would be more effective to make the libraries globally available. Furthermore, even relative paths reduce flexibility to some extent. Mary cannot move the maryjones directory without updating all files that include it.
Mary can deal with this shortcoming using the include_path configuration option in the php.ini file. You can use include_path to define a list of directories that will be searched when include() type functions specify relative paths. Directories should be separated by colons (semicolons on Windows platforms), as shown here:
In the previous fragment, Mary has added a path to a php_lib directory. She stores her maryjones directory there. Now any PHP file can include a maryjones package library:
include_once("maryjones/db/DatabaseLayer.php"); include_once("maryjones/xml/XmlHelper.php"); include_once("maryjones/util/Logger.php");
As long as the include_path is set, Mary's code runs on another server without any changes.
If Mary has no access to the php.ini file on her server, she still has other options. If she is running Apache, she can set the include_path option in an .htaccess file:
php_value include_path /home/mary/php_lib
She could also use the ini_set() function to set the option at runtime:
set_include_path( "/home/mary/php_lib" );
|[ Team LiB ]|