Display comment/blog using OOP in PHP

This is where you share YOUR scripts with others

Moderators: egami, macek, gesf

Post Reply
User avatar
Strider64
php-forum Active User
php-forum Active User
Posts: 297
Joined: Sat Mar 23, 2013 8:24 am

Wed Jun 05, 2013 10:37 am

I have written a nice little cms website written in Object-Orient Programming style and you can find a live demo (well actually it's my website) here: https://www.pepster.com/index.php

I decided to share a few scripts for everyone.

Here is a file I called index.html (which is included in a much larger file called index.php):

Code: Select all

<!-- # index.html = Display 2 Columns -->
<section>
<?php 
//$displayName = '';
?>
<?php // Fetch the results and display them:
// Fetches the pages (in this case 2):
while ($page = $result->fetch()) {
    // New instance of Controller, this enables to grab
    // the person who posted their real name or user's name:    
    $postedBy = new Controller($page->getCreatorId());
    // Display the appropiate info:    
	echo '
    <article><div class="blog-styling">    
	<h1><span>Posted on ' . $page->getDateUpdated() . ' by ' . $postedBy->displayName . '</span>' . $page->getTitle() . '</h1>
	<p>' . $page->getIntro() . '&nbsp;&nbsp;<a href="page.php?id=' . $page->getId() . '">read more here...</a></p>
	</div></article>
	';
}
?>
</section>
Member.php located in my classes subfolder:

Code: Select all

<?php  # Member class - Store user info and functions to access/controll the flow of data.

class Member {
	
    // The member attributes containing required and optional information.
    // The attributes must correspond to the database table columns:
    
    private $id = NULL;
    private $userType=NULL; // Required (assigned enum)
    private $username=NULL; // Required 
    private $email=NULL; // Required   
    private $pass=NULL; // Required
    private $fullName=NULL;
	private $validation_code=NULL;
    private $address=NULL;
    private $city=NULL;
    private $state=NULL;
    private $zipCode=NULL;
    
	// Method returns the user ID:
	public function getId() {
		return $this->id;
	}
	
	// Grab the user's username:
	public function getUsername() {
		return $this->username;	
	}
	
	// Grab the user's full name:
	public function getFullName() {
		return $this->fullName;	
	}	
	
	// Grab the password:
	public function getPass() {
		return $this->pass;	
	}
	
	public function getUserType() {
		return $this->userType;	
	}
	
	// Clear the password once user is logged in:
	public function clearPass() {
		$this->pass = NULL;	
	}
	
	public function getEmail() {
		return $this->email;	
	}   
	// Method returns a Boolean if the user is an administrator:
	public function isAdmin() {
		return ($this->userType == 'admin');
	}
	
	public function isNewUser() {
		return ($this->userType == 'public');	
	}
	
	// Method returns a Boolean indicating if the user is an administrator
	// or if the user is the original author of the provided page:
	public function canEditPage(Page $page) {
		return ($this->isAdmin() || ($this->id == $page->getCreatorId()));
	}
	
	// Method returns a Boolean indicating if the user is an administrator or an author:
	public function canCreatePage() {
		return ($this->isAdmin() || ($this->userType == 'author'));
	}
      
}
Page.php located in my classes subfolder:

Code: Select all

<?php # Page.php - John Pepp
// This script defines the Page clss

/* Class Page.
 * The class contains seven attributes, id, createId, sticky, title, content, dateAdded, and dateUpdated.
 * The attributes match the corresponding database columns.
 * The class contains eight methods:
 * - getId()
 * - getCreatorId()
 * - isTopicSticky()
 * - getTitle()
 * - getContent()
 * - getDateAdded()
 * - getDateUpdated()
 * - getIntro()
 */
 
 class Page {
	 
	 // All attributes correspond to database columns.
	 // All attributes are protected.
	 protected $id = null;
	 protected $creatorId = null;
	 protected $sticky = null;
	 protected $title = null;
	 protected $content = null;
	 protected $dateAdded = null;
	 protected $dateUpdated = null;
	 
	 // no need for a constructor:
	 
	 // Six methods for returning attribute values:
	 function getId() {
		 return $this->id;
	 }
	 
	 function isTopicSticky() {
		return ($this->sticky == 'yes'); 
	 }
	 
	 function getCreatorId() {
		 return $this->creatorId;
	 }
	 function getTitle() {
		 return $this->title;
	 }
	 function getContent() {
		 return nl2br(htmlspecialchars($this->content, ENT_QUOTES | ENT_HTML401, 'UTF-8'));
	 }
	 function getDateAdded() {
		 return $this->dateAdded;
	 }
	 function getDateUpdated() {
		 return $this->dateUpdated;
	 }
	 
	 // Method returns the first X characters from the content:
	 function getIntro($count = 400) {
		 return substr(nl2br(strip_tags($this->content)), 0, $count) . '...';
	 }
	 
 } // End of Page class.
I have a class call Controller.php where right now only retrieves the user's name or username:

Code: Select all

<?php
class Controller extends DBConnect { // Extend the class to include database connection
	
  /* 
   *   This class interacts between the Members class and the Pages Class,
   *   right now it only displays who "Created the Blog" to the screen; however
   *   in the future in could do more between these two classes and even more classes.
   *   So stay tune for improvement in  the future. Date Created : 6/5/2013
   */
  
  // 4 protected attributes for the protected methods: 
  protected $creatorId = NULL;
  protected $creatorName = NULL;
  protected $userType = NULL;
  protected $returnName = NULL;
  
  // This is the attribute that is accessable:
  public $displayName = NULL;
  
  // This constructor returns either username or Full Name depending on 
  // if the user is an administrator or just a regular user: 
  public function __construct($creatorId) {
	  $this->displayName = $this->determinePostedName($creatorId);
  }
  
  // This function determines if user is administrator or not then returns the appropiate name:
  protected function determinePostedName($creatorID) {
	  // Grab the poster's access level:
	  $this->userType = $this->getUserType($creatorID);
	  // Grab the appropiate name (username or fullname) based on access level:
	  if ($this->userType == 'admin') {
		  return $this->returnName = $this->getFullName($creatorID);
	  } else {
		  return $this->returnName = $this->getUsername($creatorID);  
	  }	  
  }
  
  // This function returns the username:
  protected function getUsername( $creatorId) {

	// Connect to PDO database:
	$pdo = parent::connect();	
    
	// Select username from users databse:
    $sql = "SELECT username FROM users WHERE id = :id";

    try {
	  // Use prepared statement:	
      $st = $pdo->prepare( $sql );
	  
	  // Bind the value to the query:
      $st->bindValue( ":id", $creatorId );
	  
	  // Execute query once everything is all set:
      $st->execute();
	  // fetch the row (Note: Fetch Associatie Arrays is default in DBConnect class):
      $row = $st->fetch();
	  
      // If result is return, we know we have a match:
	  if ($row) {
		 return $this->creatorName = $row['username'];
	  } else { 
	     throw new Exception('No Name on File');		  
	  }
      
    } catch ( PDOException $e ) {      
      // Write to error log or send an email to administrator:
    }
  }	
  
  // This function returns the user's full name:
  protected function getFullName( $creatorId) {

	// Connect to PDO database:
	$pdo = parent::connect();	
    
    $sql = "SELECT fullName FROM users WHERE id = :id";

    try {
      $st = $pdo->prepare( $sql );
      $st->bindValue( ":id", $creatorId );
      $st->execute();
      $row = $st->fetch();
      
	  if ($row) {
		  return $this->creatorName = $row['fullName'];
	  } else {
		  throw new Exception('No Name on File');	
	  }
      
    } catch ( PDOException $e ) {
        // Write to error log or send an email to administrator:        
    }
  }	
  
  // This function/method returns if the user is admin or not:
  protected function getUserType($creatorId) {

	// Connect to PDO database:
	$pdo = parent::connect();	
    
    $sql = "SELECT userType FROM users WHERE id = :id";

    try {
      $st = $pdo->prepare( $sql );
      $st->bindValue( ":id", $creatorId );
      $st->execute();
      $row = $st->fetch();
      
	  if ($row) {
		 return $this->creatorName = $row['userType'];
	  } else {
		 throw new Exception('No Id on File');	 
	  }
      
    } catch ( PDOException $e ) {
        // Write to error log or send an email to administrator:               
    }
  }	      
	
}
I have a utility file called utilities.inc.php and I just wanted point out that I put all my classes in a folder called classes, this way I don't have to worry about loading them in each php file that I create, I just make a new instance:

Code: Select all

<?php # utilities.inc.php

// Autoload classes from "classes" directory:
function class_loader($class) {
	require('classes/' . $class . '.php');
}
spl_autoload_register('class_loader');

header('Content-Type: text/html; charset=utf-8');
// Start the session:
session_start();

// Check for a user in the session:
$user = (isset($_SESSION['user'])) ? $_SESSION['user'] : NULL;

// Create the database connection as a PDO object:
try {
	
	$db_options = array(
		   PDO::ATTR_EMULATE_PREPARES => false                     // important! use actual prepared statements (default: emulate prepared statements)
		   , PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION           // throw exceptions on errors (default: stay silent)
		   , PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC      // fetch associative arrays (default: mixed arrays)
	   ); 		 
    
	$pdo = new PDO('mysql:host=localhost;dbname=cms;charset=utf8', 'root', '*****', $db_options);
	
	
} catch (PDOException $e) { // Report the Error!

	$pageTitle = 'Error!';
	include('includes/header.inc.php');
	include('views/error.html');
	include('includes/footer.inc.php');
	exit();
	
}
Well this thread post is getting a little long, so I call it quits for now, but feel free to leave a comment if you have any questions.

Post Reply
  • Information
  • Who is online

    Users browsing this forum: No registered users and 1 guest