Jump to content

Can't call multiple functions in Class from Controller


avargas94

Recommended Posts

I am currently building my own MVC Framework and I have run into an issue that I can't solve when attempting to use 2 methods from a single model. I know that this isn't an issue with the queries or information being return. I am unsure of the proper way that I can call 2 methods when checking to see if a user is logged in... The issue that I face is both methods are calling the DB and it throws a PDO error which I don't know how to get around the issue.. Any guidance would be nice as I have been banging my head over this issue. Thank you!

 

Fatal error: Uncaught Error: Call to undefined method PDO::Select() in C:\xampp\htdocs\PicWrist\app\models\user.class.php:318 Stack trace: #0 C:\xampp\htdocs\PicWrist\app\controllers\home.php(21): User->getUser('4') #1 C:\xampp\htdocs\PicWrist\app\core\app.php(36): Home->index() #2 C:\xampp\htdocs\PicWrist\app\init.php(47): App->__construct() #3 C:\xampp\htdocs\PicWrist\public\index.php(5): require('C:\\xampp\\htdocs...') #4 {main} thrown in C:\xampp\htdocs\PicWrist\app\models\user.class.php on line 318

 

//Controller

<?php 
	/**
	 * Load the View
	 */
	class Controller{

		public function view($view, $data = []) {
			if (file_exists('../app/views/' . $view . '.php')) {
				require_once '../app/views/' . $view . '.php';
			} 
		}

		public function model($model, $data = []) {

			if (file_exists('../app/models/' . $model . '.class.php')) {
				require_once '../app/models/' . $model . '.class.php';

				return new $model();

			} else 

				return false;
		}
	}

?>

//Home Controller
<?php 
Class Home extends Controller {

	public static $user;
	public $errors;

	public function __construct() {

		self::$user = $this->model('user');

	}

	public function index() {
		$userdata 			= [];
		$data				= [];

		show(self::$user);
		$isLoggedin	= self::$user->isLoggedin;
		show($isLoggedin);

		$userdata = self::$user->getUser($_SESSION['user_id']);
		show($userdata);

		$this->view('home', $data);
	}

}

?>
<?php 
/**
 * Users
 */
class User
{
	private $db;
	private $errors = '';
	public $isLoggedin = False;
	public $isAdmin = False;

	public function __construct() {
		$this->isLoggedIn();
	}

	public function isLoggedIn() {

		if(isset($_SESSION['user_id'])){

			$data['user_id'] = $_SESSION['user_id'];
			$db = Database::getInstance();
			$query = "SELECT * FROM users WHERE user_id = :user_id LIMIT 1";
			$results = $db->Select($query, $data);

			if (is_array($results)) {
				 $this->isLoggedIn = True;
			}
		}

	}


	public function getUser($id) {

		if(isset($id)) {

			$data['user_id']	= intval($id);
			$db 				= Database::getInstance();
			$query 				= 'SELECT * FROM users WHERE user_id = :user_id';

			$results = $db->Select($query, $data);

			if (is_array($results)) {
				return $results;
			} else {
				return False;
			}
		} else {
			return False;
		}
	}

//DB
<?php 
	/**
	 * Database Connection
	 */
	class Database	{
		private $dbHost = DB_HOST;
		private $dbUser = DB_USER;
		private $dbPass = DB_PASS;
		private $dbName = DB_NAME;

		private $statment;
		private static $dbHandler;
		private $error;

		public function __construct()
		{
			$conn = 'mysql:host=' . $this->dbHost . ';dbname=' . $this->dbName;

			$options = array(
				PDO::ATTR_PERSISTENT 	=> true,
				PDO::ATTR_ERRMODE 		=> PDO::ERRMODE_EXCEPTION
			);

			try {
				self::$dbHandler = new PDO($conn, $this->dbUser, $this->dbPass, $options);
			} catch (PDOException $e) {
				self::$error = $e->getMessage();
				echo self::$error;
			}
		}

		public static function getInstance() {

			if(self::$dbHandler) {
				return self::$dbHandler;
			}

			return $instance = new Self();
		}

		public function Select($query, $data = array()) {
			$statement = self::$dbHandler->prepare($query);
			$result	= $statement->execute($data);

			If($result) {
				$data = $statement->fetchAll(PDO::FETCH_OBJ);
					if(is_array($data)) {
						// show($data);
						return $data;
				}
			}

			return False;
		}

		public function Update($query, $data = array()) {
			$statement = self::$dbHandler->prepare($query);
			$result	= $statement->execute($data);

			If($result) {
				return True;
			} 
			
			return False;

		}

	}

?>

 

Edited by avargas94
Wrong Code
Link to comment
Share on other sites

public static function getInstance() {
  if(self::$dbHandler) {
	  return self::$dbHandler;
  }

  return $instance = new Self();
}

This code is incorrect.  When you first call this function you will return $instance which is an instance of your Database class.  Every subsequent time you call it you will return self::$dbHandler which is an instance of PDO.

You need to save $instance on the object (ie, self::$instance) and check if that exists and return it.  Your self::$dbHandler should just be a normal instance variable ($this->dbHandler) not a static one.

Link to comment
Share on other sites

16 minutes ago, kicken said:
public static function getInstance() {
  if(self::$dbHandler) {
	  return self::$dbHandler;
  }

  return $instance = new Self();
}

This code is incorrect.  When you first call this function you will return $instance which is an instance of your Database class.  Every subsequent time you call it you will return self::$dbHandler which is an instance of PDO.

You need to save $instance on the object (ie, self::$instance) and check if that exists and return it.  Your self::$dbHandler should just be a normal instance variable ($this->dbHandler) not a static one.

Okay so I will remove the static and update everything the $this->dbHandler and I updated the getInstance() section as you stated.. Thank you!

public static function getInstance() {

  if(self::$instance) {
  	return self::$instance;
  }

  return self::$instance = new Self();
}

 

Edited by avargas94
Link to comment
Share on other sites

5 minutes ago, avargas94 said:

Where would the correct place to save the $instance the the object?

You do essentially what you were doing with $dbHandler.  You had the right idea, just the wrong details.

private static $instance = null;

//...

public static function getInstance() {
  if(self::$instance) {
	  return self::$instance;
  }

  return self::$instance = new Self();
}

 

  • Like 1
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.