Jump to content

Creating a class for a comment box


gsingh85

Recommended Posts

Hi Everyone.  I am new to the world of coding in PHP and I am currently doing some practise stuff. At the moment I have a mysql database set up and I have a very basic html site. I want to place a simple comment box onto the website where someone leaves their name and their comment and it submits. Later I want to be able to log in as an administrator and manage the comments but for now I just want to create the form, create the php script and have the details stored in my database.

This is turning out to be more difficult than I thought it would be. I checked out some tutorials but I've been told not to use their code because it's either badly written or it's not done in OOP style. I have been doing some reading on OOP and the theory behind it. This is what I understand of it so please correct me if I'm wrong.

1. Objects belong to classes.

2. The classes define the objects properties and methods (functions).

3. Each object may contain different values of properties and methods but can belong to the same class.

4. Each property may have it's own methods (functions).

Is this correct?

What I would like to do is create a comment box script so users can leave comments on my site but create the script in OOP style. I'm struggling to do this because I don't know how I would first create the class. Can someone please help me and tell me how I should create the class? Thanks.

 

 

Link to comment
Share on other sites

IMHO - as a newbie you should begin by trying simple procedural php and html and SEE how it's done.  You have a perfect learning-tool example project in front of you, so just work on the php to generate the page (html) and the php to handle the input and post the data to your db.  When you have that working you can then find something else to do (phase 2?) that you can work a class into.   Basically, this example doesn't need classes as it is so small and limited. 

 

Good luck.

Link to comment
Share on other sites

T

 

IMHO - as a newbie you should begin by trying simple procedural php and html and SEE how it's done.  You have a perfect learning-tool example project in front of you, so just work on the php to generate the page (html) and the php to handle the input and post the data to your db.  When you have that working you can then find something else to do (phase 2?) that you can work a class into.   Basically, this example doesn't need classes as it is so small and limited. 

 

Good luck.

 

 

I have already done that. I have created a few things in PHP and learned it's way of doing certain things like connecting to a database, echoing out messages and so on. I just feel I'm not learning anything solid because the tutorials I have seen different people do the same thing in different ways. I understand what they are doing and why they are doing it but they don't seem to be working within a set structure. It all just seems like random code glued togther. If I could find a way of doing things within a structure I feel I would learn a lot better.

 

Yes I appreciate it doesn't need classes but I thought because it's so small and limited may be that would be a good way of learning how OOP works. It's purely for a learning excersise that's all. If this is not a good example to work on is there anything else that I can work on within PHP that I can create in OOP style? Nothing to complicated but something that I can learn from by practising myself.

Link to comment
Share on other sites

I've been a programmer for 30+ years - still don't have a structure.  Programming is about learning to solve problems in a logical way and writing code in sensible way so that you and others can decipher it in the future.  That's about as much structure as one needs.

Link to comment
Share on other sites

Hi Everyone.  I am new to the world of coding in PHP and I am currently doing some practise stuff. At the moment I have a mysql database set up and I have a very basic html site. I want to place a simple comment box onto the website where someone leaves their name and their comment and it submits. Later I want to be able to log in as an administrator and manage the comments but for now I just want to create the form, create the php script and have the details stored in my database.

 

This is turning out to be more difficult than I thought it would be. I checked out some tutorials but I've been told not to use their code because it's either badly written or it's not done in OOP style. I have been doing some reading on OOP and the theory behind it. This is what I understand of it so please correct me if I'm wrong.

 

1. Objects belong to classes.

 

2. The classes define the objects properties and methods (functions).

 

3. Each object may contain different values of properties and methods but can belong to the same class.

 

4. Each property may have it's own methods (functions).

 

Is this correct?

 

What I would like to do is create a comment box script so users can leave comments on my site but create the script in OOP style. I'm struggling to do this because I don't know how I would first create the class. Can someone please help me and tell me how I should create the class? Thanks.

 

Classes are the definition/blueprint of a type.  A type is something that both represents something and the actions that can be performed on that thing.  Example: an integer is a type that represents whole numbers that can be manipulated via mathematics.  Objects are individual, discrete instances of that class (type).  Using the integer example, 5 would be an instance of an integer.

 

