Passing complex objects via PHP - php

I've been researching a bit but I cannot find any way of doing this...
I need to pass an instance of a complex PHP class (formed by properties, functions, arrays, etc.) between different pages. The variable of the object is called $Model; I've been trying to use the GET method and "serialize" / "unserialize", but I cannot retrieve the object in the new page...
I'm trying to pass the object as follows:
echo 'Pass Model Object';
Then, I'm trying to retrieve it like this:
if(isset($_GET['modelobject'])) //$_GET when used in a link!
{
$ModelObjPost = unserialize($_GET['modelobject']); //$_GET when used in a link!
echo "POST: Model Object retrieved<br>";
var_dump($ModelObjPost);
}
There could be some kind of problem with certain characters in the serialization (I'm not sure, though), as the link that should send the object sometimes gets printed as (and it is also recognized as a URL):
r";s:3:"new";b:0;}i:2;(... MORE STUFF ...)s:9:"dbModelId";s:1:"1";}">Pass Model Object
Should I try a completely different approach, or this method should work, but there is just something I'm doing wrong?
Thanks in advance for your time!

Warning: I would discourage serializing a class and placing the result in an end-user readable location. This probably reveals far more about your application than you should be disclosing publicly.
Let's clear up some terminology right up front. I assume you know this, but just to be clear... A class is both the code that defines the behavior you want for an object and data (properties). An instance is when you use the new keyword on a class to create a usable object using that class definition.
By the very nature of how PHP works (typically), all instances are unloaded and deleted after a page loads. It cannot survive in memory to be used on a second page.
Typically you would create a file that contains the class definition you're trying to pass between pages, and create a new instance of the class on each page.
If you're trying to keep state between pages, you should look at using sessions. If you choose to use sessions, and want to keep an instance of your class inside your session, keep in mind what I said above - it will be deleted and recreated between the pages. You will need to make sure your class is set up to reload everything it needs to operate. PHP provides for a "magic" method to do this: __wakeup() in this method, you will need to restore the object back to the same state it was in on the previous page load.
Other ways to pass data between pages (or page loads) would be arrays for HTTP GET or POST.
$data = array( 1,2,3,4, 'a' => 'abcd' );
$query = http_build_query(array('aParam' => $data));
$url = 'somepage.php?data=' . $query;
Forms may be created to pass arrays of data by utilizing array notation in the form field names
<form action="somepage.php" method="post">
<input name="option[a][]" value="option a,0">
<input name="option[a][]" value="option a,1">
<input name="option[b][]" value="option b,0" />
<input name="option[b][]" value="option b,1" />
<input name="option[]" value="option 0" />
</form>
Access this data like this:
<?php
echo $option['a'][0];
echo $option['a'][1];
echo $option['b'][0];
// etc

Your two best options in this case would be to either:
Use a $_SESSION variable. You could save the object as $_SESSION['Model'] and access that on each page that you need to use it. Be sure to call session_start(); on each of those pages to resume the session.
Use urlencode(serialize($Model)) in the URL and use urldecode() on the next page to make sure that you don't have encoding issues in the URL. json_encode() and json_decode() would also be a good option for object to string serialization.

Related

Maintain php object state

My php code creates a "School" object which is (among other functions) able to return several forms which are being ,on submit, handled by php.
Thru one of these forms i'm able to add a "SchoolClass" object to a array in the "School" object but it seems that the "School" object is recreated at some point after i add the "SchoolClass" object. This re-creation makes the array of "SchoolClass" disappear.
The functions that returns the forms are static, but the functions where "SchoolClass" objects are added to the array are not static; ("School::ShowStudentForm() and School->RegisterSchoolClass($class)")
Both the class definition and the php-script which handles the form after submit is in the same file(index.php). I had the idea that keeping both the class code and the form handling code in the same file would do the trick, but it did not make a change.
Question 1: how do i maintain the "School" object for as long as i need it?
Question 2: is it ok to create a class with only static methods and write the data directly to a file or database to avoid the whole problem or just skip the whole object approach and just use "normal" functions?
Yes, this problem is probably encounterd before and therefore also answered before but i have not been able to find a answer which i understand.
OK....i figured it out.
I can use the $_SESSION variable to store it.
Now i do like this in the start of the page:
$school = null;
if(!isset($_SESSION["school"]))
{
$school = new School;
$_SESSION["school"] = $school;
echo "New school <br>";
} else {
$school = $_SESSION["school"];
}

Is $_GET available in all created classes?

I do one request and my URL has a parameter like this .../index.php?customer=abc
In index.php's class $_GET['customer'] is available.
There are multiple other classes being created then.
Finally in somefile.php containing some different class someClass, $_GET['customer'] is no more available.
I am forced to use a framework that uses a form that eval()s PHP code on button click.
new TDynButton($body, "login", ... , "\$this->win->doLogin();");
IndoLogin() there is no $_GET['customer']. Cannot understand why. Is it possible if this framework uses action=GET in the background that I am losing my $_GET? Im totally lost.
Thanks.
My approach would be to give the information in $_GET['customer'] to the instatiated object by passing it in the constructor and store it in a private member. This way you have the information needed and no direct access to $_GET is nessessary. This is anyway a better design I think.
$_GET is a global variable that will be available throughout the script you use it in. You have to pass it to the script, though - such as somefile.php?customer=peter
Yes, $_GET is a superglobal variable that is available in all PHP scripts.
And yes, generally, framework convert/sanitaze the GET/POST arrays and clears them.

returning values from function or method multiple times by only calling the class once

I have a members.php file that shows my websites members. I echo members name by using foreach method. A method of Members class returns an array, then I use foreach loop in the members.php file to echo the members. I am trying to aovid writing as less php code as possible in my members.php file where my html files are located. Is there a way to avoid using foreach inside members.php file?
For example, is it possible to return value from a method couple of times? (by only calling the object once). Just like how we normally call the functions? This question doesn't make sense, but I am just trying to see if there is a away around this issue?
You could write an intermediate function that caches whatever the Members-method returns and return just one index from the cache, specified by a parameter. But then you are back to using a some kind of loop.
There's nothing wrong with a loop in your view. After all, PHP is a templating language.
However, you could write an object method to return/print a formatted members list.

CodeIgniter, Accessing class property after page reloads, is it possible?

I have a CI page that will load to a div in view file, using jQuery. Using switch(page_parameter), I control what is showing from the page.
When I call the page for 3rd time, I set a value to the class array.
But when I call the 4th time, the array become empty.
I was wondering, is it actually possible to use the class property to store value that can be used after page re-access? Or something missing in my head?
I know that using session is not a good idea, since the real array is a big chunk of serialized xml.
Here's my code:
class MyClass extends MY_Controller
{
public static $pitems = array();
function Hotel(){
parent::MY_Controller();
}
function new_campaign(){
$params = $this->uri->uri_to_assoc();
switch($params['step']){
case '3' : self::$pitems = array("test","another"); //here the class array was set successfully
$this->load->view('viewer');
break;
case '4' : print_r(self::$pitems); //here the array is empty
break;
}
}
In the viewer page, there's a call to the page:
Next page
Same issue also with $this->
What am i missing here?
Thanks in advance~
edit:
I saw a script that has similar scenario. it successfully reused the variable set in the constructor, instead of treating it as a class variable. i'll look thorough to confirm this, but for now, i'll close this thread. Thanks Chris for sharing.
Im not really sure what your trying to do but I have users jQuery post()/get()/ajax() many of times in CI and have had no problems. So despite not knowing or understanding what your trying to do. I thought I'd at least say I know loading data without refresh in CI through something like jQuery isn't an issue. Example on system I built on CI had a twitter like feed of tweets where jQuery on a timer was polling for new data and coming back with it each time accordingly if something new was to be shown.

Using objects in Ajax calls PHP files

I have instantiated a class in my index.php file. But then I use jQuery Ajax to call some PHP files, but they can't use my object that I created in the index.php file.
How can I make it work? Because I donĀ“t want to create new objects, because the one I created holds all the property values I want to use.
Use the session to save the object for the next page load.
// Create a new object
$object = new stdClass();
$object->value = 'something';
$object->other_value = 'something else';
// Start the session
session_start();
// Save the object in the user's session
$_SESSION['object'] = $object;
Then in the next page that loads from AJAX
// Start the session saved from last time
session_start();
// Get the object out
$object = $_SESSION['object'];
// Prints "something"
print $object->value;
By using the PHP sessions you can save data across many pages for a certain user. For example, maybe each user has a shopping cart object that contains a list of items they want to buy. Since you are storing that data in THAT USERS session only - each user can have their own shopping cart object that is saved on each page!
Another option if you dont want to use sessions is to serialize your object and send it through a $_POST value in your AJAX call. Not the most elegant way to do it, but a good alternative if you don't want to use sessions.
See Object Serialization in the documentation for more informations.
mm, you should store in session, $_SESSION["someobj"] = $myobj;, and ensure that when you call the Ajax PHP file this includes the class necessary files which defines the class of $myobj and any contained object in it.
Could you be more specific? I can try.
This is how I create an object then assign it to a session variable:
include(whateverfilethathastheclassorincludeit.php)
$theObject = new TheObjectClass();
//do something with the object or not
$_SESSION['myobject'] = $theObject;
This is how I access the object's members in my Ajax call PHP file:
include(whateverfilethathastheclassorincludeit.php)
$theObject = $_SESSION['myobject'];
//do something with the object
If you don't want to move your object that is in your index.php, have your ajax make a request to index.php but add some extra parameters (post/get) that let your index.php know to process it as an ajax request and not return your normal web page html output.
You have not provided code, but what I guess is that you need to make your instantiated object global for other scripts to see it, example:
$myobject = new myobject();
Now I want to use this object elsewhere, probably under some function or class, or any place where it is not getting recognized, so I will make this global with the global keyword and it will be available there as well:
global $myobject;
Once you have the object, you can put it into the session and then utilize it in the Ajax script file.
As others have suggested, $_SESSION is the standard way to do it, in fact, that was one of the reasons, that sessions where invented to solve. Other options, i.e. serializing the object rely on the client side to hold the object and then return it untampered. Depending on the data in the object, it is not a good solution, as a) the object may include information that should not be available on the client side for security reasons and b) you will have to verify the object after receiving it.
That said, and if you still want to use the object on the client side, then JSON is an option for serializing object data, see JSON functions in PHP.
Based on most of the answers here, referring to storing the object in $_SESSION, is it more efficient to store only the individual properties that need to be accessed in AJAX as opposed to the whole object, or does it not matter?
E.g.
$_SESSION['object'] = $object;
vs
$_SESSION['property1'] = $object->property1;
$_SESSION['property2'] = $object->property2;
I know the OP is asking about accessing the entire object, but I guess my question pertains to if it's just a matter of only accessing certain properties of an object, and not needing to access methods of a class to alter the object once it's in AJAX.

Categories