mirror of
https://github.com/DesignPatternsPHP/DesignPatternsPHP.git
synced 2025-08-02 13:07:27 +02:00
some more code examples
This commit is contained in:
@@ -10,10 +10,18 @@ namespace DesignPatterns;
|
|||||||
|
|
||||||
$userMapper = new UserMapper();
|
$userMapper = new UserMapper();
|
||||||
|
|
||||||
$user = $userMapper->find(1);
|
// fetch a record from Database
|
||||||
|
$user = $userMapper->findById(1);
|
||||||
|
|
||||||
if ($user !== null) {
|
if ($user !== null) {
|
||||||
echo "Hello " . $user->getUsername() . ". Your email is " . $user->getEmail();
|
echo "Hello " . $user->getUsername() . ". Your email is " . $user->getEmail();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// save a new record on Database
|
||||||
|
var $newUser = new User('', 'Odysseus', 'Odysseus@ithaca.gr');
|
||||||
|
$userMapper->save($newUser);
|
||||||
|
|
||||||
|
// fetch all from a table on Database
|
||||||
|
var $user = $userMapper->findAll();
|
||||||
|
|
||||||
?>
|
?>
|
@@ -14,11 +14,11 @@ class User
|
|||||||
protected $username;
|
protected $username;
|
||||||
protected $email;
|
protected $email;
|
||||||
|
|
||||||
public function __construct(array $options = null)
|
public function __construct($id, $username, $email)
|
||||||
{
|
{
|
||||||
if (is_array($options)) {
|
$this->id = $id;
|
||||||
$this->setOptions($options);
|
$this->username = $username;
|
||||||
}
|
$this->email = $email;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getUserId() {
|
public function getUserId() {
|
||||||
|
@@ -31,8 +31,8 @@ class UserMapper
|
|||||||
/**
|
/**
|
||||||
* create new Database connector on $_adapter using specific table
|
* create new Database connector on $_adapter using specific table
|
||||||
*
|
*
|
||||||
* $_adapter var could be a specific to a table class or a generic interface for
|
* $_adapter var could be a specific to a table class or a generic
|
||||||
* connecting to Database and do certain jobs
|
* interface for connecting to Database and do certain jobs
|
||||||
*/
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,12 +43,14 @@ class UserMapper
|
|||||||
*/
|
*/
|
||||||
public function save(User $user)
|
public function save(User $user)
|
||||||
{
|
{
|
||||||
|
// $data keys shoulds correspond to valid Table columns on the Database
|
||||||
$data = array(
|
$data = array(
|
||||||
'userid' => $user->getUserId(),
|
'userid' => $user->getUserId(),
|
||||||
'username' => $user->getUsername(),
|
'username' => $user->getUsername(),
|
||||||
'email' => $user->getEmail(),
|
'email' => $user->getEmail(),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// if no ID specified create new user else update the one in the Database
|
||||||
if (null === ($id = $user->getUserId())) {
|
if (null === ($id = $user->getUserId())) {
|
||||||
unset($data['userid']);
|
unset($data['userid']);
|
||||||
$this->_adapter->insert($data);
|
$this->_adapter->insert($data);
|
||||||
|
Reference in New Issue
Block a user