Created
February 23, 2011 20:18
-
-
Save pentikos/841100 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class User | |
{ | |
protected $id; | |
protected $name; | |
public function setId($id) | |
{ | |
$this->id = $id; | |
} | |
public function getId() | |
{ | |
return $this->id; | |
} | |
public function setName($name) | |
{ | |
$this->name = $name; | |
} | |
public function getName() | |
{ | |
return $this->name; | |
} | |
} | |
class UserRepository | |
{ | |
protected $pdo; | |
public function __construct(Pdo $pdo) | |
{ | |
$this->pdo = $pdo; | |
} | |
public function fetchAll() | |
{ | |
$statement = $this->pdo->prepare('SELECT * FROM user'); | |
$statement->execute(); | |
$users = array(); | |
foreach($statement->fetchAll() as $user_row) | |
{ | |
$user = new User(); | |
$user->setId($user_row['id']); | |
$user->setName($user_row['name']); | |
$users[] = $user; | |
} | |
return $users; | |
} | |
public function save(User $user) | |
{ | |
// Dit gaat een nieuw record worden aangezien de ID eigenlijk door de database gezet moet worden | |
if (null === $user->getId()) | |
{ | |
$statement = $this->pdo->prepare('INSERT INTO user (name) VALUES (:name)'); | |
$statement->bindParam(':name', $user->getName(), PDO::PARAM_STR,50); | |
$statement->execute(); | |
$user->setId($this->pdo->lastInsertId()); | |
} | |
else | |
{ | |
$statement = $this->pdo->prepare('UPDATE user SET name=:name WHERE id=:id'); | |
$statement->bindParam(':name', $user->getName(), PDO::PARAM_STR,50); | |
$statement->bindParam(':id', $user->getId(), PDO::PARAM_INT); | |
$statement->execute(); | |
} | |
} | |
} | |
$pdo = new PDO('mysql:dbname=test;host=localhost', 'root',''); | |
$userRepository = new UserRepository($pdo); | |
$user = new User(); | |
$user->setName('Don'); | |
$userRepository->save($user); | |
$user->setName('Gerritjan'); | |
$userRepository->save($user); | |
foreach($userRepository->fetchAll() as $user) | |
{ | |
echo $user->getName(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment