Ajax call file or files - php

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.

Related

is this the proper use of auto_prepend_file

Looking at building my first PHP application from the ground up. So pardon the noob question.
Is it proper to use auto_prepend_file to manage common variables like a default db connection or run session_start() or is there a more favorable way to define "application" variables and add session management to every page?
I'm asking because I came across a warning in netbeans when using a variable defined in an include. Searching google I saw a few posts stating that defining the variables in an include was bad practice; so what's the good practice in PHP?
Thanks
Most modern php application layouts do not have the required resources loaded in the code.
Instead most often there is an autloader that parses the requested resource (class name) and loads the correct file. Then most things are encapsulated in objects and classes.
The most common standard now is PSR-0
Configs are mostly stored in config files of various formats, like xml. Then there is often an object that is used to read those configs. From this object the configuration is then obtained to be used in certain places like database connections.
Also those things that get executed are mostly not executed in the code but rather execute themselves by attaching themselves to certain points in a program.
Most php frameworks have a thing called "hooks" or "events". Basically it's nothing else but a simple list with event names and for each entry a list of functions that should be executed.
When some part of the code "fires" it uses a helper class that walks through the entries of the list and executes those as well.
You ask yourself, can't you have loops there? The simple answer is, yes.
The whole idea behind all this stuff is that you have to change no existing code anywhere if you want to bring new code into your application.
Is that good practice? I honestly don't know.
If a project exceeds a certain size and multiple persons are programming on it, some standard may be necessary. And the way not to modify existing code has proven good in practice.
Regarding auto_prepend_file, that is something that I would not do.
I may do it if I have no other way. For example, if I want to execute some code that protects my application from ddos or security injections. And I just do not want to mess with the application itself.
But if I design something from the start, I would not do it.
Why? Maybe I want to switch to a new webserver, or even execute my program in the command line. Then I have a problem if I defined my auto prepending in apache...
Or maybe I have some code where I do not want that at all? Just one file within my application where I just do not want it because I do not need it and it takes up resources or is a security risk?
I often write an application where I have for example the database username and password directly in the function that establishes the link.
Why? Why not? Because I do not want to have it available on a global scale. If it's in the function code, its harder for other, possibly insecure code, to access it.
The very most common mean is to have a config file and just require it somewhere in your application.
Also most modern applications do not have different php files that get loaded by the webserver, so there is no need for having the same code at multiple places.
Instead most modern applications have a single php file (mostly index.php) that serves as a so called "bootstrap" file. The webserver rewrites every request instead of the requests to static resources like images to there, and everything else, like deciding what content to show when looking at the requested url, is handled in the application.

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 Directory structure in source code where to put AJAX code

I have accumulated a few AJAX scrips and they are a bit spread out within my directory structure.
Usually I just have the JavaScript call them and the scripts are named like "xyz_ajax.php"
I am trying to make things more organized. What is the best place to put these scripts within the source directory structure? And what is a decent naming convention? Or is my naming kind of ok?
Because this is a matter of taste, you can do it however you want. The way I have done it is create a single AJAX handler file, which is a front-facing web file that all AJAX requests are sent through. Based on the type of request, it will serve the right data. If you have many files, keep them in a single folder somewhere (with only ajax files, not with any include files) so you can keep that open for the public (as you need to in order for the browser to request/send information to and from these files).
It is really personal preference, but certainly being consistent is going to help you out in the long run. It does somewhat matter if you are using a template/bootstrap/MVC etc framework as they tend to have their own best practices. I'm not exactly sure in your case what you mean by "source directory" but if it's public-facing, you may want to consider any issues if they are hit directly either by accident or maliciously, and in that case you may want to use a handler file, as described by #SamT.
Personally, I use an underscore to indicate a page or view fragment, but that's just my own style. It's also nice it that it groups the fragments from the main views as well as making them easier for me to identify.

Why should MVC for websites require a single point of entry?

I see many MVC implementations for websites have a single-entry point such as an index.php file and then parses the URL to determine which controller to run. This seems rather odd to me because it involves having to rewrite the URL using Apache rewrites and with enough pages that single file will become bloated.
Why not instead just to have the individual pages be the controllers? What I mean is if you have a page on your site that lists all the registered members then the members.php page users navigate to will be the controller for the members. This php file will query the members model for the list of members from the database and pass it in to the members view.
I might be missing something because I have only recently discovered MVC but this one issue has been bugging me. Wouldn't this kind of design be preferable because instead of having one bloated entry-file that all pages unintuitively call the models and views for a specific page are contained, encapsulated, and called from its respective page?
From my experience, having a single-entry point has a couple of notorious advantages:
It eases centralized tasks such as resource loading (connecting to the db or to a memcache server, logging execution times, session handling, etc). If you want to add or remove a centralized task, you just have to change a singe file, which is the index.php.
Parsing the URL in PHP makes the "virtual URL" decoupled from the physical file layout on your webserver. That means that you can easily change your URL system (for example, for SEO purposes, or for site internationalization) without having to actually change the location of your scripts in the server.
However, sometimes having a singe-entry point can be a waste of server resouces. That applies obviously to static content, but also when you have a set of requests that have a very specific purpose and just need a very little set of your resorces (maybe they don't need DB access for instance). Then you should consider having more than one entry point. I have done that for the site I am working on. It has an entry point for all the "standard" dynamic contents and another one for the calls to the public API, which need much less resources and have a completely different URL system.
And a final note: if the site is well-implemented, your index.php doesn't have to become necessarily bloated :)
it is all about being DRY, if you have many php files handling requests you will have duplicated code. That just makes for a maintenance nightmare.
Have a look at the 'main' index page for CakePHP, https://github.com/cakephp/cakephp/blob/master/app/webroot/index.php
no matter how big the app gets, i have never needed to modify that. so how can it get bloated?
When deeplinking directly into the controllers when using an MVC framework it eliminates the possibility of implementing controller plugins or filters, depending on the framework you are using. Having a single point of entry standardizes the bootstrapping of the application and modules and executing previously mentioned plugins before a controller is accessed.
Also Zend Framework uses its own URL rewriting in the form of Routing. In the applications that use Zend Framework I work on have an .htaccess file of maybe 6 lines of rewriterules and conditions.
A single entry point certainly has its advantages, but you can get pretty much the same benefit from a central required file at the top of every single page that handles database connections, sessions, etc. It's not bloated, it conforms to DRY principles (except for that one require line), it seperates logic and presentation and if you change file locations, a simple search and replace will fix it.
I've used both and I can't say one is drastically better or worse for my purposes.
Software engineers are influencing the single point of entry paradigm. "Why not instead just to have the individual pages be the controllers?"
Individual pages are already Controllers, in a sense.
In PHP, there is going to be some boilerplate code that loads for every HTTP request: autoloader require statement (PSR-4), error handler code, sessions, and if you are wise, wrapping the core of your code in a try/catch with Throwable as the top exception to catch. By centralizing code, you only need to make changes in one place!
True, the centralized PHP will use at least one require statement (to load the autoloader code), but even if you have many require statements they will all be in one file, the index.php (not spread out over a galaxy of files on under the document root).
If you are writing code with security in mind, again, you may have certain encoding checks/sanitizing/validating that happens with every request. Using values in $_SERVER or filter_input_array()? Then you might as well centralize that.
The bottom line is this. The more you do on every page, the more you have a good reason to centralize that code.
Note, that this way of thinking leads one down the path of looking at your website as a web application. From the web application perspective, a single point of entry is justifiable because a problem solved once should only need to be modified in one place.

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.

Categories