With OOP, you're defining complex types and using individual instances of them to do things.  They're complex because they're created using the base types (like string, int, etc.) that the underlying language comes with.  The power of OOP comes from the fact that objects can contain other objects, and pass them around from object to object.

 

That said, we're not just going to tell you how to complete your task.  Show us what you've tried so far, and we'll help, but we don't just give out answers on request as a matter of policy.  

Link to comment
Share on other sites

To expand on Kevin's explanation. Objects identify things in your application. For example a Comment.

 

class Comment {
}
A Comment consists of a few things to regard it as such:

- the author;

- the date it was written;

- what was written;

- and if it was a reply, to which comment it was replied.

 

A class thus groups related information and functions.

 

class Comment {
  private $author;
  private $createDate;
  private $text;
  private $replyTo;
  
  public function __construct(Author $author, DateTime $createDate, $text, Comment $replyTo = null) {
    ..
  }
}
An Author is also a thing in your application with it's own information.

 

class Author {
  private $firstName;
  private $lastName;
  private $emailAddress;
  private $websiteUrl;
  
  public function __construct($firstName, $lastName, Email $email, Url $websiteUrl = null) {
    ..
  }
}
We can continue further down this path and identify Email and Url, because we want both of these to be valid and avoid having to check their validity inside Author, where it does not belong.

 

class Email {
  private $value;
  
  public function __construct($email) {
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      throw new Exception('Email is invalid.');
    }
    ..
  }
}

class Url {
  private $value;
  
  public function __construct($url) {
    if (!filter_var($url, FILTER_VALIDATE_URL)) {
      throw new Exception('Url is invalid.');
    }
    ..
  }
}
You may notice that we did not create classes for $text, $firstName, and $lastName. We could, but because there is nothing interesting about them we simply leave them as strings. Edited by ignace
Link to comment
Share on other sites

Hi Every. Over the last few days I've been working on my very basic comment box programme. I've purposly kept it basic so I can follow it. I managed to make the programme work using a tutorial without any kind of classes or objects but now I want to create the code in oop style. I've created a class which I think is right and within that class I have created 2 variables within it. I have also created 2 objects of that class however I don't think I've done it right. Can someone please have a look at it and point out where I need to make the amendments.

<?php

	class Comment {
		private $author;
		private $comment;
		

}

	$username = new comment ();
	$usercomment = new comment ();
	


//if the form has been submitted then we want to execute some code in the brackets
if ($_POST) {

//below we have defined are variables.
	$username = $_POST ['name'];
	$usercomment = $_POST ['commentcontent'];
	
	
	//not quite sue what this means
	$handle = fopen("comments.html","a");
	fwrite($handle, "<b>" . $username . "</b>:<br/>" . $usercomment . ",<br/>");
	fclose($handle);
	


}

?>
<html>
<body>

<form action = "" method = "POST">
Comments: <textarea rows = "10" cols = "30" name = "commentcontent"></textarea><br/>
name: <input type = "text" name = "name"<br/>
<input type = "submit" value = "post!"><br/>

</form>
<?php include "comments.html"; ?>
</body>
</html>
Link to comment
Share on other sites

Well besides the posts by ignace and KevinM1, which gave you alot of what you needed, Symphony has a pretty good article about moving from procedural to OOP, but I have to postface it with: OOP requires a different kind of thinking, so this will only get you so far into the OOP world. This is just a good place to get your feet wet.

 

That being said, my first comment is: is a user a type of comment? Not in my mind, so you'd need a User object to pass into your comment object (dependency injection) which then gets assigned to the private $author property. Does that make sense?

Always ask yourself 'is this a type of that' and if the answer is No, then it is a good place for a new class. So it would look like this

$User = new User;
$comment = new Comment($User);

// now to get the author of the comment, we'd
echo $comment->author; 
// although this would cause an error because the property is private. We'd need to change it to public or create getters/setters

Now to expand on that, we can convert your procedural code to be like this:

if ($_POST) {
        // create our data pieces
	$user = new User($_POST ['name']);
	$commentContent = $_POST ['commentcontent'];
        $comment = new Comment($user, $commentContent);
	
	
	//not quite sue what this means
        /**
        * To answer this question, this is writing the data to a file called comments.html
        */
	$handle = fopen("comments.html","a");
	fwrite($handle, "<b>" . $comment->author->getName() . "</b>:<br/>" . $comment->getContent() . ",<br/>");
	fclose($handle);
	


}

