I am a PHP beginner. I have developed a social networking website similar to Orkut in PHP.
The basic program flow of my website is redirect everything to index.php
The index.php determines the $_SERVER[‘REQUEST_URI’] and does what needs to be done and render the output.
I initiaze all the classes at the top of index.php I want to know if it is a good practice to do this or not.
The index.php starts like this :-
// all the configuration files
require_once ("siteconfig.php");
// include library files / classes
require_once "lib/auth.php";
require_once "lib/album.php";
require_once "lib/db.php";
require_once "lib/form.php";
require_once "lib/inbox.php";
require_once "lib/social.php";
require_once "lib/profile.php";
require_once "lib/user.php";
require_once "lib/settings.php";
require_once "lib/validate.php";
require_once "lib/logs.php";
require_once "lib/sms.php";
// initialize all the classes
$db = new db($dbuser, $dbpass, $dbname, $dbhost);
$validate = new validate();
$auth = new auth();
$user = new user();
$profile = new profile();
$social = new social();
$settings = new settings();
$usersearch = new usersearch();
$album = new album();
$logs = new logs();
$liveupdates = new liveupdates();
$sms = new sms();
Initializing all objects from the start is obviously a bad idea. Less obvious is that using “new” in your “main” code is not a brilliant thought either. Use a “loader” that provides you with objects (not classes) you need and avoid “new” outside of the loader.
// edit: why we would need this?
Imagine you have a number methods in your Controller that use the Sms object. If you use “new” and an explicit class name (the “wrong” approach above), 1) you must provide initialization data (e.g. sms gateway address) for the object in each method, 2) you have to edit your Controller code in case class name or constructor signature changes and 3) your cannot temporary replace Sms object dependent on a condition (e.g. “DummySms” for testing on your local machine).
With Loader class all issues are no problem, because you write all object initialization code exactly once.
(More precisely this pattern is called ServiceLocator, see http://martinfowler.com/articles/injection.html for more details).