I've been developing sites using Dreamweaver for the last 15 years, I do a lot of code editing manually so I have quite a good knowledge of the PHP language.
I'm diving into object orientated programming and getting to grips with classes objects and the like.
I hope to eventually port the game to a framework such as symfony, I feel at this time there's a lot more to learn before I start diving into frameworks, and would just like to concentrate on getting to grips with OOP, without having to worry about templating frameworks, ORM etc.
The game itself is quite simple, its based on a party game called Mafia http://en.wikipedia.org/wiki/Mafia_(party_game)
There's a certain amount of players required, once enough players have joined, the game starts and people vote who they want to eliminate.
There are 2 periods of voting during the day and a night round where certain players can vote at night.
I've created the initial user login (for which I am using Facebook's PHP SDK).
I just wanted to get some advice on the best way to go before I get to far ahead of myself.
I think I am probably adding to much functionality to my game class
What's the best way to break it down?
Most of the data for the game is stored in a MySQL database, where I am using PDO (moving away from the horrendously insecure way that Dreamweaver implements).
Some of the questions I Have along the way are:
Do I create separate classes for the data in the database.
For example for my game table just have a class that fetches a list of games that i can then iterate through and display them as a list on my page.
within this class I can create methods to join a game, create a game, leave a game.
each method would return the game object $this
.
Have a class that contains a list of users in the current game, then within that class have methods for processing votes or do i have a separate class called gameFunctions that receives the current game, and list of users in that game with methods that perform the game functions such as voting.
I have already started working on it, and what I have so far is below, any tips or suggestions on how to separate the code so its more manageable would be great along with any other advice or resources that would be helpful to my learning process.
User Class:
<?php
require_once('facebook/facebook.php'); // require facebook sdk
require_once('config.class.php'); // require config class
require_once('dbconn.class.php'); //require database connector
class user{
public $_userData; // holds information of our user
private $conn; // our database connection
public $facebook; // facebook sdk
public $fbuser; // the facebook user
//Constructor
public function __construct(){
$this->conn = DBconn::getInstance(); //get DB instance
$this->facebook = new Facebook(Config::read('fb.facebook'));
$this->_userData = new stdClass();
}
/**
* CheckAccess - checks to see if the user is logged in to the session
* @return bool:
* true: user logged in
* false: user not logged in
*/
public function checkAccess(){
if(session_id() == '') {
session_start(); // Start session if we don't already have one
}
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
return true;
} else{
return false;
}
}
/**
* profileExists - Checks to see if a user profile exists
* @return bool: true/false
*/
private function profileExists(){
try{
$pdoQuery = ("SELECT count(*) FROM userprofile_upl WHERE uid_upl = :uid");
$stmt = $this->conn->dbh->prepare($pdoQuery);
$stmt->bindParam(':uid', $this->_userData->uid);
$stmt->execute();
if($stmt->fetchColumn()){
return true;
}else{
return false;
}
}catch(PDOException $e){
echo('There was an error while connecting to your profile<br>');
return false;
}
}
/**
* getProfile - querys the database and stores the users profile in $_userData
* @return bool
*/
public function getProfile(){
try{
$pdoQuery = ("SELECT
uid_upl as'uid',
firstname_upl as 'firstname',
lastname_upl as 'lastname',
info_upl as 'info'
FROM userprofile_upl
WHERE uid_upl = :uid"
);
$stmt = $this->conn->dbh->prepare($pdoQuery);
$stmt->bindParam(':uid', $this->_userData->uid);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_OBJ);
$this->_userData->firstname = $row->firstname;
$this->_userData->lastname = $row->lastname;
$this->_userData->info = $row->info;
return (true);
}catch(PDOException $e){
echo('There was an error while connecting to your profile<br>');
return false;
}
}
/**
* createProfile - Creates a user profile
* @param $user object: The Users Data
* @return bool: true/false
*/
private function createProfile(){
try{
//we need to add the facebook user to the profiles table
$pdoQuery = ('INSERT INTO userprofile_upl (firstname_upl, lastname_upl, uid_upl) VALUE (:firstname, :lastname, :uid)');
$pdoData = array(
'firstname' => $this->_userData->firstname,
'lastname' => $this->_userData->lastname,
'uid' => $this->_userData->uid
);
$stmt = $this->conn->dbh->prepare($pdoQuery);
$stmt->execute($pdoData);
return true;
}catch(PDOException $e){
echo('There was an error while creating the profile<br>');
return false;
}
}
/**
* goDashboard - Redirects a logged in user to the dashboard if they are logged in
*/
public function goDashboard(){
if($this->checkAccess()){
header('Location: '.Config::read('url.dashboard'));
}else{
return false;
}
}
/**
* generates a facebook log-out url
* @return String: facebook logout url
*/
public function getLogoutUrl(){
//set user logout_url
$params = array( 'next' => config::read('url.logout'));
$this->_userData->logout_url = $this->facebook->getLogoutUrl($params);
return $this->_userData->logout_url;
}
/**
* loginFacebook - Logs a user into the site with facebook
* Checks to see if user has an account and if not make one.
* Checks to see if user has a profile and if not make one.
* Checks to see if user has facebook credentials on this site
* @return mixed
*/
public function loginFacebook(){
$fbuser = $this->facebook->getUser();//get facebook user
if($fbuser){// if we have a user returned we have user who's authenticated and logged in with facebook
try { // Proceed knowing we have a user.
$me = $this->facebook->api('/me'); // the facebook user
//generate a log-out url
//set user logout_url
$this->_userData->logout_url = $this->facebook->getLogoutUrl($params);
//set the users details
$this->_userData->uid = $this->facebook->getUser();
$this->_userData->firstname = $me['first_name'];
$this->_userData->lastname = $me['last_name'];
$this->_userData->email = $me['email'];
$this->_userData->provider = 'facebook';
echo(" facebook account exists: ".$this->fbAccountExists());
if(!$this->fbAccountExists($this->_userData)){
echo("no fb account exists");
$this->fbCreateAccount($this->_userData);
};
echo("profile exists: ".$this->profileExists());
if(!$this->profileExists($this->_userData)){
echo("no profile exists: ");
$this->createProfile($this->_userData);
}
$this->setSession();
}
catch (FacebookApiException $e){ //if theres an error
$fbuser = null; //set the user to nothing
return false();
}
}
if(!$fbuser){
//get a login url, returns to this page so we can process the login($fblogin_url)
$loginUrl = $this->facebook->getLoginUrl(array('redirect_uri'=>Config::read('url.fblogin'), false));
header('Location: '.$loginUrl);//redirect to the login page
}
}
/**
* fbAccountExists - checks to see if a facebook account exists
* @return bool: true/false
*/
private function fbAccountExists(){
try{
$pdoQuery = ("SELECT count(*) FROM oauth_auth WHERE uid_auth = :uid and provider_auth = 'facebook'");
$stmt = $this->conn->dbh->prepare($pdoQuery);
$stmt->bindParam(':uid', $this->_userData->uid);
$stmt->execute();
if($stmt->fetchColumn()){
return true;
}else{
return false;
}
}catch(PDOException $e){
echo('There was an error while connecting to your profile<br>');
return false;
}
}
/**
* fbCreateAccount - creates a facebook account
* @return bool: true/false
*/
private function fbCreateAccount(){
try{
//we need to add the facebook user to the auth table
$pdoQuery = ("INSERT INTO oauth_auth(email_auth, uid_auth, provider_auth) VALUE (:email, :uid, :provider)");
$pdoData = array('email' => $this->_userData->email, 'uid' => $this->_userData->uid, 'provider' => $this->_userData->provider);
$stmt = $this->conn->dbh->prepare($pdoQuery);
$stmt->execute($pdoData);
return true;
}catch(PDOException $e){
echo('There was an error while connecting to your profile<br>');
return false;
}
}
/**
* setSession - Stores session variables to imitate user login.
*/
function setSession(){
if(session_id() == '') {session_start();}// Start session if we dont already have one
$_SESSION['loggedin'] = true;
$this->_userData->loggedin = true;
$_SESSION['uid'] = $this->_userData->uid;
$_SESSION['provider'] = $this->_userData->provider;
header('Location: '.Config::read('url.dashboard'));
}
/**
* getSession - saves session vars to our user
* @return bool: true - session retrieved
* @redirect if no session found redirects to login page
*/
public function getSession(){
if(session_id() == '') {session_start();}// Start session if we dont already have one
if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true) {//Check to see if user is logged in
header("location: ".Config::read('url.baseurl')); // User is logged in Redirect to homepage
}else{
//save session to this user
$this->_userData->loggedin = $_SESSION['loggedin'];
$this->_userData->provider = $_SESSION['provider'];
$this->_userData->uid = $_SESSION['uid'];
return true;
}
}
}
Game Class:
<?php
/**
* Created by Base5 Designs.
* and Dizzy Developments
* User: Dizzy High
* Date: 14/04/14
* Time: 12:08
*/
require_once('config.class.php'); // require config class
require_once('dbconn.class.php'); //require database connector
class game {
public $conn; // database handler
public $gameID; // id of game
public $name; //name of game
public $host; // uid of game host (the game creator)
public $playerCount; // number of players in game
public $roundTime; //round time of game in seconds
public $visibility; // public (1) or private game (0)
public $alias; // whether game players use an alias name or not (1 yes 2 no)
public $status; //status of game (waiting, active, complete)
public $currentRound; // current round of game (0 not started, odd day, even night)
public $startTime; // datetime - start time of game
public $createdTime; // datetime date game created
function __construct(){
$this->conn = DBconn::getInstance(); //get DB instance
}
/**
* assignSettings - assigns settings
* @param $name - property name
* @param $value - property value
*/
function assignSetting($name, $value){
$whitelist = array('id', 'name', 'host', 'playerCount', 'roundTime', 'visibility', 'alias', 'status', 'currentRound', 'startTime', 'createdTime');
if (in_array($name, $whitelist)) {
$property = $name;
$this->$property = $value;
}
}
/**
* makeGame- creates a new game and adds it to the database with the defined settings
* @param $settings
* @return bool
*/
function makeGame($settings){
//var_dump($settings);
if (is_array($settings)) {
foreach($settings as $k=>$v) {
$this->assignSetting($k, $v);
}
} else {
die('Config Error!');
}
try{
//add the game to the games table
$pdoQuery = ('INSERT INTO games_gam (name_gam, host_gam, playercount_gam, roundtime_gam, visibility_gam, alias_gam) VALUE (:gameName, :gameHost, :playerCount, :roundTime, :visibility, :alias)');
$pdoData = array(
'gameName' => $this->name,
'gameHost' => $this->host,
'playerCount' => $this->playerCount,
'roundTime' => $this->roundTime,
'visibility' => $this->visibility,
'alias' => $this->alias
);
var_dump($pdoData);
$stmt = $this->conn->dbh->prepare($pdoQuery);
$stmt->execute($pdoData);
$this->gameID = $this->conn->dbh->lastInsertId();
//add creator to game
$this->addPlayer($this->host);
return $this;
}catch(PDOException $e){
echo('There was an error while creating the game<br>');
return false;
}
}
/**
* getGame - retrieves a game from the database
* @param $gameID INT - the id of the game
* @return $this
*/
function getGame($gameID){
try{
$pdoQuery = ("SELECT
id_gam as 'id',
name_gam as 'name',
host_gam as 'host',
playercount_gam as 'playerCount',
roundtime_gam as 'roundTime',
visibility_gam as 'visibility',
status_gam as 'status',
alias_gam as 'alias',
starttime_gam as 'startTime',
createdtime_gam as 'createdTime'
FROM games_gam
WHERE id_gam = :id"
);
$stmt = $this->conn->dbh->prepare($pdoQuery);
$stmt->bindParam(':id', $gameID);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_OBJ);
$this->gameID = $row->id;
$this->name = $row->name;
$this->host = $row->host;
$this->playerCount = $row->playerCount;
$this->roundTime = $row->roundTime;
$this->visibility = $row->visibility;
$this->status = $row->status;
$this->alias = $row->alias;
$this->startTime = $row->startTime;
$this->createdTime = $row->createdTime;
return ($this);
}catch(PDOException $e){
echo('There was an error while connecting to game: '.$gameID.'<br>');
return false;
}
}
/**
* addPlayer - adds player to a game
* @param $uid - uid of player
* @return bool
*/
function addPlayer($uid){
if(!$this->playerInGame($uid)){
try{
$pdoQuery = ('INSERT INTO gameplayers_gpl (idgam_gpl, uid_gpl) VALUE (:idgam, :uid)');
$pdoData = array(
':idgam' => $this->gameID,
':uid' => $uid
);
$stmt = $this->conn->dbh->prepare($pdoQuery);
$stmt->execute($pdoData);
return true;
}catch(PDOException $e){
echo('There was an error while creating the profile<br>');
return false;
}
}
}
/**
* leaveGame - Removes a player from a game
* @param $gameID - the id of the game
* @param $uid - the uid of the player
* @return $this
*/
function leaveGame($uid){
if($this->playerInGame($uid)){
try{
$pdoQuery = ('DELETE FROM gameplayers_gpl WHERE uid_gpl = :uid AND idgam_gpl = id');
$pdoData = array(
':uid' => $uid,
':id'=> $this->$gameID
);
$stmt = $this->conn->dbh->prepare($pdoQuery);
$stmt->execute($pdoData);
return $this;
}catch(PDOException $e){
echo('There was an error while removing the player from the game<br>');
return false;
}
}
}
/**
* gameFull - checks to see if a game has all player slots filled
* @return bool true: game is full
* @return bool false: has slots
*/
function gameFull(){
try{
$pdoQuery = ("SELECT count(*) FROM gameplayers_gpl WHERE idgam_gpl = :gameID");
$stmt = $this->conn->dbh->prepare($pdoQuery);
$stmt->bindParam(':gameID', $this->gameID);
$stmt->execute();
$rowCount = (int) $stmt->fetchColumn();
if($rowCount < $this->playerCount){
return false;
}else{
return true;
}
}catch(PDOException $e){
echo('There was an error while checking if the game was full<br>');
return false;
}
}
/**
* playerInGame - checks to see if a player in the game
* @param $uid: id of user
* @return bool
*/
function playerInGame($uid){
try{
$pdoQuery = ("SELECT count(*) FROM gameplayers_gpl WHERE idgam_gpl = :gameID AND uid_gpl = :uid");
$stmt = $this->conn->dbh->prepare($pdoQuery);
$pdoData = array(
':uid' => $uid,
':gameID'=> $this->gameID
);
$stmt->execute($pdoData);
$rowCount = (int) $stmt->fetchColumn();
if($rowCount > 0){
return true;
}else{
return false;
}
}catch(PDOException $e){
echo('There was an error while checking if the user was in the game<br>');
return false;
}
}
function getGamesList($roundtime){
try{
$pdoQuery = ("SELECT
id_gam as 'id',
name_gam as 'name',
host_gam as 'host',
playercount_gam as 'playerCount',
roundtime_gam as 'roundTime',
visibility_gam as 'visibility',
status_gam as 'status',
alias_gam as 'alias',
starttime_gam as 'startTime',
createdtime_gam as 'createdTime'
FROM games_gam
WHERE visibility_gam = :visibility AND roundtime_gam = :roundtime AND status_gam = :gamestatus"
);
$stmt = $this->conn->dbh->prepare($pdoQuery);
$pdoData = array(
'visibility' => 0,
'roundtime' => $roundtime,
'gamestatus' => 'waiting',
);
$stmt->execute($pdoData);
$obj = $stmt->fetchAll();
return ($obj);
}catch(PDOException $e){
echo('There was an error while connecting to game: '.$gameID.'<br>');
return false;
}
}
/**
* Convert number of seconds into years, days, hours, minutes and seconds
* and return an string containing those values
*
* @param integer $seconds Number of seconds to parse
* @return string
*/
function secondsToTime($seconds){
$y = floor($seconds / (86400*365.25));
$d = floor(($seconds - ($y*(86400*365.25))) / 86400);
$h = gmdate('H', $seconds);
$m = gmdate('i', $seconds);
$s = gmdate('s', $seconds);
$string = '';
if($y > 0){
$yw = $y > 1 ? ' years ' : ' year ';
$string .= $y . $yw;
}
if($d > 0){
$dw = $d > 1 ? ' days ' : ' day ';
$string .= $d . $dw;
}
if($h > 0){
$hw = $h > 1 ? ' hours ' : ' hour ';
$string .= $h . $hw;
}
if($m > 0){
$mw = $m > 1 ? ' minutes ' : ' minute ';
$string .= $m . $mw;
}
if($s > 0){
$sw = $s > 1 ? ' seconds ' : ' second ';
$string .= $s . $sw;
}
return preg_replace('/\s+/',' ',$string);
}
function getHost($gameID){
}
function initGame(){
}
function processVotes(){
}
function setPlayerRole($uid, $role){
}
function getPlayerRole(){
}
function getPlayerHealth(){
}
function getGameDay(){
}
function getGameVotes(){
}