Jump to content

Getting very good I think at understanding OOP critique advice needed though!


j.smith1981

Recommended Posts

I am after some advice about doing some rather basic things that wouldnt really be done in OOP and see if there's a better way of doing this.

 

As I just said though I know this is not the required system just one displaying of a form but I think its really cool for just simplying OOP ( :D), and I actually understand it, I always need to start off small, understand it all, before I start waffling will show you my code (in no way finished yet, as you can tell from some of the html elements but its principle works:

 

<?php
ini_set('display_errors',1);

class Form{

public $to;
public $user;
public $email;
public $subject;
public $comment;

function showForm(){
	// displaying of form to the user:
	echo <<<userform
<html>
<head>
<title>Jez's Contact Form</title>
</head>
<body>
	<form id="contact" name="contact" method="post" action="{$_SERVER['PHP_SELF']}">
	<label for="">Enter something:</label><input type="text" id="user"
	</form>
</body>
</html>
userform;
}
}

if(!array_key_exists('submit',$_POST)) {

$myForm = new Form;

// now we construct the form:
$myForm->showForm();

// print_r($myForm);
}

?>

 

If a submit button in the form hasnt been hit, then show form, later on going to do and try out some validation, just wanted some advice before I get too big for my boots as such.

 

Any advice on improving it (obviously finishing my form off of course which is what I will do), but any further advice is greatly appreciated,

Jez.

Link to comment
Share on other sites

Ok I have this:

 

<?php
ini_set('display_errors',1);

class Form{

public $to;
public $user;
public $email;
public $subject;
public $comment;

function showForm(){
	// displaying of form to the user:
	echo <<<userform
<html>
<head>
<title>Jez's Contact Form</title>
</head>
<body>
	<form id="contact" name="contact" method="post" action="{$_SERVER['PHP_SELF']}">
	<label for="">Enter something:</label><input type="text" id="user" name="user" value="" />
	<input type="submit" id="submit" name="submit" value="Submit" />
	</form>
</body>
</html>
userform;
}

function showMessage() {
	echo <<<MESSAGE
<html>
<body>
		{$_POST['user']}
</body>
</html>
MESSAGE;
}
}

if(!array_key_exists('submit',$_POST)) {

$myForm = new Form;

// now we construct the form:
$myForm->showForm();

// print_r($myForm);
}

?>

 

But how is the best method for displaying results like when the user has submitted a form for example and says hello in the user field, didnt bother changing the var, could have said value or something in there but hey, its for simple purposes.

 

How is the best way for it to say 'you typed in: hello' or whatever the user has typed in the field?

 

Bit confused about this, probably would help aswell with another post I have made possibly, hmm bit stuck now lol.

Link to comment
Share on other sites

You're welcome ; )

 

<html>
<head>
</head> 
</body> 
<form method="post" action="<?php
  echo $_SERVER["PHP_SELF"];
?>"> 
<table> 
<tr><td>Name:<input type="text" name="name" size="10"></td></tr> 
<tr><td>Say what you want: <input type="text" name="you_typed" size="50"></td></tr> 
<tr><td><input type="submit" name="submit" value="Give me the data!"></td></tr> 
</table>
</form> 
</body> 
</html>

<?php
  
  class echoIt
  {
      
      var $name;
      var $you_typed;
      function passed($arg1, $arg2)
      {
          $this->name = $arg1;
          $this->you_typed = $arg2;
      }
  }
  $your_name = $_POST['name'];
  $what_you_typed = $_POST['you_typed'];
  $output = new echoIt();
  $output->passed($your_name, $what_you_typed);
  echo "Your name is " . $output->name . " and you typed: " . $output->you_typed . ".";
?>

 

Link to comment
Share on other sites

It's not uncommon to have HTML helper objects like this.  Just remember to keep them as abstract as possible.  A Form object should really only display the starting and ending <form></form> tags, with its action being determined by parameters passed in.  The other inputs would then be their own objects.  A Textbox object, Password object, SelectList object, etc.  This allows you to create a form with an arbitrary number of inputs, and gives you a hook for validation.

 

It's hard to describe in more detail if you don't know the MVC pattern.

Link to comment
Share on other sites

Ahh!

 

Wonderful really appreciate that, so I'd use the html elements before and beyond the form tags out of the php script, makes sense.

 

Will go over this, shouldnt take me long to understand this to be fair, that example makes perfect sense!

 

Really appreciate it, thanks again,

 

Jez

Link to comment
Share on other sites

I am having sorry some trouble still with this form:

 

<html>
<body>

<?php
// display errors just in development mode:
ini_set('display_errors',1);

class Form {

public $entry;

function constructEntry($userEntry) {
	$this->entry = $userEntry;
}
}

// set it here just to show it works!

if(!array_key_exists('submit',$_POST)) {
echo "Message to user saying it hasnt been submitted!";
} else {
$myentry = new Form(); // creates an object will set the above var in the blueprint as NULL!

$userEntry = $_POST['entry'];
$myentry->constructEntry($userEntry);
}

?>

<form id="user_entry" name="user_entry" method="post" action="<? echo $_SERVER['PHP_SELF'];?>">
<input type="text" id="entry" name="entry" value="" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>

</body>
</html>

 

I did put the var_dump($myentry) and print_r($myentry) and its still coming up with the attribute in the class as being NULL, going to try this yet again to see if I can get this working lol.

 

I'd appreciate any help,

Jez.

Link to comment
Share on other sites

Ignore me having an idiot day lol, some reason because I login via SSH to my server (allot more secure than FTP).

 

Its then reasked me for my password and didnt subsequently update the file, woops!

 

It works wonderfully thanks ever so much!

 

Going to see how far I can get with this, should be really interesting.

 

Again thanks,

Jez.

Link to comment
Share on other sites

Would you criticise this for me please?

 

<html>
<body>

<?php
// display errors just in development mode:
ini_set('display_errors',1);

class Form {

public $error;
public $entry;

function errorMessage($message) {
	$this->error = $message;
}

function constructEntry($userEntry) {
	$this->entry = $userEntry;
}
}

// set it here just to show it works!

if(!array_key_exists('submit',$_POST)) {
echo "Message to user saying it hasnt been submitted!";
} else {

$myentry = new Form(); // creates an object will set the above var in the blueprint as NULL!

$userEntry = $_POST['entry'];
$myentry->constructEntry($userEntry);
echo "<pre>";
print_r($myentry);
echo "</pre>";

// print_r($myentry); // this is just to test to see if it works!

if($userEntry == '') {
	$myentry->errorMessage("You didnt type anything!");
	echo "<pre>";
	print_r($myentry);
	echo "</pre>";
}
}

?>

<form id="user_entry" name="user_entry" method="post" action="<? echo $_SERVER['PHP_SELF'];?>">
<label for="entry">Enter Data: </label><input type="text" id="entry" name="entry" value="" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>

</body>
</html>

 

I am really impressed with what I have done but lacking confidence in knowing if its the best way (albeit obviously not a reason for using OOP, but again just to illustrate how its used, maybe in bigger systems, I might have 4 forms and I want to contain them), so understand how it could possibly fit into say a some sort of CMS system or something.

 

But dont want to get too far ahead and encourage my bad habits (unknown to me of course).

 

Any helps appreciated,

Jez.

Link to comment
Share on other sites

Would you criticise this for me please?

 

Sorry but, what is there to critique? It doesn't do anything.

 

Sorry I have done something your link says not to do as such, its rather an open ended question, going to attempt something, like adding it to a database, see if it works and then post back if there's a better way of doing this.

 

Then perhaps conver that backwards sort of, what I mean is use it like a guestbook, sorry about that last post.

 

Thanks again,

Jez.

Link to comment
Share on other sites

I have tried doing the mysql_connect as a function, is this basically the best way of doing this?

 

Just seems a bit shoddy to me, but I couldnt get it working, so I have included a segment of code since all the other parts work, going to have a retry at a few bits of it just to improve the logic so to speak, but this is what I have done so far, if not empty field being entered then do (connect to database basically).

 

Here's the code:

	if($userEntry == '') {

	$myentry->errorMessage("You didnt type anything!");

} else {

	// look at this soon! look at adding to the database here?
	$connect = mysql_connect('localhost','jeremy','s56pj989');

	if(!$connect) {

		echo mysql_error();
		exit;

	} else {

		$select_db = mysql_select_db('test',$connect);
		if(!$select_db) {

			echo mysql_error();
			exit;

		}
	}
}

 

Any help as usual is really appreciated, god the amount of learning I am doing from this, getting rid of my bad habbits is kinda good, going to look through a book also just to bump it up a bit.

 

Thanks again and any replies are truely appreciated!

Jez.

Link to comment
Share on other sites

This is the most important piece of advice so far from above:

 

"Just remember to keep them as abstract as possible."

 

When you are dealing with abstract things like forms which can have any number of fields, field types, decorators etc etc it is very important to keep things abstract and extend with the specifics, like what html to use.

 

A prefect example of a form class or object as it would be is Zend_Form. You can download it freely and even use it without using the whole Zend Framework. This also begs the statement "don't reinvent the wheel".

 

There are already perfectly valid and best practice classes available for dealing with such things. You should either use them, or at least download the source and develop your own class based on their source. This will teach you about security, extendibility, maintainability etc

 

First of all, do not have anything in your class file, but your class. That means do not have <html> at the top, you should NEVER need to weave in and out of php in a file which declares a class. This is very basic and the first important step in keeping it abstract.

 

For example, if you wanted to use this class on another site within a template you would produce invalid html as once you include the class, you are also including the html that goes with it. In this case more <html> tags.

 

Secondly, you should probably separate what html markup you produce for the form. This means having specific methods for declaring what tags, classes, id's etc you should use and what structure it should be in. This will allow you to define a default way of dealing with things but also allow you to override this default behaviour either through class extension or specific methods within the base class for dealing with this.

 

===

On your latest reply. You should use yet another class like your form class to deal with database connections. If you take all the above into account your file should look like this:

 

(note, usually a connection is maintained anyway. It doesn't usually matter when you make this connection - meaning you don't need to validate much to do so.)

 

// include your Form class which contains nothing but your class
include('path/to/classes/myForm.class.php');

//include your Database class
include('path/to/class/myDatabase.class.php');

if(ISSET($_POST('submit'))){

  // validate input, and connect to database if necessary
  
  if($validationClass->isValidEntry($_POST['entry'])){
    $db = new Database();
    $db->connect();
    
    // perform query etc
  }

}else{

  // create new form etc
  $form = new Form();

}

 

In the above I have also included use of a $validationClass. This is yet another class which can assist you and should be abstracted. A valid entry or username or password can change from app to app so it is important that you not need to change your form class (which should only deal with form construction) to change these validation methods.

 

..which leads again to that very important point of keeping things abstract but also loosely coupled. This means one class does rely on another class which then relies on another class. Each 'base' class should deal with something abstract. Personally, for this I would have:

 

Form class which can be extended to change html structure

Validation class which can be extended to change validation methods

Database class which ca be extended to change database connection settings

 

The above is generally how frameworks deal with these tasks. Main thing to focus on in base classes is abstraction. Can it be easily used with another app? Does it rely on too many other classes? how easily can it be customized or extended?

 

If you can answer yes to all of those questions then you have a class you can reuse over and over again and save yourself many hours of needless work.

Link to comment
Share on other sites

Actually about 10 minutes I had a funny feeling you would reply with something like that.

 

But yes makes sense the ZendFramework, will definately give that a look.

 

Been meaning to play around with that, you include the classes in the php.ini file dont you? Or is is just like smarty HTML where you can declare where their located incase you need to use it in a portable app. kind of?

 

I get what classes are though, their just libraries more though arent they?

 

But thats a great tip about abstractation, would I be better off doing that, doing an abstract class then formally or just a class that extends?

 

Can see that with an abstract class it means you cant create an object directly off an abstract but you can when you extend it yes?

 

Thanks and again I look forward to any replies,

Jez.

Link to comment
Share on other sites

I get what classes are though, their just libraries more though arent they?

 

Not in the slightest.  At least, not if you're trying to write legit OOP code.  Each class defines a data type (think int or string).  They denote both a kind of data and the actions that can be performed on that data.  An object is an instance of that newly created custom data type.

 

Objects are supposed to represent things - a product in an online store, a user, a login handler, etc.

 

Objects are also supposed to be as independent as possible.  All your system should know of an object is its public interface - the public data members and methods it contains (not to be confused with the interface keyword, which is both similar and different).  This allows one to change the implementation of an object without changing how it's used by other parts of the system.  This is what the terms abstraction, encapsulation, and polymorphism describe.

 

Think LEGOs.  Objects are the blocks.  They all have their unique characteristics (this one is blue, the other is a 1x4, etc.), and they can all be put together in different ways to make new meta shapes, but they can only connect together in one way - by matching pegs with holes.  This is how objects work.  The peg->hole relationship is facilitated by an object's public interface.  That's the only proper way to stick the blocks together.

Link to comment
Share on other sites

I get what classes are though, their just libraries more though arent they?

 

Not in the slightest.  At least, not if you're trying to write legit OOP code.  Each class defines a data type (think int or string).  They denote both a kind of data and the actions that can be performed on that data.  An object is an instance of that newly created custom data type.

 

Objects are supposed to represent things - a product in an online store, a user, a login handler, etc.

 

Objects are also supposed to be as independent as possible.  All your system should know of an object is its public interface - the public data members and methods it contains (not to be confused with the interface keyword, which is both similar and different).  This allows one to change the implementation of an object without changing how it's used by other parts of the system.  This is what the terms abstraction, encapsulation, and polymorphism describe.

 

Think LEGOs.  Objects are the blocks.  They all have their unique characteristics (this one is blue, the other is a 1x4, etc.), and they can all be put together in different ways to make new meta shapes, but they can only connect together in one way - by matching pegs with holes.  This is how objects work.  The peg->hole relationship is facilitated by an object's public interface.  That's the only proper way to stick the blocks together.

 

Fantastic analogy!

Link to comment
Share on other sites

Yea,

 

I mean I am massively learning this, just need to really use it to appreciate it so to speak!

 

Looks like I have my work cut out for me over the holiday lol from work, just want to appreciate it, I mean I do get that what I did was quite combersome, but its good in its own way to understand why other things exist to help with that (its all good!)

 

No but thank you really appreciate the feedback!

 

Thanks again,

Jeremy. :D

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.