Jump to content

[SOLVED] Using Data transfer objects between script & HTML


matrixbegins

Recommended Posts

Hello Everybody!

 

Can I use data transfer objects like JAVA BEANS of java in PHP. I'll illustrate my problem with my example.


 

Here are Few Files that I use in my application:

 

1. DataHandler.php            // a simple class that connects to database , closes connection, executes

                                    //insert/select/update/ delete queries.

2. UserInfo.php              // a simple class that have some Getters/ setters methods for accessing a user's attributes.

 

3. ShowUserInfo.php      // A simple file that authenticate & obtain data of a particular user.

 

4.MyHome.php              // A simple view / HTML to show data.

 

Now whenever a user logged in Showuser.php fetchs data and obtain an object of UserInfo Class, which have some attributes like username, phptoUrl, type(paid/free), Age etc.

 

Now How ShowUserInfo.php  must pass this object to MyHome.php so that it can used as a proper object there.

In order to solve this I passed the object as a session variable as I have to use this object on some other pages too. But on reteriving Values e.g.  obj->getUsername(); Php shows an error stating non_object method call or some thing like that.

 

Please Help. Please tell me also that am I following a good practice or not. as I am new to PHP so I can't get into MVC framework yet. I well be very Obeliged if u could suggest a proper practice to use OOP.

______________________________________________

With Warm Regards

Ankur

Link to comment
Share on other sites

session_start() is the function that allows you to KEEP the $_SESSION superglobal across your scripts. HTTP is a stateless protocol, that's why variables don't preserve themselves between pages. So, for the server to maintain the $_SESSION array across all the pages you have to engage session functionality with session_start().

 

Simply include it on top of ALL your pages that will use the session functionality, but remember that you MUST call the function BEFORE anything is sent to the web browser, i.e. before any print() or echo.

 

I don't think that including the files before session_start() makes a difference, but I can be wrong and can't hurt to try.

 

Example:

 

On page1.php

<?php
//Incude necessary stuff

session_start();

$clown = new FunnyObject();
$clown->makeMeLaugh();

//Store it
$_SESSION['clown'] = $clown;

//Link to page2.php here
?>

 

On page2.php

<?php
//Incude necessary stuff

session_start();

//Retrieve it
$clown = $_SESSION['clown']

//Use it!
$clown->makeMeLaughAgain();
?>

 

This will NOT work:

<?php
echo 'This is my webpage!';

session_start() // <- You cant initialize it here since you already echo'ed something on screen.
?>

 

And finally, if you don't want to use sessions, take a look at object serialization, which is the default procedure that session functionality uses to pass objects between pages.

 

Hope this helps,.

Cheers.

Link to comment
Share on other sites

Dear Mr. Mattcooper !

 

Here is some code. first I want u must take a look at directory structure. I just tried to MIMIC MVC Architecture but I'm not using any framework.

Application
           |__app_code
           |              |__Model
           |               |          |__HandleData.php
           |               |          |__LookupXml.php
           |               |          |__userInfo.php
           |               |          |__VabData.php.
           |               |
           |               |__Controller
           |                           |_chnginfo.php
           |                           |_getInfo.php
           |                           |_vabLogin.php
           |                
           |__ pages
                   |_ myHome.php

DatasourceConfig.XML
index.php

 

Ok now when a user logs in from Index.php it is authenticated and redirected to myHome.php

 

Here is code for userInfo.php

<?php
require_once("HandleData.php");

class userInfo{
private $email,$name,$sex,$dob,$country,$photourl,$skills;

/*Email*/
public function getEmail(){
	return $this->email;
}
public function setEmail($email){
	$this->email=$email;
}
/*Name*/
public function getName(){
	return $this->name;
}
public function setName($name){
	$this->name=$name;
}
/*Sex*/
public function getSex(){
	return $this->sex;
}
public function setSex($sex){
	$this->sex=$sex;
}
/*DOB*/
public function getDob(){
	return $this->dob;
}
public function setDob($dob){
	$this->dob=$dob;
}
/*Country*/
public function getCountry(){
	return $this->country;
}
public function setCountry($country){
	$this->country=$country;
}
/*Photourl*/
public function getPhoto(){
	return $this->photourl;
}
public function setPhoto($photourl){
	$this->photourl=$photourl;
}
/*Skills*/
public function getSkills(){
	return $this->skills;
}
public function setSkills($skills){
	$this->skills=$skills;
}

/*userInfo*/
public function getInfo($str){
	$user=new userInfo();
	$data=new HandleData();

	$arr=$data->select($str);

	if($arr){
		$user->setEmail($arr['email']);
		$user->setName($arr['name']);
		$user->setSex($arr['sex']);
		$user->setDob($arr['dob']);
		$user->setCountry($arr['country']);
		$user->setPhoto($arr['photourl']);
		$user->setSkills($arr['skills']);

	}
	else{
		$user->setEmail(NULL);
		$user->setName(NULL);
		$user->setSex(NULL);
		$user->setDob(NULL);
		$user->setCountry(NULL);
		$user->setPhoto(NULL);
		$user->setSkills(NULL);
	}

	return $user;
}
}

 

