I'm new to OO PHP and I'm trying to create a simple properly-designed user authentication system.
- What am I doing right and what not?
- Is this right according to the MVC model?
Connection.class.php
<?php
class Connection {
private $host = 'host';
private $name = 'name';
private $user = 'user';
private $pass = 'pass';
public $con;
function __construct() {
try {
$this->con = new PDO("mysql:host=$this->host;dbname=$this->name;charset=utf8", $this->user, $this->pass);
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex) {
die('Failed trying to connect to the database');
}
}
}
User.class.php
<?php
class User {
private $id;
private $username;
private $email;
private $password;
function __construct($id, $username, $email, $password) {
$this->id = $id;
$this->username = $username;
$this->email = $email;
$this->password = $password;
}
function getId() {
return $this->id;
}
function getUsername() {
return $this->username;
}
function getEmail() {
return $this->email;
}
function getPassword() {
return $this->password;
}
}
UserService.class.php
<?php
class UserService {
protected $db;
public function __construct($db) {
$this->db = $db;
}
public function login($email, $password) {
$stmt = $this->db->con->prepare('SELECT * FROM user WHERE email = ?');
$stmt->execute(array($email));
if ($stmt->rowCount() > 0) {
//Check password here
//Return user object and set session on success
//$user = $stmt->fetchObject('User');
$user = $stmt->fetch(PDO::FETCH_ASSOC);
return new User($user['id'], $user['username'], $user['email'], $user['password']);
}
return false;
}
public function logout() { }
public function register() { }
public function getUser($userId) {
$stmt = $this->db->con->prepare('SELECT * FROM user WHERE id = ?');
$stmt->execute(array($userId));
if ($stmt->rowCount() > 0) {
return $stmt->fetch(PDO::FETCH_ASSOC);
}
return false;
}
}
Example usage
//Include class files
$userService = new UserService($db);
if ($user = $userService->login('[email protected]', 'testPass')) {
echo 'Logged in as: ' . $user->getEmail();
} else {
echo 'Invalid login';
}