When I first learned AJAX, I was also teaching myself the languages of PHP, JavaScript, SQL, HTML, and CSS. I followed my coworkers existing web apps as examples of how to write my own web applications. Now that I have a better grasp on the languages and how they work, I have begun to question the existing script structure that my coworkers and I use. Basically, we have all of our calls to one PHP file, and send an event in the url.
It is structured something like this:
Url:wepappname_ajax.php?event=dosomething
PHP:
If ($event == dosomething) {
//do something
} elseif ($event == dosomethingelse) {
//do something else
}
Is a giant if statement really the route we should be taking? Should we section everything off into functions instead, or should we be making seperate PHP files for every different event?
1 Answer 1
I think in any language/framework/application it is good to try to have single responsibility of components, for your case it would mean to have each of the ajax "events" in separate files.
you could have files like:
/ajax/posts.php
/ajax/userInfo.php
...
each file could then require some core/common functionality from one location
it makes it much more readable/easier to maintain this way
you could also try using a framework that enforces this kind of structure.
hope this helps :)
-
Do you think these files should always be within separate files, no matter how related the events are? Say I have events "getUserInfo" and "updateUserInfo". Since both deal with user info, they are somewhat related, yet they still perform different tasks. Would you recommend placing both events within the hypothetical userInfo.php file or creating two seperate files named by their respective events?JCB– JCB2015年02月17日 17:04:41 +00:00Commented Feb 17, 2015 at 17:04
-
1I would go for different files inside /ajax, though you can agregate all datastore operations in one file like /data/user.php and include it from many placeskruczy– kruczy2015年02月18日 11:55:40 +00:00Commented Feb 18, 2015 at 11:55
-
1have to add that it is a preference of mine to have one file per endpoint, depending on your preference you might want to aggregate CRUD operations in one file, just go with whatever you think is easier to read/understandkruczy– kruczy2015年02月18日 12:03:09 +00:00Commented Feb 18, 2015 at 12:03