
So you’re writing a plugin that uses an object to maintain the state of your application, perhaps the object is used to construct a document, or a menu, or something else entirely, and your application requires multiple form submissions. How do you maintain the state of your object across submissions?
There are lots of ways to do this, use sessions, use hidden fields, recreate the object manually with each postback. Which method proves most obvious depends on your background, and experience. The most usual for PHP, is to use session variables to save the data
For the examples I’m going to create an object with four methods: getters and setters for the internal data, one to save the state and one to reload it again, exactly how and when these are called may differ depending on circumstances.
[php]
class myClass{
//the array the data will be stored in
var $collection = array();
function getVar($name){
if ( isset($this->collection[$name]) ) {
return $this->collection[$name];
}
}
function setVar($name = '', $value = ''){
$this->collection[$name] = $value;
}
function loadState(){
if ( isset( $_SESSION['myClass_state'] ) ) {
$data = $_SESSION['myClass_state'];
$this->collection = (!empty($data['collection'])) ? $data['collection'] : array();
//repeat for any other data maintained
}
}
function saveState(){
$data['collection'] = $this->collection;
//add any other internal data in the same way
$_SESSION['myClass_state'] = $data;
}
}
These methods can then be called after checking to see whether the form is actually being submitted.
[php]
$myClass = new myClass();
if ( isset( $_POST['submit'] ) ) {
$myClass->loadState();
//make any changes dictated by the information that has been posted
$myClass->setVar('post_title',$valueSubmitedInForm);
$myClass->saveState();
}
An interesting alternative to this, which I haven’t used in anger but have considered, is to use hidden forms to contain the same data. Instead of saving the information in a session variable the data is serialized, base64 encoded, and added as the value of a hidden field.
There are more security issues with doing things this way though so it is probably best avoided.