i’m a php novice, and i’m wondering the best way to go about using previously defined class methods from a front facing ajax file. i trolled through 50 or more of the top questions looking for something similar to this, so my apologies if this has been asked before.
my project is set up using a front controller which calls initialize.php, which then includes all the class files i’ve made for this project thus far, whether those class methods/properties will be needed now or not (if this is super bad then someone please tell me an alternative :[[). so basically, for every request made on this site initialize is called, all of those classes are defined and two are instantiated immediately, those two being the classes i use for the database and sessioning/login stuff.
i’ve been doing this in my ajax files:
<?php
// login.ajax.php
require_once 'initialize.php';
$email = $_POST['email'];
$password = $_POST['password'];
$remember = $_POST['remember'];
global $session; // this is instantiated right away every time
$login = $session->login($email, $password);
echo json_encode($login);
?>
recent complications are now making me rethink this approach. constantly loading initialize seems really wasteful, but including/requiring just the necessary class files would be a pain in the ass at best. in this example i’d need to include session, which would also need two other classes to perform this login.
It seems you may wish to use PHP autoloading mechanism.
To see some details, please go to the PHP autoloading documentation. You can read there that:
Within your initialization file (or separate one, depending on your design decisions) just define
__autoload()function that will be used to include required files:This should solve the issue / need of multiple requirement / inclusion declarations – from now on, when you instantiate some class and it is not available, newly defined function (
__autoload()) will be called to include necessary files.