Skip to content

Instantly share code, notes, and snippets.

@cythrawll
Last active October 7, 2015 07:48
Show Gist options
  • Save cythrawll/3130241 to your computer and use it in GitHub Desktop.
Save cythrawll/3130241 to your computer and use it in GitHub Desktop.
Example of three layered Service
<?php
class Author extends Entity {
public $name;
public $penNames;
}
<?php
class AuthorDao extends Dao {
public function getBooks($id) {
$stmt = $this->db->prepare('...');
$stmt->execute(array($id));
return SomeMapper::mapResultToBooks($stmt);
}
public function updateAuthor(Author $author) {
$stmt = $this->db->prepare('..');
$stmt->execute(array($author->name, $author->penNames));
}
}
<?php
interface AuthorService {
public function getBooksByAuthor($id);
public function updateAuthor(Author $author);
}
class AuthorServiceDaoImpl implements AuthorService {
private $authorDao;
public function getAuthorDao(AuthorDao $dao) {
$this->authorDao = $authorDao;
}
public function getBooks($id) {
return $this->authorDao->getBooks($id);
}
public function updateAuthor(Author $author) {
try {
$this->authorDao->getDB()->startTransaction();
$this->authorDao->updateAuthor($author);
$this->authorDao->commit();
} catch(Exception $ex) {
$this->authorDao->getDB()->rollback();
throw $ex;
}
}
}
<?php
//omitting setting exception mode, don't forget it!
$db = new PDO(...);
$authorDao = new AuthorDao($db);
$authorService = new AuthorServiceDaoImpl($authorDao);
$authorService->getBooks($author->getPrimaryKey());
//tip: you can simplify construction by using a Builder pattern, or a Factory pattern if you want to handle more than one implementation of the service.
<?php
class Dao {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
public function getDB() {
return $this->db;
}
}
<?php
class Entity {
private $primaryKey;
public getPrimaryKey() {
return $this->primaryKey;
}
public setPrimaryKey($primaryKey) {
$this->primaryKey = $primaryKey;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment