Lots of if
's tend to signal the need for some classes. What are you using for the main routing that's being done by your app? In other words, when you point to domain.com/blog
, how does your app know where to go?
One way to do routing is to use a front controller. It parses the request and makes the appropriate calls. From there, you can create classes for each individual controller your app needs. For example, perhaps you have a blog
part of your site. Your front controller routes all requests that start with /blog
to the BlogController.php
class. This class has several methods: show
, create
, delete
, recent
, etc. And depending on the url request, the appropriate method is called.
At this point, adding ajax is easy & organized. Say you have implemented comments in PHP, so you have an addComment
method on your Blog
controller. To turn it into ajax, simply make your ajax request to /blog/comment/add
(or whatever route you're currently using to get here). The front controller will point it to the appropriate method in your Blog
controller, and now all you need to do is check if the request was ajax (look at the $_SERVER['HTTP_X_REQUESTED_WITH']
variable). If it was, return just the data you need (some success info).
To add new, ajax-only functionality, you can simply add more methods to your controller, and point your ajax request to the appropriate url. Essentially, you'll be using url's to handle your routing, instead of your if-else structure. And why not? That's what a web app is designed to do in the first place.
For more on this type of architecture, check out this really great article from Symfony2's documentation: http://symfony.com/doc/current/book/from_flat_php_to_symfony2.html.