Learn from your fellow PHP developers with our PHP blogs, or help share the knowledge you've gained by writing your own.
<?php
namespace App;
use App\Comment;
use App\CommentVote;
use App\CommentSpam;
use App\User;
use Auth;
class CommentModel
{
}
?>
public function getAllComments($pageId)
{
$comments = Comment::where('page_id',$pageId)->get();
$commentsData = [];
foreach ($comments as $key) {
$user = User::find($key->users_id);
$name = $user->name;
$replies = $this->replies($key->id);
$photo = $user->first()->photo_url;
$reply = 0;
$vote = 0;
$voteStatus = 0;
$spam = 0;
if(Auth::user()){
$voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
$spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
if($voteByUser){
$vote = 1;
$voteStatus = $voteByUser->vote;
}
if($spamComment){
$spam = 1;
}
}
if(sizeof($replies) > 0){
$reply = 1;
}
if(!$spam){
array_push($commentsData,[
"name" => $name,
"photo_url" => (string)$photo,
"commentid" => $key->id,
"comment" => $key->comment,
"votes" => $key->votes,
"reply" => $reply,
"votedByUser" =>$vote,
"vote" =>$voteStatus,
"spam" => $spam,
"replies" => $replies,
"date" => $key->created_at->toDateTimeString()
]);
}
}
$collection = collect($commentsData);
return $collection->sortBy('votes');
}
protected function replies($commentId)
{
$comments = Comment::where('reply_id',$commentId)->get();
$replies = [];
foreach ($comments as $key) {
$user = User::find($key->users_id);
$name = $user->name;
$photo = $user->first()->photo_url;
$vote = 0;
$voteStatus = 0;
$spam = 0;
if(Auth::user()){
$voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
$spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
if($voteByUser){
$vote = 1;
$voteStatus = $voteByUser->vote;
}
if($spamComment){
$spam = 1;
}
}
if(!$spam){
array_push($replies,[
"name" => $name,
"photo_url" => $photo,
"commentid" => $key->id,
"comment" => $key->comment,
"votes" => $key->votes,
"votedByUser" => $vote,
"vote" => $voteStatus,
"spam" => $spam,
"date" => $key->created_at->toDateTimeString()
]);
}
}
$collection = collect($replies);
return $collection->sortBy('votes');
}
public function createComment($arary)
{
$comment = Comment::create($array);
if($comment)
return [ "status" => "true","commentId" => $comment->id ];
else
return [ "status" => "false" ];
}
<?php
namespace App;
use App\Comment;
use App\CommentSpam;
use App\CommentVote;
use App\User;
use Auth;
class CommentModel
{
public function getAllComments($pageId)
{
$comments = Comment::where('page_id', $pageId)->get();
$commentsData = [];
foreach ($comments as $key) {
$user = User::find($key->users_id);
$name = $user->name;
$replies = $this->replies($key->id);
$photo = $user->first()->photo_url;
$reply = 0;
$vote = 0;
$voteStatus = 0;
$spam = 0;
if (Auth::user()) {
$voteByUser = CommentVote::where('comment_id', $key->id)->where('user_id', Auth::user()->id)->first();
$spamComment = CommentSpam::where('comment_id', $key->id)->where('user_id', Auth::user()->id)->first();
if ($voteByUser) {
$vote = 1;
$voteStatus = $voteByUser->vote;
}
if ($spamComment) {
$spam = 1;
}
}
if (sizeof($replies) > 0) {
$reply = 1;
}
if (!$spam) {
array_push($commentsData, [
"name" => $name,
"photo_url" => (string) $photo,
"commentid" => $key->id,
"comment" => $key->comment,
"votes" => $key->votes,
"reply" => $reply,
"votedByUser" => $vote,
"vote" => $voteStatus,
"spam" => $spam,
"replies" => $replies,
"date" => $key->created_at->toDateTimeString(),
]);
}
}
$collection = collect($commentsData);
return $collection->sortBy('votes');
}
protected function replies($commentId)
{
$comments = Comment::where('reply_id', $commentId)->get();
$replies = [];
foreach ($comments as $key) {
$user = User::find($key->users_id);
$name = $user->name;
$photo = $user->first()->photo_url;
$vote = 0;
$voteStatus = 0;
$spam = 0;
if (Auth::user()) {
$voteByUser = CommentVote::where('comment_id', $key->id)->where('user_id', Auth::user()->id)->first();
$spamComment = CommentSpam::where('comment_id', $key->id)->where('user_id', Auth::user()->id)->first();
if ($voteByUser) {
$vote = 1;
$voteStatus = $voteByUser->vote;
}
if ($spamComment) {
$spam = 1;
}
}
if (!$spam) {
array_push($replies, [
"name" => $name,
"photo_url" => $photo,
"commentid" => $key->id,
"comment" => $key->comment,
"votes" => $key->votes,
"votedByUser" => $vote,
"vote" => $voteStatus,
"spam" => $spam,
"date" => $key->created_at->toDateTimeString(),
]);
}
}
$collection = collect($replies);
return $collection->sortBy('votes');
}
public function createComment($arary)
{
$comment = Comment::create($array);
if ($comment) {
return ["status" => "true", "commentId" => $comment->id];
} else {
return ["status" => "false"];
}
}
public function voteComment($commentId, $array)
{
$comments = Comment::find($commentId);
$data = [
"comment_id" => $commentId,
'vote' => $array->vote,
'user_id' => $array->users_id,
];
if ($array->vote == "up") {
$comment = $comments->first();
$vote = $comment->votes;
$vote++;
$comments->votes = $vote;
$comments->save();
}
if ($array->vote == "down") {
$comment = $comments->first();
$vote = $comment->votes;
$vote--;
$comments->votes = $vote;
$comments->save();
}
if (CommentVote::create($data)) {
return true;
}
}
public function spamComment($commentId, $array)
{
$comments = Comment::find($commentId);
$comment = $comments->first();
$spam = $comment->spam;
$spam++;
$comments->spam = $spam;
$comments->save();
$data = [
"comment_id" => $commentId,
'user_id' => $array->users_id,
];
if (CommentSpam::create($data)) {
return true;
}
}
}
?>
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Comment;
use App\CommentVote;
use App\CommentSpam;
use App\User;
use Auth;
class CommentController extends Controller
{
public function index($pageId)
{
$comments = Comment::where('page_id',$pageId)->get();
$commentsData = [];
foreach ($comments as $key) {
$user = User::find($key->users_id);
$name = $user->name;
$replies = $this->replies($key->id);
$photo = $user->first()->photo_url;
$reply = 0;
$vote = 0;
$voteStatus = 0;
$spam = 0;
if(Auth::user()){
$voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
$spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
if($voteByUser){
$vote = 1;
$voteStatus = $voteByUser->vote;
}
if($spamComment){
$spam = 1;
}
}
if(sizeof($replies) > 0){
$reply = 1;
}
if(!$spam){
array_push($commentsData,[
"name" => $name,
"photo_url" => (string)$photo,
"commentid" => $key->id,
"comment" => $key->comment,
"votes" => $key->votes,
"reply" => $reply,
"votedByUser" =>$vote,
"vote" =>$voteStatus,
"spam" => $spam,
"replies" => $replies,
"date" => $key->created_at->toDateTimeString()
]);
}
}
$collection = collect($commentsData);
return $collection->sortBy('votes');
}
protected function replies($commentId)
{
$comments = Comment::where('reply_id',$commentId)->get();
$replies = [];
foreach ($comments as $key) {
$user = User::find($key->users_id);
$name = $user->name;
$photo = $user->first()->photo_url;
$vote = 0;
$voteStatus = 0;
$spam = 0;
if(Auth::user()){
$voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
$spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
if($voteByUser){
$vote = 1;
$voteStatus = $voteByUser->vote;
}
if($spamComment){
$spam = 1;
}
}
if(!$spam){
array_push($replies,[
"name" => $name,
"photo_url" => $photo,
"commentid" => $key->id,
"comment" => $key->comment,
"votes" => $key->votes,
"votedByUser" => $vote,
"vote" => $voteStatus,
"spam" => $spam,
"date" => $key->created_at->toDateTimeString()
]);
}
}
$collection = collect($replies);
return $collection->sortBy('votes');
}
public function store(Request $request)
{
$this->validate($request, [
'comment' => 'required',
'reply_id' => 'filled',
'page_id' => 'filled',
'users_id' => 'required',
]);
$comment = Comment::create($request->all());
if($comment)
return [ "status" => "true","commentId" => $comment->id ];
}
public function update(Request $request, $commentId,$type)
{
if($type == "vote"){
$this->validate($request, [
'vote' => 'required',
'users_id' => 'required',
]);
$comments = Comment::find($commentId);
$data = [
"comment_id" => $commentId,
'vote' => $request->vote,
'user_id' => $request->users_id,
];
if($request->vote == "up"){
$comment = $comments->first();
$vote = $comment->votes;
$vote++;
$comments->votes = $vote;
$comments->save();
}
if($request->vote == "down"){
$comment = $comments->first();
$vote = $comment->votes;
$vote--;
$comments->votes = $vote;
$comments->save();
}
if(CommentVote::create($data))
return "true";
}
if($type == "spam"){
$this->validate($request, [
'users_id' => 'required',
]);
$comments = Comment::find($commentId);
$comment = $comments->first();
$spam = $comment->spam;
$spam++;
$comments->spam = $spam;
$comments->save();
$data = [
"comment_id" => $commentId,
'user_id' => $request->users_id,
];
if(CommentSpam::create($data))
return "true";
}
}
public function destroy($id)
{
}
}?>
<?php
namespace App\Http\Controllers;
use App\CommentModel;
use Illuminate\Http\Request;
class CommentController extends Controller
{
private $commentModel = null;
private function __construct()
{
$this->commentModel = new CommentModel();
}
public function index($pageId)
{
return $this->commentModel->getAllComments($pageId);
}
public function store(Request $request)
{
$this->validate($request, [
'comment' => 'required',
'reply_id' => 'filled',
'page_id' => 'filled',
'users_id' => 'required',
]);
return $this->commentModel->createComment($request->all());
}
public function update(Request $request, $commentId, $type)
{
if ($type == "vote") {
$this->validate($request, [
'vote' => 'required',
'users_id' => 'required',
]);
return $this->commentModel->voteComment($commentId, $request->all());
}
if ($type == "spam") {
$this->validate($request, [
'users_id' => 'required',
]);
return $this->commentModel->spamComment($commentId, $request->all());
}
}
}
?>
$users = [new User(), new User()];
I see a lost opportunity to use Iterator.public function getUsers(): array
{
return $userArray;
}
public function setUsersToActiveState()
{
$users = $this->getUsers();
foreach ($users as $user) {
if(!$user->getActiveStatus()) {
$user->setActiveStatus(true);
}
}
}
There immediately two problems occurred.
class UsersCollection implements \IteratorAggregate
{
private $users = [];
public function getIterator() : UserIterator
{
return new UserIterator($this);
}
public function getUser($position)
{
if (isset($this->users[$position])) {
return $this->users[$position];
}
return null;
}
public function count() : int
{
return count($this->users);
}
public function addUser(User $users)
{
$this->users[] = $users;
}
}
class UserIterator implements \Iterator
{
private $position = 0;
private $userCollection;
public function __construct(UsersCollection $userCollection)
{
$this->userCollection = $userCollection;
}
public function current() : User
{
return $this->userCollection->getUser($this->position);
}
public function next()
{
$this->position++;
}
public function key() : int
{
return $this->position;
}
public function valid() : bool
{
return !is_null($this->userCollection->getUser($this->position));
}
public function rewind()
{
$this->position = 0;
}
}
class UsersCollectionTest extends TestCase
{
public function testUsersCollectionShouldReturnNullForNotExistingUserPosition()
{
$usersCollection = new UsersCollection();
$this->assertEquals(null, $usersCollection->getUser(1));
}
public function testEmptyUsersCollection()
{
$usersCollection = new UsersCollection();
$this->assertEquals(new UserIterator($usersCollection), $usersCollection->getIterator());
$this->assertEquals(0, $usersCollection->count());
}
public function testUsersCollectionWithUserElements()
{
$usersCollection = new UsersCollection();
$usersCollection->addUser($this->getUserMock());
$usersCollection->addUser($this->getUserMock());
$this->assertEquals(new UserIterator($usersCollection), $usersCollection->getIterator());
$this->assertEquals($this->getUserMock(), $usersCollection->getUser(1));
$this->assertEquals(2, $usersCollection->count());
}
private function getUserMock()
{
}
}
class UserIteratorTest extends MockClass
{
public function testCurrent()
{
$iterator = $this->getIterator();
$current = $iterator->current();
$this->assertEquals($this->getUserMock(), $current);
}
public function testNext()
{
$iterator = $this->getIterator();
$iterator->next();
$this->assertEquals(1, $iterator->key());
}
public function testKey()
{
$iterator = $this->getIterator();
$iterator->next();
$iterator->next();
$this->assertEquals(2, $iterator->key());
}
public function testValidIfItemInvalid()
{
$iterator = $this->getIterator();
$iterator->next();
$iterator->next();
$iterator->next();
$this->assertEquals(false, $iterator->valid());
}
public function testValidIfItemIsValid()
{
$iterator = $this->getIterator();
$iterator->next();
$this->assertEquals(true, $iterator->valid());
}
public function testRewind()
{
$iterator = $this->getIterator();
$iterator->rewind();
$this->assertEquals(0, $iterator->key());
}
private function getIterator() : UserIterator
{
return new UserIterator($this->getCollection());
}
private function getCollection() : UsersCollection
{
$userItems[] = $this->getUserMock();
$userItems[] = $this->getUserMock();
$usersCollection = new UsersCollection();
foreach ($userItems as $user) {
$usersCollection->addUser($user);
}
return $usersCollection;
}
private function getUserMock()
{
}
}
public function getUsers(): UsersCollection
{
$userCollection = new UsersCollection();
foreach ($whatIGetFromDatabase as $user) {
$userCollection->addUser($user);
}
return $userCollection;
}
public fucntion setUsersToActiveState()
{
$users = $this->getUsers();
foreach ($users as $user) {
if(!$user->getActiveStatus()) {
$user->setActiveStatus(true);
}
}
}
As you can see setUsersToActiveState remains the same, we only do not need to specify for our IDE or collagues what type $users variable is. public function addUser(User $users)
{
if ($user->getAge() > 18) {
$this->users[] = $users;
}
}
public function addUsers(array $users)
{
foreach($users as $user) {
$this->addUser(User $users);
}
}
CREATE TABLE <code>mydbname</code>.<code>content</code> ( <code>ID</code> INT(11) NOT NULL AUTO_INCREMENT , <code>title</code> VARCHAR(100) NOT NULL , <code>content</code> LONGTEXT NOT NULL , <code>author</code> VARCHAR(50) NOT NULL , PRIMARY KEY (<code>ID</code>)) ENGINE = MyISAM COMMENT = 'content table';
conn.php
file in your root/includes folder.conn.php
file, remember to include your own database credentials.
<?php
$letsconnect = new mysqli("localhost","dbuser","dbpass","dbname");
?>
index.php
at the root of your CMS folder.
<?php
include('includes/conn.php');
if ($letsconnect -> connect_errno) { echo "Error " . $letsconnect -> connect_error;
}else{
$getmydata=$letsconnect -> query("SELECT * FROM content");
foreach($getmydata as $mydata){ echo "Title: "; echo $mydata['title']; echo "<br/>"; echo "Content: "; echo $mydata['content']; echo "<br/>"; echo "Author: "; echo $mydata['author']; echo "<br/>"; echo "<br/>";
}
}
$letsconnect -> close();
?>
index.php
in your backend folder.
<html>
<head><title>Backend - Capture Content</title></head>
<body>
<form action="<?php $_SERVER[‘PHP_SELF’];?>" method="post">
<input type="text" name="title" placeholder="Content Title here" required/>
<textarea name="content">Content Here</textarea>
<input type="text" name="author" placeholder="Author" required/>
<input type="submit" value="Save My Data" name="savedata"/>
</form>
</body>
</html>
<form>
tag.
<?php
if(isset($_POST['savedata'])){
include('../includes/conn.php');
if ($letsconnect->connect_error) {
die("Your Connection failed: " . $letsconnect->connect_error);
}else{
$sql = "INSERT INTO content(title,content,author)VALUES ('".$_POST["title"]."', '".$_POST["content"]."', '".$_POST["author"]."')";
if (mysqli_query($letsconnect, $sql)) {
echo "Your data was saved successfully!";
} else { echo "Error: " . $sql . "" . mysqli_error($letsconnect);
} $letsconnect->close();
}
}
?>
Note, this is a basic MySQL query to insert data. However, before using this in production it's important to add proper escaping and security to prevent SQL injections. This will be covered in the next article.
We highly recommend that you follow these tutorials on a localhost testing server like Uniserver. Read through Part 1 here to look at our recommendations. These tutorials follow a phased approach and it is highly recommended that you do not make snippets of code live prior to completing this tutorial series.
$sql = "INSERT INTO content(title,content,author)VALUES ('".$_POST["title"]."', '".$_POST["content"]."', '".$_POST["author"]."')";
$title = $letsconnect -> real_escape_string($_POST['title']);
$content = $letsconnect -> real_escape_string($_POST['content']);
$author = $letsconnect -> real_escape_string($_POST['author']);
$letsconnect
? This was used because of our db connection defined in conn.php.$sql = "INSERT INTO content (title,content,author) VALUES ('".$title."', '".$content."', '".$author."')";
$sql
.<html>
<head>
<title>My Awesome CMS – Page Title</title>
</head>
<body>
</body>
</html>
</head>
tag. <link href=”../assets/css/style.css” type=”text/css” rel=”stylesheet”/>
<?php
tag. <div id="myfirstid"></div>
<div class="myfirstclass"></div>
<div class="myfirstclass"></div>
<div class="myfirstclass"></div>
<div class="myfirstclass"></div>
<div class="myfirstclass"></div>
#myfirstid{
Background:lightblue;
Font-family:Arial;
Font-size:44px;
Font-weight: Bold;
}
.myfirstclass{
Font-size:15px;
Color: darkblue;
}
include(‘includes/header.php’);
<divs>
we used for practice earlier, we have something better in store! include(‘includes/footer.php’);
foreach($getmydata as $mydata){ echo "Title: "; echo $mydata['title']; echo "<br/>"; echo "Content: "; echo $mydata['content']; echo "<br/>"; echo "Author: "; echo $mydata['author']; echo "<br/>"; echo "<br/>";
?>
<div id=”myfirstid”>
<?php
foreach($getmydata as $mydata){
echo "<div class=”myfirstclass”>Title: ";
echo $mydata['title'];
echo "<br/>";
echo "Content: ";
echo $mydata['content'];
echo "<br/>";
echo "Author: ";
echo $mydata['author'];
echo "</div><br/><br/>";
}?>
</div>
<?php
<?php
include('includes/header.php');
include('includes/conn.php');
if ($letsconnect -> connect_errno) { echo "Error " . $letsconnect -> connect_error;
}else{
$getmydata=$letsconnect -> query("SELECT * FROM content");
?>
<div id="myfirstid">
<?php
foreach($getmydata as $mydata){
echo "<div class=”myfirstclass”>Title: ";
echo $mydata['title'];
echo "<br/>";
echo "Content: ";
echo $mydata['content'];
echo "<br/>";
echo "Author: ";
echo $mydata['author'];
echo "</div><br/><br/>";
}
?>
</div>
<?php
}
$letsconnect -> close();
include('includes/footer.php');
?>