Reputation: 7723
I have built a PHP video upload library aimed to be used in different frameworks . ## HERE ##.
But i want to make it optimized like , i dodnt want to include or make\
require or require_once call in class and also i want the configuration class to be available to all class i have at run time ... without explicitly calling or making require once.
How can i do that , most php project use bootstrap class /file to do that , and some body pls help me.
Upvotes: 1
Views: 689
Reputation: 7020
You can create an autoload function . This way you will only load the required library.
A basic autoload function looks like this:
define('PATH_LIBRARY', '/some/path/lib/');
function myautoload($class_name){
// you can do string manipulation to build the filename, for example
$filename = strtolower($class_name);
$filename = str_replace('_', '/', $filename);
$filename = ucwords($filename);
$filepath = PATH_LIBRARY.$filename.'.php';
if (file_exists($filepath))
{
require_once($path);
return true;
}
}
spl_autoload_register('myautoload');
Edit that code has to be added at the beginning of your code (usually in a file included at the top of your index.php
), so all instruction after will benefit of it. You can improve it by checking different directory (for example if the class name starts with "controller", or "model", change the path to the appropriate directory)
Upvotes: 2
Reputation: 431
I would suggest to make a way to have an auto_load.php
file and this file would contain the files required to include, and then you can include this auto_load.php
into the entry point file / class to your library to load all the necessary files for your library to work. It is the same idea as how composer
work and it is efficient.
You can take a look into psr-4
standards in loading classes.
http://www.php-fig.org/psr/psr-1/
require_once
is the same as require
except PHP will check if the file has already been included, and if so, not include (require) it again, refer to http://php.net/manual/en/function.require-once.php
Upvotes: 2