Here is code for function HandleData->select($str)

 

<?php
include_once("VabData.php");   // [b]this is a class i have written a single function[/b]
public function select($str){
          	$stmt=VabData::getConnection()->prepare($str);
          		$stmt->execute();
          		return($stmt->fetch(PDO::FETCH_ASSOC));
             
         }
?>

 

Here is code for VabData::getconnection();

<?php
include_once("LookXml.php");

class VabData{         
               
             private static $conn = null;
            
// function to read XML file  & get a connection
  public static function getConnection(){
            $lookup=new LookXml();
            $constr=$lookup->getConnectionString();
            $user=$lookup->getUser();
            $pass=$lookup->getPassword();
            
                if(!self::$conn){
                   try{
                        self::$conn=new PDO($constr,$user,$pass);
                        self::$conn->setAttribute(PDO::ATTR_ERRMODE,
                                        PDO::ERRMODE_EXCEPTION);
                         
                     }
                   catch(PDOException $ex){
                      echo "Error<br>";
                        echo"Sorry, an error has occurred. Please
                      try your request later\n" . $ex->getMessage();
                      }                    
                }
                return self::$conn;
         }
}
?>

 

Now Take a look at getInfo.php

<?php
session_start();
include_once($_SERVER['DOCUMENT_ROOT']."vab/app_code/Model/userInfo.php");
require_once("appFunctions.php");

$email=$_SESSION['uid'];
$query="SELECT * FROM userinfo WHERE email='{$email}'";
[b]$info=new userInfo();[/b]
$info=$info->getInfo($query);
if($info->getEmail()==$email)
	{

		$_SESSION['email']=$info->getEmail();
		$_SESSION['name']=$info->getName();
		$_SESSION['sex']=$info->getSex();
		$_SESSION['dob']=$info->getDob();
		$_SESSION['country']=$info->getCountry();
		$_SESSION['skills']=$info->getSkills();
	[b][/b]	redirect_to("../../pages/profile.php");
	}
else{
	$_SESSION['msg']="Error Loading Information from the Database";
	redirect_to("../../pages/freeHome.php");
}
?>

 

Rather Than doing so setting Too many session variables I tried to set The object of userInfo i.e. $info as

$_SESSION["thisuser"]=$info;

 

On the Html Page i.e. myHome.php

I tried this

<?php
session_start();
include_once($_SERVER['DOCUMENT_ROOT']."vab/app_code/Model/userInfo.php");
$user=new userInfo();
$user=$_SESSION["thisuser"];
echo "Hello "
echo $user->getEmail();
?>

It generates an error

 

Now I think I have given almost all info.  forgive me and ask for info that u want.  Please Keep in mind this a beginner appraoch.

 

Please State  also that am I following a good practice. Please point out some pitfalls & drawbacks in my application design.

 

________________________________________________________________________________

With Warm Regards

ANKUR

 

 

Link to comment
Share on other sites

Be aware that you are overwritting variables all over the place.

 

For example, in getInfo.php you are doing this: (I assume that the [ b] tags are not part of your code).

 

<?php

$info=new userInfo(); // $info is now an instance of the userInfo class
$info=$info->getInfo($query); // info now contains the return value from the getInfo(); method, it is no longer an instance of the userInfo class.
if($info->getEmail()==$email) // info->getEmail DOES NOT EXIST since $info is not an object.

?>

 

Again in myHome.php

<?php

$user=new userInfo(); // $user is a new instance of the userInfo clas
$user=$_SESSION["thisuser"]; // $user is now overwritten with the session variable.

?>

 

That's probably why you get an error, you replaced the object with some random data.

Link to comment
Share on other sites

Thanks Mr.

 

Well this was the that we can implement in Java.

 

So how can Pass one object from one layer to another.

<?php
Line1 ::: $info=$info->getInfo($query);
line 2 :::  if($info->getEmail()==$email)
Line 3 :::$user=$_SESSION["thisuser"];
?>

in Line 1 getInfo($query) is function of class userInfo and returning an object of userInfo. So I think no problem with Line 1

