PHP, jQuery and Ajax Object Orientation

2019-07-17 05:18发布

问题:

I'm a fairly experienced programmer getting my head around PHP and Ajax for the first time, and I'm having a bit of trouble figuring out how to incorporate object-oriented PHP into my ajax webapp.

I have an admin page (admin.php) that will load and write information (info.xml) from an XML file depending on the users selection of a form on the admin page. I have decided to use an object (ContentManager.php) to manage the loading and writing of the XML file to disk, i.e :

class ContentManager{

 var $xml_attribute_1
 ...

 function __construct(){
    //load the xml file from disk and save its contents into variables
    $xml_attribute = simplexml_load_file(/path/to/xml)
 }
 function get_xml_contents(){
    return xml_attribute;
 }
 function write_xml($contents_{
 }
 function print_xml(){
 }    
}

I create the ContentManager object in admin.php like so

<?php
include '../includes/CompetitionManager.php';
$cm = new CompetitionManager()
?>
<script>
  ...all my jquery
</script>
<html>
  ... all my form elements
</html>

So now I want to use AJAX to allow the user to retrieve information from the XML file via the ContentManger app using an interface (ajax_handler.php) like so

<?php
  if(_POST[]=="get_a"){

  }else if()
  }
  ...
 ?>

I understand how this would work if I wasn't using objects, i.e. the hander php file would do a certain action depending on a variable in the .post request, but with my setup, I can't see how I can get a reference to the ContentManager object I have created in admin.php in the ajax_handler.php file? Maybe my understanding of php object scope is flawed.

Anyway, if anyone can make sense of what I'm trying to do, I would appreciate some help!

回答1:

think of each ajax call as a separate request. if in the life cycle of a particular request you have not instantiated your ContentManager, the object doesn't exist. If you'd like to use a single object between multiple requests, serialize it to session and deserialize it early in the request life cycle.



回答2:

I dont know if this is what you need, well, here goes. Have a single PHP file to handle all the form submissions. For eg: proc.php or something like that in the ACTION="proc.php". Inside the proc.php, depending upon the parameters submitted, make function calls. One other thing you should likely do is to create an instance of the class (the object) at the end of the class file itself avoiding the need to check everytime if the object was instantiated or not. Use global $objectname before you make calls to the object functions, if necessary.