This is the first time I'm doing a project in complete OO style. My classes look very messy. I found myself doing require_once
on a bunch of class files and creating new instances of classes. So I put all the requiring and creating instances into a separate file (init.php) like so:
<?php
require_once 'resources/config.php';
require_once 'classes/db.php';
require_once 'classes/auth.php';
require_once 'classes/msg.php';
require_once 'classes/validate.php';
require_once 'classes/view.php';
require_once 'functions/misc.php';
//DB connection
$db = new DB(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$dbConnection = $db->connect();
$msg_class = new Msg();
$validate = new Validate($dbConnection);
$msg_strings[] = array();
$view = new View($dbConnection);
?>
Now I'm just doing require_once
on this file.
And I don't use the View class in a few pages. So is it a bad practice and not good for performance to create instances of a class if I'm not going to use it?
The best practice is generally to use an autoloader
, PHP provides an excellent autoloader for this purpose - SPL autoloader : http://php.net/manual/en/function.spl-autoload-register.php
You can create a callback which will automatically be called by PHP when a class is not found, in this callback you can require / include the folder path where PHP will search for your classes, you can also register multiple autoloaders which will be called in the order they are defined, example below -
function auto_loader($classname) {
//search in the classes folder for a class file.
include 'classes/' . $classname . '.php';
}
function auto_load_somethingelse($class){
//include here
}
//register the autoloaders
spl_autoload_register('auto_loader');
spl_autoload_register('auto_load_somethingelse');
Place this at the top of your file where you have called your init.php file and the autoloader will be called whenever it finds a class that needs to be auto-loaded.