if line1 is valid Line 2 will also execute as value of  $email is retreived from a session variable which is used to keep track of user Authentication.

 

For Line 3, I am fully aggreed to your view that objest is overwritten by Session variable.  So if it is not working then There must be a way to Type cast a session varible into a desired datatype/ object.

 

Can u suggest me something on thisconcept.

Link to comment
Share on other sites

Here Is a simple Example That I used for demo.

 

I used 5 files.

 

1.ClassDemo.php

2. script.php

3. pageHtml.php

4.Second.php

5. appfunctions.php

 

ClassDemo.php

<?php

class ClassDemo{

private $user, $type;

public function getUser(){
	return $this->user;
}

public function setUser($user){
	$this->user=$user;
}


public function getType(){
	return $this->type;
}

public function setType($type){
	$this->type=$type;
}
}
?>

 

Now scripts.php

<?php
session_start();

include_once("ClassDemo.php");
include_once("appFunctions.php");
$user=$_POST["user"];
$type=$POST["type"];
$obj= new ClassDemo();
$obj->setUser($user);
$obj->setType($type);

$_SESSION["UserObj"]=$obj;

redirect_to("Second.php");

?>

 

Now pageHtml.php

<HTML>

<BODY>
<form  name="form1" method="post" action="script.php">

  <label>Email
  <input name="user" type="text" id="email" />
  </label>
  <p>
    <label>Password
    <input name="type" type="text" id="pwd" />
    </label>
  </p>
  <p>
    <label>
    <input type="submit" name="Submit" value="Login" />
    </label>
  </p>
</form>
</BODY>
</HTML>

 

Second.html

<?php
session_start();
include_once("ClassDemo.php");
$user=new ClassDemo();
$user=$_SESSION["userObj"];

echo $user->getUser();
echo"<br>";
echo $user->getType();
?>

 

 

Now appFunctions.php

 

<?php
function redirect_to( $location = NULL ) {
	if ($location != NULL) {
		header("Location: {$location}");
		exit;
	}
}
?>

Finally when I run this whole assembly I encountered with this error !!

 

Fatal error: Call to a member function getUser() on a non-object in C:\wamp\www\demoapp\second.php on line 7.

 

Now I think this simple to understand.

 

One more thing

First I write second.php as

<?php
session_start();
$user=$_SESSION["userObj"];

echo $user->getUser();
echo"<br>";
echo $user->getType();
?>

 

But I got Same error !!

 

Please Help me out

Link to comment
Share on other sites

As rhodesa stated, your class has to be included before session_start(), the session handler has to know the class definition before it can recreate it.

 

second.php

<?php
include_once("ClassDemo.php"); // Include before session_start

session_start();

$user=new ClassDemo(); // This line is not needed.

$user=$_SESSION["userObj"];

echo $user->getUser();
echo"<br>";
echo $user->getType();
?>

Link to comment
Share on other sites

Thanks Mr. Aeglos

 

But I regret to say that its not working. whether  $user=new ClassDemo(); is included or not.

 

Some problem in system or something else.

 

I have figured out another way  If we can convert an object to equivalent array. i.e. an array indexed by class' attributes

 

arr{ ['name']="XYZ" ,

      ['Type']= "Paid" }

 

Or something liike that.

Can u give some Idea about this concept

 

Link to comment
Share on other sites

 

But I regret to say that its not working. whether  $user=new ClassDemo(); is included or not.

 

 

The point is that the line you indicated right there does not matter at all. The key is having the class file included BEFORE the session. If it does not work for you then something else must be wrong. I just tested this with 3 files I made from scratch and worked perfectly. Try this ultra simple example, SHOULD work...

 

 

class.php

<?php
class Something{    
    private $foobar;
    
    public function getFoobar(){
        return $this->foobar;
    }
    
    public function setFoobar($foobar){
        $this->foobar = $foobar;
    }
}
?>

 

first.php

<?php
session_start();

include_once('class.php');

$text = 'It Verks!';
$fb = new Something();
$fb->setFoobar($text);
$_SESSION['fb'] = $fb;
echo '<a href="second.php">Click!</a>';
?>

 

second.php

<?php
include_once('class.php');

session_start();

$fb = $_SESSION['fb'];
echo $fb->getFoobar();
?>

 

I just ran this and worked.

 

As for passing the variables directly as an array, it's no problem. The $_SESSION array is simply a place intended to store user-specific persistent data (although we end up throwing all kinds of data in there). There is no problem in doing something like $_SESSION['userDataArray'] = $user->getData(); or similar. In fact, it might even be a good practice to do so.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.