PHP include_once or require_once in a loop - php

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.

Related

Proper PHP coding style

I'm working on a new project that is going to make heavy use of different AJAX calls to PHP. Is it proper to create one file that contains all the different functions and use a case statement to pick the proper one, or should I create a php folder and put each function in its own file?
I'm trying to get my skills back on track with modern web design standards and practices, and in the past, one file to rule them all was the way to go for simplicity sake; however, so much has changed that I wanted to ask before I got 10,000 lines into this project.
Thank you for any advice you can provide.
This question will illicit a lot of personal opinion.
Case and point, my opinion:
Code re-usability is key of any programming language. Store like functions together in an include file, include the type (or however else you organized your functions) in the main module in which you need those functions in. You shouldn't put one function per file, but at the same time one huge file with 400 functions in it would be a nightmare.
Just use a modern framework and the style it will impose on your coding.
and use an Opcode, which will enable you to write clearer code without impacting performance.
Some modern framework names will be Zend, Yii, Codeigniter etc
Instead of thinking about the implementation of the problem why not think about the interface?
This is what I mean, you could separate the real work to done in classes somewhere, and let the ajax make calls to another separate classes/function. Then the functions called through ajax can query the different classes/objects to accomplish the work and send respond back to ajax. It may sound like the MVC pattern. The advantage of this is clearly code reusability , improved decoupling and easier code maintenance.
Example:
class Cook{
function friedEgg(){/**/}
function currySoup(){/**/}
function sandwich(){/**/}
}
And function called through ajax could be
function ajaxBreakfast(){
$cook = new Cook;
$result = $cook->friedEgg();
$result .= $cook->sandwich();
echo $result;
}
function ajaxLunch(){
$cook = new Cook;
$result = $cook->currySoup();
echo $result;
}
Hope you get my point!
If I understand, it's totally fine to have all your functions in the same file (if you're making a really big site, you should probably divide them; like functions for this section, functions for that section).
I'm not sure why you would use a switch statement to pick them; sometimes it's useful but normally won't you just be calling the functions directly? Like include the "library" file, and call "getNewId()" whenever a user registers or something.
IMO it depends.
If your Ajax script is 10,000 lines, and you are handling dozens or hundreds of Ajax requests per second, and you are not using an opcode cache for PHP, you are going to waste a lot of time and resources loading such a large script into memory, parsing it, and executing a few lines from it.
If you have 2,000 lines, and a few dozen ajax calls per minute, then it's not as big a deal.
One file per function may be a bit overkill as well, perhaps there are some functions that could be grouped together and then you include the file when any of the functions related to that file are called.

PHP Performance on including multiple files

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

Simply include the script or a function?

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.

php & mySQL: Load only functions that are needed and only on demand while avoiding duplication

I use the following procedure to call the functions within the pages of my web app.
//index.php
include("functions.php");
include("file1.php");
include("file2.php");
I have all my functions going into functions.php page. The content of this page may be over 5000+ lines of code and it contains all the functions used within the website. So loading 5000+ lines of code in all the pages of my website, even when it's not needed, seems like a lot of load. So my questions is:
How to load only functions that are needed and only on demand without having to create a separate functions page for each of my pages?
Please consider this example:
//functions.php contains functions f1 through 10
function f1()
{
//do something
}
function f1()
{
//do something
}
...(through)
function f10()
{
//do something
}
If index.php page makes use of only functions f1 and f2, how can I load only those 2 functions on that page, without having to load all the rest of the functions (f3 through f10)? Please note that my app. is using mysql database(if that helps).
Also maybe it's worth mentioning again that one idea that I already have is that I will need to create functions for each of my pages i.e, functions_index.php page for use in index.php page and likewise, create different function pages for the rest of the pages in my app. While at once this seems like a good idea, I may end up duplicating the same function(s) over and over and this can lead to heavy duplication. My sole aim is to keep the functions centrally accessible by all the pages, yet load the functions only on demand. Hope this is possible.
Thank you.
Note: Please note that all the code written is mainly done via functions and IS NOT OOPS based. So I would really appreciate any solutions that can be implemented without having to switch to using OOPS concepts. Thanks again.
If you switch to an OO design, you can create an autoload function (and register it with spl_autoload_register) to load classes on-demand.
Other than that, perform some profiling to see what the impact is of loading all your functions. Performance-wise, there might not be a significant impact relative to other aspects. There's a design-wise impact of having a monolithic file containing all the functions you may need, namely the danger of increased coupling. You decrease coupling by separating concerns.
first of all, load 5k lines of code is not that hard for php, but other than that, you should seriously think about splitting your single file into separate, easy to handle chunks and while you are at it you could even start coding in an oop way
There's no really clean way to get PHP to load certain functions in certain places without a tradeoff involving code duplication. For example, you could separate your functions into logical classes, and then load only the appropriate class for the appropriate section - but those classes can't overlap, or you'll end up duplicating code and defeat what you're trying to do in the first place (and there's certain stuff that will always overlap).
However, if you're concerned about loading the same 5000+ line file repeatedly all over the place, the real questions are:
1) Are you seeing actual degraded performance because of this? If not, why worry?
2) If you are, have you thought about using APC (Alternative PHP Cache)? That would cut out repeated parsing of that file, though it would still get executed each time.
Can you divide them into groups that make sense?
For instance:
Database Functions
File Management functions
= String functions
If so, it may work for you to do something like that and then include only the groups you want.
page 1:
include_once("functions/db.php");
include_once("functions/strings.php");
and page 2 could be:
include_once("functions/files.php");
include_once("functions/strings.php");
I did something similar like this once. I came up with a three-part solution, one or all of which might help.
First I separated out the functions I know I will always need and put them in a directory called core, with a function that automatically loads them all when the index is loaded.
Then I identified things I only need sometimes and separated them out by scope. So one particular group of tools within the app might need a particular group of functions which are not needed anywhere else, and they can all be loaded with that same function from above.
Then there are some big things that I will need in random places (Like mailer, oauth, key-value store, etc) and these have minimal wrapper functions within core which then load all the extra libraries that they need when the wrapper function is called.

Do you prefer functioning or including within one php file?

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.

Categories