PHP OOP and AJAX: how to handle servers in a class?

I am working on converting my standard PHP project to OOP, but I am facing a problem on how to handle AJAX calls with PHP classes. I am not happy with the way I am doing it now. I have a TillAjax.php file that I am calling from my TillUI.php file from an AJAX call.

In the TillAjax.php file I am doing this to get the information passed from the ajax call.

$till = new Till();
if(isset($_POST['data']))
    $till->doStuff($_POST['data']);

      

I think this destroys OOP.

I was working with ASP.NET MVC and here it was possible to trigger a specific action in the controller without having to check the post value. So I want to know if there is a smarter PHP way to solve this problem?

+2


source to share


2 answers


The method I'm using for this must have an Ajax class.

Your php file calls Ajax::Process($_GET['handle'])

where "handle" contains the name of the static class method, so maybe "Till :: Process". The Ajax class checks the function for a list of allowed functions (i.e. functions that you allow to be called via ajax) and then uses it call_user_func_array

to call the function (my code uses the contents of $ _POST as arguments to navigate to the function). The return of this function is automatically encoded as json and output to the client.

This means your target php file looks like this:

<?php

//File: ajax.php

include ("Ajax.php");

Ajax::Process($_GET['handle']);

?>

      



Which I find pretty simple.

Then you can have javascript like this (jquery):

$.get('ajax.php?handle=Till::Process', {}, function(result) {
  //called on page response
});

      

So then the result now contains any data returned from the php Till :: Process method.

+6


source


Have you considered using PHP MVC frameworks like CodeIgniter , CakePHP , Kohana , etc.? They will allow you to route requests to specific controller methods. It will be a much cleaner solution if you switch to one of these frameworks.



+1


source







All Articles