If I had a large number of functions would it be better to keep them all in one large file or would it be better to separate them into several files of related functions. By better I mean more efficient for both maintainability and for the server processing the request.
For example right now I have all my files in a file named include.php. But would it be wiser to have an include file of includes like:
<?php
include('/functions/user.php');
include('/functions/admin.php');
include('/functions/content.php');
include('/functions/nav.php');
include('/functions/database.php');
include('/functions/other_junk.php');
?>
Definitely separate them, for maintainability sake. I doubt performance will suffer at all, but even if it does (just a teensy bit) you're better off writing maintainable, readable code.
You want to be sure you're using a PHP cache like XCache or APC. Your PHP files should then all be in memory and you shouldn't be worried about your includes hitting the disk at all.
I would definitely find it easier if you broke up like minded functions/classes into their own files.
In terms of maintainability, it's usually better to separate your functions into related groups. ( like you showed above, user.php would be only the user-related functions ).
You should only have a file that has all of those includes if you know that you'll need all of the included files every time you need to include any file.
Otherwise, it defeats the purpose of having that 'catch-all' file.
In my experience multiple includes and/or requires generally arent goping to set you too much back if youre talking a couple dozen or so files for function libraries. Especially if you can manage to only call the statement for a particular file once during a request lifecycle.
Where it starts to show performance hits is if you get into OOP or a highly complex functional/procedural type architecture where there may be hundreds of different classes/files. But generally at that point youll have hopefully done some kind of mitigation via caching/compiling.
I have a list of includes in a central .config file.
For all OOP classes though I use autoload -> I know it's slightly slower, but it saves having to including them as I make a new class. And they're only loaded as required.
As an aside, include is quicker than include_once as it doesn't have to check if the file has been included already.
Related
Should I try to keep all helper functions in the same file (say, all in functions.php) at the cost of reading in unnecessary functions, or store functions in separate files where I'll only include files with functions I need, at the cost of the overhead for including more files? How big of an overhead is there to include separate helper files? I know for images like icons it's faster to join icons together in 1 image, but I'm not sure if the same applies here.
This completely depends on the project you're working on - sometimes the one approach may be faster, sometimes the other. But in general, just avoid making lots of global helper functions and put them in appropriate classes instead, as static helpers if need be. Then read up on autoloading and watch as PHP's magic solves the problem all in one go for you - loading and parsing the files automatically as you need them.
If you also use PHP 5.5+ (or an older version with an opcache-like extension) the code will even be precompiled, lowering overhead even further.
Generally speaking some more - once you're starting to worry about the parsing overhead of your code you're usually guilty of premature optimization. In a world where nearly all webservers have quad core hyperthreaded multigigahertz processors and are backed by RAID SATA storage, loading an extra file isn't going to be a realistic problem. Find the real bottlenecks when all the code is done, and spend your optimization time there.
So here is what I want to do.
The first option is to write each
function in different php file each
one and then include all of them in
a php file that is called include
functions.php and whenever I create
a new page , let's say index.php I
just include "functions.php";
Why do I need to do that? Because I'll just have to include only one file and all the functions will be included. Now the problem probably will be the server load. I'm not sure how much uncalled functions affect the performance.
The second option is to create again the files I need, team them up and then whenever I need a function just call it. The drawback of this is that I'll have more work to do in order to categorize and I'll have to include a lot of files
So I want to ask, does the first option increase the cpu and memory load that much that I have to go to the second one? Are there any performance issues with the first way or the functions that are not being used are not parsed at all by the php ?
Disk is a slowest part of the server, so in this case variant "all functions in 1 file" will give you little more performance, theoretically.
But I don't recommend you to create "functions.php", better way is OOP. Create classes (objects) with methods, use autoloaders and PSR-0 standard and you will forget about "include" and "require" at all.
This is a time to remember Donald Knuth's famous quote:
Programmers waste enormous amounts of
time thinking about, or worrying
about, the speed of noncritical parts
of their programs, and these attempts
at efficiency actually have a strong
negative impact when debugging and
maintenance are considered. We should
forget about small efficiencies, say
about 97% of the time: premature
optimization is the root of all evil.
Yet we should not pass up our
opportunities in that critical 3%."
In general, your development model should be tuned to match the needs and goals of the project. After you have met the goals, you can always return to such questions as the one you asked. When you do that, your question will probably answer itself. The program structure will dictate the best way to handle your includes.
You may wish to consider using object-oriented programming (OOP) if it is applicable to your project. Whenyou use OOP, this problem may even become a non issue if your objects handle their own dependency loading.
My current workflow I include function and class files as and when I need to. However, this can get quite messy with you have quite a lot of them in which some depend on others.
So I'm considering using a head file which includes on the files in the includes directory. But my question is, are there any PHP performance issues for doing this over including as an when i need. Often times I have to use include_once, so doing 1 big include would get rid of the need for this.
The best approach would probably be autoloading. You do not need to (manually) include any class at all, then. Take a look at this. I recommend using the spl_autoload_register()-function. That would resolve dependencies on the fly. The performance of includes is really irrelevant in most cases. The slow things usually happen in other places. Using autoloading has the added benefit of lazy loading. You do not load source files that are not in use. This might even speed up your application.
Normally performance (speed) in PHP is not affected by the amount of codelines or files but of:
Access to db
Access to file system!!!
Access to third party APIs (SOAP...)
Coding style
PHP code is interpreted on the fly. If a given piece of code is not used, it will not be 'compiled' and so will not incur a performance hit.
However, all code on a given page (and its includes) goes through a syntax check so that may slow things down a little.
Certainly I would consider the includes that you have and whether or not you really need them.
There is a performance effect but it is not a very significant one. Do whatever makes it quicker and easier for you to write the code. If down the line you find that you really need that 1ms back, and you have already trimmed all of the other fat elsewhere, then go for it. Otherwise you are throwing away development time on trying to be "perfect" when it never actually makes a practical difference.
I would recommend you look at autoloading: manual. I would also recommend using spl_autoload_register over one __autoload() function as it allows for greater control with separating out modules or namespaces.
Well including files does have a hit on the performance of your app because it needs to read your app from the disk but if you stay below about 100 files this is trivial.
Btw if you don't like having to include your class files every time check out the magic method autoload:
function __autoload($class_name) {
include $class_name . '.php';
}
http://php.net/manual/en/language.oop5.autoload.php
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.
So far I have about 3 PHP includes on my site.
<?php include("includes/header.html"); ?>
Is there any reason why I shouldn't add a ton of these?
Not really. They're used quite often and liberally—though more often than not, to include other PHP files. Those PHP files then often include other ones, so there's really no concern.
By the way, if you do use this technique to include other PHP files (e.g. library files with functions you're using), it's a good idea to use require_once (there's also include_once, as well as plain require); require will cause an error if its argument cannot be found, and won't continue trying to render the page. require_once (and include_once) will not include the same file more than once, even if you call require_once (or include_once) from different places.
I suspect that you are doing something like this:
<?php
include("session_and_headers.php");
include("top_nav.html")
include("right_sidebar.html");
?>
... actual content generation code ...
<?php
include("footer.html");
include("js_loader.php");
?>
There is nothing inherently wrong with that for simple static sites, or situations where users will have only several distinct views.
But, what happens if you want to use a slightly different side bar on only certain types of pages? Where do you put the logic to determine that so it is obvious to the next person who inherits your code?
If you get into those kinds of complexities, I recommend going with the MVC approach (even if you mostly use the view/controller aspects of it).
If you're doing a nn page site in PHP that just needs to share common elements, then there is no reason to avoid simply including the files as needed.
Don't look at this so much as is it bad for PHP, look at it more as is it hard to maintain?
There's one advantage to writing object-oriented code and upgrading to PHP 5: you can avoid a "ton of includes" using class autoloading.
Only downside is performance - each include costs you system calls. With 3 or 10 it's all small change unless your traffic is huge, but about 100 may be a problem. The solution is to use a bytecode cache (like apc) and set your realpath_cache_size variable to higher value (default is enough for about 100-200 files, depending on the path lengths).
Other than that - not much of a problem.