BTW, this is just an example. Hope it helps you get started.

Edited by TOA
Link to comment
Share on other sites

Looking at Author and making the implicit explicit we get:

 

class Author {
  ..
  
  public function say($comment) {
    $this->comments[] = $o = new Comment($this, $comment);
    return $o;
  }
}
Your code is then:

 

if ($_POST) {
  $author = new Author($_POST['name'], new Email($_POST['email']));
  // or find it: $author = $repo->findByEmail(new Email($_POST['email']));
  $comment = $author->say($_POST['commentcontent']);

  // depending on the type of ownership you persist either $author or $comment
  
  $repo->persist($comment);
  $repo->flush();
}
Edited by ignace
Link to comment
Share on other sites

Ok I've literally been at this for about  2 hours. After some tweaks I've managed to get this error:

 

Fatal error: Call to a member function getName() on a non-object in C:\xampp\htdocs\tutorials\basiccomment\index.php on line 34

 

This is because of this code: $comment->author->getName() and $comment->getContent().

 

If I change to this:

 

$comment->author & $comment->comment

 

Then I don't get the above "fatal error" instead it posts empty "name" and "commentcontent". If fact it posts ":;" on the html file.

 

I think I'm starting to understand the theory and the logic behind it but I've not got it to work so I still haven't fully grasped it. I've been switching between recommended links, sites and tutorials but they do things slightly different from each other so it's hard to fit it into a real world application. I know I've done it wrong because it's not posting anything but I'm not sure what I need to do to put it right. I've been doing some changes here and there but I've still not got it to work. I think I missing a function somewhere but I'll post the code in full if anyone is kind enough to offer me any information.

<?php

	class Comment {
		public $author;
		public $comment;
	}


class user {

	
}

	$User = new User;
$comment = new Comment($User);

// now to get the author of the comment, we'd
echo $comment->author; 
	


if ($_POST) {
        // create our data pieces
	$user = new User($_POST ['name']);
	$commentContent = $_POST ['commentcontent'];
        $comment = new Comment($user, $commentContent);
	
	
	//not quite sue what this means
        /**
        * To answer this question, this is writing the data to a file called comments.html
        */
	$handle = fopen("comments.html","a");
	fwrite($handle, "<b>" . $comment->author . "</b>:<br/>" . $comment->comment . ",<br/>");
	fclose($handle);
	


}


?>
<html>
<body>

<form action = "" method = "POST">
Comments: <textarea rows = "10" cols = "30" name = "commentcontent"></textarea><br/>
name: <input type = "text" name = "name"<br/>
<input type = "submit" value = "post!"><br/>

</form>
<?php include "comments.html"; ?>
</body>
</html>
Link to comment
Share on other sites

 

Ok I've literally been at this for about  2 hours. After some tweaks I've managed to get this error:

 

Fatal error: Call to a member function getName() on a non-object in C:\xampp\htdocs\tutorials\basiccomment\index.php on line 34

 

This is because of this code: $comment->author->getName() and $comment->getContent().

 

If I change to this:

 

$comment->author & $comment->comment

 

Then I don't get the above "fatal error" instead it posts empty "name" and "commentcontent". If fact it posts ":;" on the html file.

 

I think I'm starting to understand the theory and the logic behind it but I've not got it to work so I still haven't fully grasped it. I've been switching between recommended links, sites and tutorials but they do things slightly different from each other so it's hard to fit it into a real world application. I know I've done it wrong because it's not posting anything but I'm not sure what I need to do to put it right. I've been doing some changes here and there but I've still not got it to work. I think I missing a function somewhere but I'll post the code in full if anyone is kind enough to offer me any information.

 

You're getting that error because the getName function is not defined in the user class. Sorry, I should have been clearer about that. You'll need to define that method and give it the needed functionality to return the author's name. And for what it's worth, author is a better name than user, it's clearer. 

 

You should really step back and learn the basics though. It seems like you might be getting ahead of yourself.

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.