Skip to content

Instantly share code, notes, and snippets.

@brabijan
Created June 4, 2013 13:47
Show Gist options
  • Save brabijan/5706051 to your computer and use it in GitHub Desktop.
Save brabijan/5706051 to your computer and use it in GitHub Desktop.
<?php
namespace Model\Repositories;
use Nette;
abstract class BaseRepository extends Nette\Object
{
/** @var Nette\Database\Connection */
protected $connection;
/**
* @param Nette\Database\Connection $db
*/
public function __construct(Nette\Database\Connection $db)
{
$this->connection = $db;
}
/**
* @return Nette\Database\Table\Selection
*/
protected function getTable()
{
preg_match('#(\w+)Repository$#', get_class($this), $m);
return $this->connection->table(lcfirst($m[1]));
}
/**
* @return Nette\Database\Table\Selection
*/
public function findAll()
{
return $this->getTable();
}
/**
* @return Nette\Database\Table\Selection
*/
public function findBy(array $by)
{
return $this->getTable()->where($by);
}
/**
* @param array $by
* @return Nette\Database\Table\ActiveRow
*/
public function findOneBy(array $by)
{
return $this->findBy($by)->limit(1)->fetch();
}
/**
* @param $id
* @return Nette\Database\Table\ActiveRow
*/
public function find($id)
{
return $this->getTable()->get($id);
}
}
<?php
/*
*
* Edit user
*
*/
public function actionEditUser($id)
{
try {
$this->selectedUser = $this->usersRepository->findUser($id);
} catch (\Model\Repositories\UserDoesNotExistException $e) {
$this->setView("notFound");
}
}
<?php
namespace Model\Repositories;
use Nette;
use Model;
class UsersRepository extends BaseRepository
{
public function findUser($id)
{
$user = $this->find($id);
if ($user === FALSE) {
throw new UserDoesNotExistException;
}
return $user;
}
public function findUsers()
{
return $this->findBy(array("removed" => FALSE));
}
public function findUserByEmail($email)
{
return $this->findOneBy(array("email" => $email));
}
public function addUser($email, $password, $role, $data)
{
if ($this->findUserByEmail($email) !== FALSE) {
throw new UserAlreadyExistException;
}
$password = Model\Authenticator::calculateHash($password);
$data["email"] = $email;
$data["password"] = $password;
$data["role"] = $role;
$data["registerDate"] = new Nette\DateTime();
$data["removed"] = FALSE;
$this->getTable()->insert($data);
}
public function editUser($userId, $data)
{
$user = $this->find($userId);
if ($user === FALSE) {
throw new UserDoesNotExistException;
}
if ($data["password"] == NULL) {
unset($data["password"]);
} else {
$data["password"] = Model\Authenticator::calculateHash($data["password"]);
}
unset($data["password2"]);
return $user->update($data);
}
public function deleteUser($userId)
{
return $this->findUser($userId)->update(array("removed" => TRUE));
}
}
class UserDoesNotExistException extends Nette\InvalidStateException
{
}
class UserAlreadyExistException extends Nette\InvalidStateException
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment