Jump to content

Passing $_POST to Object


TomTees

Recommended Posts

I'm practicing my OOP skills and want to pass $_POST values to an Object's Instance Variables when a form is submitted.

 

This is what I have so far...

 

index.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
</head>
<body>
	<!-- Registration Form -->
	<form method="post" action="results.php">
		<!-- Registration Fields -->
		<div>
			<label for="email">E-mail:</label>
			<input type="text" name="email" class="txt" id="email" />
		</div>
		<div>
			<label for="password">Password:</label>
			<input type="password" name="password" class="txt" id="password" />
		</div>
		<div>
			<input type="submit" name="btnSubmit" value="Register" class="btn" id="btnSubmit" />
		</div>
	</form>
</body>
</html>

 

 

results.php

<?php
include ('classes/FormHandler.class.php');
?>

 

 

FormHandler.class.php

<?php
class HandleForm {
	// Define Variables.
	private $email;
	private $password;

	public function __construct($email, $password){
		$this->email = $email;
		$this->password = $password;
	}
}
?>

 

 

I'm a little stuck on how I initialize the Instance Variables in the Constructor?!

 

 

 

TomTees

 

 

Link to comment
Share on other sites

In results.php you can do something like this:

 

<?php
   include ('classes/FormHandler.class.php');
   $formHandler = new HandleForm($_POST['email'], $_POST['password']);
?>

 

$formHandler is now an instance of the HandleForm class and the email/password from post have been passed to its constructor and subsequently saved by the code you already have there.

 

EDIT: Misread your class name, corrected

Link to comment
Share on other sites

In results.php you can do something like this:

 

<?php
   include ('classes/FormHandler.class.php');
   $formHandler = new HandleForm($_POST['email'], $_POST['password']);
?>

 

$formHandler is now an instance of the HandleForm class and the email/password from post have been passed to its constructor and subsequently saved by the code you already have there.

 

That simple, huh?!

 

 

EDIT: Misread your class name, corrected

 

Actually I'm the one that had things mixed up!

 

 

So, some follow-up questions...

1.) If this was a real app, how would I protect the password?

 

2.) How do I "return" both the email and password from the object (e.g. I want to echo them)?

 

3.) Can I use different names for the parameters in my constructor or must they match the Instance Variables?

	public function __construct($email, $password){
		$this->email = $email;
		$this->password = $password;
	}

 

4.) If I pass this object to another object will I then be able to access the email and password?

 

 

 

TomTees

 

 

Link to comment
Share on other sites

1) Do you mean when you store it? Hash it. See md5()

If this is a live site, that will potentially have quite a bit of traffic, I would strongly suggest that you ditch md5() as it has been proven vulnerable, and change to the hash() and use the 'SHA512' algorithm, but firstly check what algorithms you have available by using hash_algos this works in the same way as phpinfo() - ie no paramters needed, it just gives an array of algorithms available..

 

Hope that makes sense to you anyway..

 

Rw

Link to comment
Share on other sites

2.) How do I "return" both the email and password from the object (e.g. I want to echo them)?

 

 

I'd like to expand on this a little bit. You already have a good starting point for your class, but to retrieve the information from it the most standard OOP way of doing it is using getters and setters. Some languages (particularly C#) have specific language constructs that allow this but in PHP we just make methods to do the same. Typically the information itself is stored inside private variables like you're already using in your class. This means that you cannot access them directly from outside the class, so this is where getters and setters come in. As an example, here's an example modification to your class:

 

 

   class HandleForm {      // Define Variables.      private $email;      private $password;      public function GetEmail()      {         // Simply return the $email field         return $this->email;      }      public function SetEmail($newValue)      {          if(IsValidEmail($newValue)) // IsValidEmail is a made up function but it shows that you can do value checking in your setter to make sure nothing invalid gets passed             $this->email = $newValue;          else             ShowError('Invalid Email!'); // Another made up function      }      public function __construct($email, $password){         $this->email = $email;         $this->password = $password;   }}

 

 

As you see there you can have a great deal of control over what goes into and out of your class. If you, for example, wanted to make the $email field read only (to the world outside your class of course, you can still access it internally with $this->email), you could remove the SetEmail() function. That's just for example purposes only, you probably wouldn't have a need to actually do that.

 

So with the above code in mind, to actually echo the values, you could do something like this in your results.php or wherever else:

 

<?php   include ('classes/FormHandler.class.php');   $formHandler = new HandleForm($_POST['email'], $_POST['password']);   echo $formHandler->GetEmail(); // Displays the class's $email field?>

 

 

 

 

(worth noting is that PHP has "magic methods" for getting and setting I believe but I've never really used them and as I understand they don't allow as much control)

Link to comment
Share on other sites

I notice your class is called 'FormHandler', but the design of the class is specific to a certain form. One of the benefits of OOP is reusable code, your class design kind of defeats that benefit due to the field specific functions and contructor arguments, because you'll have to make a new form handler class when you need another form like a contact us form.

 

I would create the form handler class to be very generic and not specific to a certain form, so that it can be used on almost any form. If I needed the class to do something that is very specific to a certain form then I would extend the FormHandler base class and add the method or functionality needed. This way I would be taking advantage of another benefit of OOP which is inheritance.

Link to comment
Share on other sites

I'd like to expand on this a little bit. You already have a good starting point for your class, but to retrieve the information from it the most standard OOP way of doing it is using getters and setters.

 

Except using Getters/Setters is a bad idea.  http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

 

That is what I'm trying to learn now.  How to create and pass objects to other objects.  (I believe that is the "proper" OOP way to do things?!)

 

 

 

TomTees

 

Link to comment
Share on other sites

I notice your class is called 'FormHandler', but the design of the class is specific to a certain form. One of the benefits of OOP is reusable code, your class design kind of defeats that benefit due to the field specific functions and contructor arguments, because you'll have to make a new form handler class when you need another form like a contact us form.

 

I would create the form handler class to be very generic and not specific to a certain form, so that it can be used on almost any form. If I needed the class to do something that is very specific to a certain form then I would extend the FormHandler base class and add the method or functionality needed. This way I would be taking advantage of another benefit of OOP which is inheritance.

 

If I were to assign the $_POST array to another internal array in my object would that be more multi-functional?

 

 

 

TomTees

 

 

Link to comment
Share on other sites

 

If I were to assign the $_POST array to another internal array in my object would that be more multi-functional?

 

TomTees

 

Absolutely, you have two options there, you could add code to your constructor to grab the $_POST and store in a property, or you could create a public method that accepts an array of data as its argument. I would prefer the last option as this would again further improve the reusability of your class.

Link to comment
Share on other sites

Absolutely, you have two options there, you could add code to your constructor to grab the $_POST and store in a property, or you could create a public method that accepts an array of data as its argument. I would prefer the last option as this would again further improve the reusability of your class.

 

How would I assign the $_POST array to an internal array in my Constructor?

 

Why don't you like doing it in the Constructor?

 

 

 

TomTees

 

P.S.  What is wrong with PHPFreaks the last few weeks?  The website keeps showing errors when I access it?!

 

 

 

Link to comment
Share on other sites

I'd do it something like this

<?php

class FormHandler
{

    private $_data = array();

    public function __construct($input = false)
    {
          if(is_array($input))
         {
              $this->_data = $input
         }
    }

    public function addData($input)
    {
          $this->_data = $input; // could do some checking here for unwanted data, and check $input is_array etc
          // or instead of overriting the private array, you could just append to it
     }

}


//usage

$form = new FormHandler();

$form->addData($_POST); // could pass any array in here, doesn't havent to be $_POST or $_GET etc

//or

$form = new FormHandler($_POST);
?>

 

The advantage of this way is you're not restricted to retrieving input from the $_POST, you could use the $_GET or build your own array if needed.

 

In that example the input data could be passed in into the constructor, or by using the public method. IMO that just gives you a bit more flexibility as you might not always want to declare the input when you create the instance of the class.

Link to comment
Share on other sites

>  private $_data = array();

 

Why do you use the format $_data ??

 

It's a style thing.  A lot of coders prepend an underscore to private members to denote that they are private.  It improves readability, but has no functional meaning.

 

 

>    public function __construct($input = false)

 

Can this be "private"?

 

 

TomTees

 

 

 

Yes.

Link to comment
Share on other sites

BTW, is it...

 

class FormHandler3 {

 

or

 

class FormHandler3{

 

or doesn't the extra space matter?

 

What about on functions?

 

 

TomTees

 

 

 

Doesn't matter in either case.

 

EDIT: In JavaScript, brace position does matter.  It's always best to keep the opening brace of a function on the same line as its name and argument list in JavaScript.

Link to comment
Share on other sites

How would I assign the $_POST array to an internal array in my Constructor?

 

 

From my somewhat limited knowledge, the answer to your question lies in what your asking $_POST is a super global, and because of that, so long as it is set/has state, you can access this array from anywhere within the scope of your project.

 

>>private function __construct(){

 

This has a lot of benefits really, I only like to call things public when I have to, though I do steer clear of protected; be aware though as these instructions are php5> and are NOT compatible with anything less, so make sure you know that you can migrate servers without needing to worry about compatibility issues, I tend to write with php4 in mind, but when expressly asked for php5, I go wild!!!

 

Rw

Link to comment
Share on other sites

>>private function __construct(){

 

This has a lot of benefits really, I only like to call things public when I have to, though I do steer clear of protected;

 

Making the __construct private means you won't be able to instantiate the class into an object.

Link to comment
Share on other sites

Making the __construct private means you won't be able to instantiate the class into an object.

 

If it is left "Public", can anyone tamper with it?

 

 

TomTees

 

 

It can be executed (and will instantiate the object), and it can also be overridden.

Link to comment
Share on other sites

Making the __construct private means you won't be able to instantiate the class into an object.

 

If it is left "Public", can anyone tamper with it?

 

 

TomTees

 

 

It can be executed (and will instantiate the object), and it can also be overridden.

 

So you just have to live with it being "public" and hope your constructor doesn't get hacked, huh?  :-\

 

 

 

TomTees

 

 

Link to comment
Share on other sites

Making the __construct private means you won't be able to instantiate the class into an object.

 

If it is left "Public", can anyone tamper with it?

 

 

TomTees

 

 

It can be executed (and will instantiate the object), and it can also be overridden.

 

So you just have to live with it being "public" and hope your constructor doesn't get hacked, huh?  :-\

 

 

 

TomTees

 

 

 

How would it get hacked?

Link to comment
Share on other sites

How would it get hacked?

 

Maybe too strong of a term, but it could be enacted by another developer when it shouldn't be.

 

From what was described before, you could call the __Constructor repeatedly even if you hadn't instantiated yet.  (Maybe I misunderstood?!)

 

Someone earlier said you could make it "private" but I guess that isn't so.

 

I'm just averse to "public" anything if it doesn't need to be set as such!  :shy:

 

 

TomTees

 

Link to comment
Share on other sites

How would it get hacked?

From what was described before, you could call the __Constructor repeatedly even if you hadn't instantiated yet.  (Maybe I misunderstood?!)

 

Yeah, I think you misunderstood.  Calling the constructor IS instantiating an object.  Whenever the word 'new' is written an object is being instantiated.

 

Now, you don't need to DEFINE a constructor.  If you don't define one, PHP will simply invoke the default constructor, which doesn't do anything but tell PHP "Hey, this is an object."

 

Someone earlier said you could make it "private" but I guess that isn't so.

 

You CAN make a constructor private.  This is used when you want to deny public/multiple instantiation.  It's a critical part of the Singleton pattern and other static classes (Factories).

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.