This question already has answers here:
Autoloader for functions
(13 answers)
Closed 1 year ago.
I have a single functions file for my entire site and given a single page 90% of the file is not even called. So i want to load only the functions which are called in the page and i am new to php.
Group functions together into several objects with common traits, by making them static functions, and put each object in a separate file. Then use PHP5 autoloading functions to load appropriate objects only when they are used.
You can split this file into many small files and include only that you need to use.
However if it is not a big file it will not decrease your performance at all
You could split up your functions file in multiple files, but mind that if you need more files, loading may even be slower, because you need more IO commands to load the different files.
Futhermore, you split files by functionality. If you feel all these functions belong together, keep them together in that file. It will not slow down your script very much.
If you like, you can put the functions in (static) classes and use an autoloader to load the file, but I'm not in favor of this solution. I think static classes are just an excuse to get functions (and vars) out of the global scope, and creating classes just for auto-loading is abusing the autoload functionality.
Of course, if you create a more object oriented script, using classes makes sense too, and auto-loading them might be convenient.
Actually it's not a problem to have a function available for use but you only use it in part of your application. It's more important you have everything when you need it at hand w/o actually caring about when to load.
If your system grows, what you might look for is an autoloader. PHP supports autoloading of classes but not for functions. However you can group your functions into classes (some will slap me for making such a statement) to make use of autoloading then.
If Your file size is not big then it will not decrease your performance at all.still if you want to achieve your goal then group related functions and place them in separate files and include only necessary files...
Related
Currently I load in all my classes by including a "all.inc.php" file on every page of my site, this file then goes on to include all the config, classes, functions, etc. that I will use on the whole site.
My issue with this is that often I use classes that only pertain to certain pages/sections of a website, so often I am including a bunch of classes at the start of the page which will not be used.
Obviously autoloading the classes would fix this issue, so my question is, would autoloading the classes give me a performace downside as the server then has to check if a file exists? And if there is a downside, then is this downside worse than having to include a number of classes that may not get used on the page? Or is the difference negatable?
This article has some information and benchmarks: PHP autoload performance (archived). Conclusion:
Autoloading does not significantly degrade performance. Include_path lookup, reading and parsing PHP scripts from disk takes much longer time than that bare autoloading logic costs.
Autoloading a class is almost as fast as including the class in the normal way. Switching to autoloading will improve performance in your case, because PHP loads less files and classes.
Autoloading will improve the performance if the script does not have to search the files each time in the filesystem. If you use namespaces you can have a nice mapping of the namespace and class name to a folder and file like Some/Nice/ClassName would map to Some/Nice/ClassName.php.
If you do not use namespaces and have to search through folders I suggest you to create a custom singleton class to include files that allows you to do something like:
App::uses('Some/Nice', 'ClassName');
In Autoload use the registered path and class name to map it to a path and file combining both args from the uses method in my example. This will allow you some namespace like functionality for class loading until you're ready to change your app to use namespaces.
You should use autoloading with cache index of all available classes/files in project.
Example:
$class_cache=array(
'MyClass'=>'lib/MyClass.php',
'Item'=>'model/Item.php'
);
function __autoload($class_name) {
if(array_key_exists($class_name))
include $class_cache[$class_name];
else
throw new Exception("Unable to load $class_name.");
}
You need to keep class list actual or write some generator for $class_cache.
Each include() and require() (and their _oncesiblings) carry a performance penalty on their own. Disk seeks and reads also come at a cost. It really depends on your code, if you are loading 20 classes but use only 2 or 3 at any single point, then it's definitely worth going the autoloading route.
If performance is your main concern, you should look into merging your class files into a single file and instantiate what you need.
A really old question, but all the answers were actually wrong.
... autoloading takes a significant amount of resources. The number varies a lot and that’s maybe not what you’ve seen in your own app, but a typical 10% wouldn’t be surprising.
from CTO of Blackfire.io, so I'm sure he knows what he is talking about. Read more here
I have this problem that is really causing me headeches whenever i'm designing my apps in php: I don't know if i should create separete files for each function(e.g.: functions for validating specific forms).
OK, one would possibily argue that this makes no sense because I would have to include each file separetly and this would result in a more slow application maybe?
But I still think it does make sense since for one pageload i doubt that other functions would be used by the script at all, so they must be loaded just for nothing? besides, i don't have to include each function-file manually if the system i design does this dinamically (parsing url vars or such) for me, that is, loading function(-files) exactly when needed. What do you think?
The overhead in file includes is minimal, you shouldn't have to worry about it really, considering caching and other things. Of It's more about how you can keep yourself organized and find your stuff quickly.
Honestly, I rarely use functions, I use classes. The rule is usually to have a class per file. But I also have a toolbox file that contains all my global functions.
Are you using OO? If so, then you should definitely keep it one class per file, and name the files intelligently...
class Page {
...
}
should be findable somewhere like classes/Page.php or includes/Page.class.php or similar.
If you just have a bunch of global functions, you should group them in files, e.g. includes/functions/general.php.
To elaborate, your functions folder may have...
array.php
string.php
form_validation.php
request.php
general.php
html.php
If you are organising your files like this, a better idea is to use a class and make the functions static, e.g. string::isAlphaNum($str). This is a better idea because it only introduces one new term to your global namespace, instead of a bunch of them needlessly.
If you are using PHP 5.3, you could also look at namespaces.
You should just make sure that you have APC, xCache or eAccelerator installed. All of them provide cache for compiled PHP bytecode.
It means that once the file has been included it will be stored in memory and ready to use by feature requests. There won't be any need to include files.
You will almost certainly see a more significant performance hit through increased disk I/O reads on (many) multiple file includes than for smaller set of files with many functions.
For automatic file includes, wrap functions into suitable classes and use spl_autoload to let PHP handle the include process.
I'm trying to find the best pragmatic approach to import functions on the fly... let me explain.
Say I have a directory called functions which has these files:
array_select.func.php
stat_mediam.func.php
stat_mean.func.php
.....
I would like to: load each individual file (which has a function defined inside) and use it just like an internal php function.. such as array_pop(), array_shift(), etc.
Once I stumbled on a tutorial (which I can't find again now) that compiled user defined functions as part of a PHP installation.. Although that's not a very good solution because on shared/reseller hosting you can't recompile the PHP installation.
I don't want to have conflicts with future versions of PHP / other extensions, i.e. if a function named X by me, is suddenly part of the internal php functions (even though it might not have the same functionality per se) I don't want PHP to throw a fatal error because of this and fail miserably.
So the best method that I can think of is to check if a function is defined, using function_exists(), if so throw a notice so that it's easy to track in the log files, otherwise define the function. However that will probably translate to having a lot of include/require statement in other files where I need such a function, which I don't really like. Or possibly, read the directory and loop over each *.func.php file and include_once. Though I find this a bit ugly.
The question is, have you ever stumbled upon some source code which handled such a case? How was it implemented? Did you ever do something similar? I need as much ideas as possible! :)
One way you could pull something like this off is to put those functions into classes and then set up an __autoload function. If you are against wrapping the functions in classes than this solution probably won't apply to you. Personally I like it because it allows me to namespace my functions and share private methods between them.
First you set up your autoload function similar to this. You'll want to adjust the naming convention to fit your own style, and probably introduce some error handling, but this is just to get the basic idea across.
function __autoload($class_name){
require_once(strtolower("library/$class_name.class.php"));
}
Then anywhere in your code regardless of scope you can do something like this.
arrayFunctions::doStuff($myArray);
PHP will automatically try to include "library/arrayFunctions.class.php" and look for a method called "doStuff" in the arrayFunctions class.
I have issues with this idea. Hitting the file system to include a single function is very expensive in the terms of it lowering your max possible requests per second.
It's generally much better to load/parse five functions in a single file (static class?) and only use two of them (one stat call) rather than load two files for two functions (two stat calls).
Which obviously becomes even worse when you need all five functions.
To automatically load stuff when need, put your functions in classes and use autoloading.
For the name conflict, use namespaces (if you have PHP 5.3).
I have a javascript file that communicates to a controller class, which in turn delegates which function to run to a transactions class.
Is it better to have the transactions class broken up into multiple smaller files and then in my switch statement include which ever smaller file i need? or should i have all my transactions in one file?
I know keeping file size down is always a good idea, but will that affect my ajax functions if my transactions file starts getting pretty lengthy?
I vote for smaller files, so you avoid antipattern : God Object
Whether you include files or not is really up to you, and in the end they use up very minimal disk i/o unless you include like 100 files.
What I'd suggest is breaking them up into smaller files based on sets of functions (HTML functions, URL functions, etc) or classes (one class per file) just like any other script.
This is partly to save your sanity, and also because it is a good practice to simply seperate everything so you can take one file containing all of X functions over to another project that needs the same functions.
How do you manage your php codes? Do you prefer functioning within one php file or including larger blocks of "raw code"?
Edit: In fact, my code is pretty nasty, as I don't use any namespaces and classes - only functions and including. I shall look the classes up ^^.
Use them as you need them.
I use include for chunks of big code doing processing, and functions for "utility" functions. Sometines i use includes within function also... it really depends on how clean you like your code.
Think that many includes means more fopen() from the PHP module, and those can slow doewn the whole script execution..so dont try and put too many includes though.
If you are using php classes, this will sort itself out. If you are not, then it's really hard to give an acceptable answer, except that you should learn to. All php code I've seen done either way without classes seems to become quickly messy.
I agree that OOP is the way to go. Large solid blocks of code are nightmare for maintenance. Definately not the way to go. You should split your code into small blocks that interact with each other and are easily maintanable on their own.
When I used to program in PHP I liked to group general utility functions in a common file to include in most of the pages, and group classes in dedicated files, to load them only when needed.
I typically use functions/classes for logic and includes for display. I end up with something like this in a controller...
case 'widgetlist':
$widgets = $DAO->getWidgets(); //get some query
include('view/showWidgets.php'); //assume a global $widgets variable
break;
I have found it easier to give an HTML/CSS designer an include rather than a function call which displays. The down side is that I rely on globals to pass variables to the include rather than arguments which are much safer.
I make classes in separate files, with the correct prefixes as namespace (until they are included at least). I also put functions as static methods in "static classes" for the namespace effect.
I use autoload to include the files so I don't have to write a hundred includes.
Save My_Example_Class as {lib}/My/Example/Class.php
The thing I'm working on has one included file at the top of every page that contains all the global functions and database setup stuff. It works as-is but I'm now moving the functions into separate files, because with everything in a big lump it's completely impractical to do any testing.
PHP has an __autoLoad () magic function that you can use to intercept class calls. If the class doesn't exist yet, you can setup some simple code to go and look for the proper class code to include. It will then continue to execute as normal.