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.
Related
I'm a beginner but I've written my first little project and something about it doesn't really feel right. I hope I can describe the problem clearly.
My whole program is basically a pile of little functions that call each other, and then one or two lines of code that call the initial function to start off the 'chain reaction' and return the desired result.
It looks kind of like this (I'm using PHP):
$result = func_A($args);
function func_A($arg1, $arg2){
$localvar1 = blah blah;
$value = func_B($localvar1, $arg2);
return $value;
}
function func_B($arg1, $arg2){
$localvar1 = blah;
$value = func_C($localvar1, $arg2);
$return value;
}
function func_C($args){
blah blah blah
}
So when I try to go through my code, I'm hopping around all over the place between functions like crazy.
Is there a better way to do this? Should I just be creating local functions within my other functions? This just doesn't feel quite right.
Overall this is fine. We'd need to know more about specific goals and what the code is doing to get into more detail. In general, keeping the nuts and bolts in functions and calling them from a sort of main "command" center is a fine approach to procedural programming.
However, some general high level rules that work for me:
Don't repeat yourself. If you find you're doing the same things over
and over again, make a function of that. If you load a value from a
file, calculate something with it, and echo that, make a function for
it.
Don't overspecialize too far. Lots of 2 line functions probably
isn't a good thing.
If you can, be general. Don't make 5 different functions to connect
to 5 different databases. Make one function and pass the name of the
database to connect to it. See the rule about not repeating
yourself.
If you have one function that calls another that calls another, and
they are always used that way, consider making a single function of
them.
Objects are great for dealing with a set of values and doing things with them. For a quick script, not so much, but if you're going to do some substantial work like validating data, storing it, reading it in, making it into a single string, that's a good opportunity to make a class. Classes will conveniently fit into a file which you can then use in other projects as well, and if you do maintenance to this class often, the scripts that use it may not need to be changed at all if your initial design was solid.
There is nothing inherently wrong (and in fact a lot right) with this approach, if you're doing procedural programming (as it appears you are).
PHP does now support Objects (albeit in a fabulously ugly way, in my opinion) so, there may be an argument for modifying your code to be more OO. However, it makes sense to isolate various tasks into small individual functions that you can then edit.
I know this is somewhat controversial, but if you're just starting out in PHP, unless it's a core requirement of your client/employer, I would bypass it entirely and look into Node.js.
There's a great deal of benefit that you get from using one language on both sides of the client/server isle, rather than dividing tasks into two similar looking but different languages, which constantly share screen real-estate as you work on them, owing to how much of a hassle it is to keep the server and display portions of the code truly separate.
Of course PHP has become so entrenched that many people see it as a foregone conclusion. But (in my irrelevant opinion) all fandom aside, it has many shortcomings and is really ripe for retirement.
You can use references to avoid repetitions. Add your functions name to an array and when you need a solution you have a main function that loops through that array and call the function with $this->$function_name.
I have a module setup that uses ajax calls, should I have one file for all my ajax calls or should all the calls have their own file?
Example of what I mean:
index.php ------ With the ajax calls
Should I have one file such as 'ajax.php' that has functions for update, delete, and edit. Or should I have update.php, delete.php, and edit.php?
It all depends on the functions your application will need to complete.
If you will have several functions that edit, several functions that delete, and several functions that update, all functions having separate needs and requirements (thus cannot be made into a single universal function), then separate files for each function (edit_ajax.php, update_ajax.php, etcetera) would be easiest in the long run.
Or, are these Ajax calls only a few of the ones you'll need involving Ajax? In that case, it may be better to group them by their domain function, which is what they're handling (students_ajax.php if those Ajax calls involve updating, deleting and editing students, for example).
Also, make sure your function calls are separated by concern if your application architecture supports it. If these calls are purely sending data to PHP to update your database, keep them in a separate file from the Ajax calls that are merely passing parameters in for a specific set of HTML to load into a page.
Ultimately, your choice is heavily dependent on your application architecture and design style, which may sound more obvious than needed but very true nonetheless.
Depends on how you want to structure it. If you are looking to do page based permissions at any point, having multiple files may be beneficial. However, having all the actions in a single file will make your life a little easier when reading through the code.
You need to pick what is best for your design.
All these actions are db action, so i would just group them in one file. Unless your deleting, updating and editing is tedious, i would give one script the ability to perform all. Otherwise having a one file per action performed seems like going overboard. Generally speaking, you should write your scripts to by dynamic and reusable.
It'll be definitely more convenient for you to have just one entrance point to your program. Put all your operations in one file (like, in index.php) and use switch or whatever logic you want to fire appropriate action. Moreover, even if your have enough logic to separate in to different files or modules, one entrance point still will be nice design decision so you can, for example, perform consistent access control, logging, etc.
I usually use multiple files with one include file that they all use to get all their functions.
That way you get the convenience of a single library, but it's much cleaner and more straightforward having a different file for each.
I would suggest using folders to separate your different pages though. Otherwise your ajax folder gets all cluttered and that can be worse than your code file being cluttered.
I currently have a AJAX heavy(almost everything) intranet webapp for a business. It is highly modularized(components and modules ala Joomla), with plenty of folders and files. ~ 80-100 different viewing pages (each very unique in it's own sense) on last count and will likely to increase in the near future.
I based around the design around commands and screens, the client request a command and sends the required data and receives the data that is displayed via javascript on the screen.
That said, there are generally two types of files, a display files with html, javascript, and a little php for templating. And also a php backend file with a single switch statement with actions such as, save, update and delete and maybe other function. Several pages/screens may use the same php backend.
Recently, I have been adding an server sided undo function that requires me to reuse some code. So, I took the chance to try out OOP but I notice that some functions are so simple, that creating a class, retrieving all the data then update all the related rows on the database seems like overkill for a simple action as speed is quite critical. Also I noticed there is only one class in an entire file.
So, what if the entire php is a class. So, between creating a class and methods, and using global variables and functions. Which is faster?
Writing object oriented PHP will not affect your performance at all. If you use extensions like Zend Optimizer, it can even work faster.
So, there's really no reason not to use the much cleaner and more easily maintainable object oriented paradigm in PHP.
Writing purely procedural code may even lead to a performance drop since optimizations can be much harder and small details that eat up execution time are more likely to occur in such a messy environment.
The question is misguided. The problem is not one of speed, it's one of code organization. Using only global functions and variables, and lots of them, it'll get harder and harder to avoid naming conflicts and keep everything organized. Classes help you package and abstract things. Execution speed is a secondary concern, and in most cases won't increase noticeably, if at all. Development speed though can increase significantly over time, since you'll have to deal less with conflicts.
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.
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.