What is the best way?
include the script
write the script as function in for example functions.php, include the functions.php and call function
thanks
Use the include:
include('functions.php');
Once you have included a file that contains any variables, functions, classes, you can call them normally because now they are part of the script where you have included them.
I still don't understand the differences of your approaches.
But if you have a lot code in this file, indeed, the best way would be to write your code as functions (if you do not already have that) and create several files that contain those.
You should try to categorize your functions and create an own file for each category. Then you have more control over which functions you include and you don't have to include all of them, you just include those files you need the functions from.
For example you can create a file database_util.php that contain database related functions, etc.
In the long run, you should learn about Object Oriented Programming, but don't misuse classes / objects as container of functions. This is not the purpose of OOP and won't help you much.
The decision to either include or use a function is not always a simple one.
In general: if you reuse code in a lot of places you should probably make it a function. Among other reasons a function has it's own variable scope which makes programming neater and more reliable.
If your code occurs only once, is seldom used or when the code to be loaded is not always the same code then including it may be better.
In neither case is the speed of loading an issue. The time difference is in 99.99% of all cases insignificant. The decision whether to use a function or an include should be made on the basis of code organization: what is easier to understand for someone maintaining the code.
In practice you akways use a function or an object to organize your code, unless there is a very compelling reason not to.
Related
Quick question about include/requre_once . I have some code that is common to a few pages that I feel would be better to be in a file to call from each page rather than code repetition.
I call the include_once in a while loop and what I noticed is that I have to use include('file.php') or it will literally load it (and display it) only once . I guess what I assumed ( incorrectly) is that it will load it on the first loop and retain the code in a cache to avoid having to access the disk each iteration of the loop.
I looked around for a "load_once_and_cache" type of command but did not find anything.
Does anyone have any suggestions for this or is putting the code in each page the only option.
Thanks again!
This is a pretty inefficient method of getting content into a loop. PHP would need to read the file from disk on each include() call. You're much better off creating a function (which may be in the included file). Include the file once, which defines the function, then call the function in your loop.
It isn't always good practice to rely on the output of an included file, except perhaps when coding a view (even then I'd think twice before doing it). Requiring a file to be included inside a loop creates a strange mix of flow control and file inclusion that can be difficult to debug and maintain.
Since the air around you post smells like a complex structure and massive amounts of code, I'm going to assume you are using OOP techniques in order to get things done.
In this case, maybe you will want to consider autoloading classes as a more efficient and fast method:
http://php.net/manual/en/language.oop5.autoload.php
You will also need to read the comments in order to fully understand what's going on and find some really methods to manage various situations.
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'd like to check if my understanding's correct about require_once(). I have a bunch of functions in file foo.php. Let's say 7/8 out of them are always used, and one of them's rather rare and rather large. I have to keep this function's definition in foo.php. Can you tell me if the following approach achieves anything, and if you think it's worth what it achieves.
Take out the body of the function and put it in an external file.
Redefine the original function to require_once() that particular file and pass execution over to the helper function.
I understand this could save server memory on the requests where that function isn't run. What exactly am I saving though? Just the memory it takes to hold the body of the function? That would mean it would have to be a pretty big function before being worth it I guess. Also, if I'm using something like APC does it become less useful?
Please correct or add to this as appropriate!
Thank you very much.
I highly doubt you will gain anything from refactoring it into a separate file. Also, do you actually have any problems with the code as it is now that makes you consider this? You know premature optimization is the root of all evil. Profile your code to see if and where it has bottlenecks before you waste your time on pointless µoptimizations.
Update: From your comment to Gordon I see you're using Drupal: This method doesn't work there, because Drupal is heavily object-oriented already. What is described here is making use of the Autoloading mechanism for a function-based project using static classes.
As Gordon says, this will save memory only for really incredibly huge functions. In my experience, though, loading includes into memory takes up much more space than the exact number of bytes needed to hold the code. I'm not a PHP internals expert, but I assume the code is parsed or at least preprocessed either way.
Assuming your PHP application is entirely function-based with no OOP, one idea that comes to mind that you could use to split up your includes is putting your functions into classes, and making use of the autoloader mechanism:
class maintenance_functions
{
public static function xyz() { ................ }
and start calling them statically:
maintenance_functions::xyz();
one class would occupy one file.
Group all the rarely used functions into separate files.
Then, you could make use of the Autoloading mechanism. This will load needed classes automatically at the point they are needed. If I for example, call
datamining_functions::xyz();
the autoloader will look for the file containing datamining_functions and include that. This eliminates the complete 'require()' hassle and lets you concentrate on how to group your functions most efficiently.
This is not a real transition to OOP: We just use class constructs to group the functions, in order to be able to use the autoloader. It should be possible to migrate functions into such classes without the need for major rewrites.
You should use Xdebug to find out the answer - worth or not is subjective.
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).
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.