Essa palestra foi feita no TDC 2016 na trilha de PHP Architecture onde a idéia principal é mostrar como aplicar boas práticas e organização de código para atender as necessidades do negócio com uso de uma linguagem simples e autoexplicativa.
8. Globalcode – Open4education
user story
Lista de Desejos
Eu como usuário convidado, quero adicionar um produto
esgotado em minha lista de desejos para que eu receba uma
notificação quando este estiver disponível.
Objetivo
reposição mais inteligente de produtos
21. Globalcode – Open4education
php estruturado
function isValidWishList(array $data);
function getWishList(array $data);
function findAllWishProducts($email);
function addWishItem(array $data);
function removeWishItem($id);
function findAllWishlistsToNotify();
function wishlistNotified($id);
28. Globalcode – Open4education
php estruturado
Without a front controller
GET /wishlist.php?email=email@test.com
With index.php as the front controller
GET /index.php/wishlist/email@test.com
29. Globalcode – Open4education
php puro front controller
// public/index.php
// load function files
// route the request internally
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$method = $_SERVER['REQUEST_METHOD'];
if (preg_match('/wishlist/(.*)$', $uri, $matches) && $method == 'GET') {
wishlistListAction($matches[1]);
} elseif ('/index.php/wishlist/add' === $uri && $method == 'POST') {
wishlistAddAction($_GET['email'], $_POST);
} else {
header('HTTP/1.1 404 Not Found');
echo '<html><body><h1>Page Not Found</h1></body></html>';
}
37. Globalcode – Open4education
php business testes automatizados
garantem regras conhecidas
auxiliam refatoração
não evitam bugs
38. Globalcode – Open4education
php business phpunit
PHPUnit 5.4.6 by Sebastian Bergmann and contributors.
................................................... 59 / 59 (100%)
Time: 349 ms, Memory: 6.00MB
OK (59 tests, 126 assertions)
39. Globalcode – Open4education
PHPUnit 5.4.6 by Sebastian Bergmann and contributors.
..................................F................ 59 / 59 (100%)
Time: 374 ms, Memory: 6.00MB
There was 1 failure:
1) ProductTest::testUpdateProductFailed
Failed asserting that exception of type "ProductException" is
thrown.
FAILURES!
Tests: 59, Assertions: 125, Failures: 1.
php business phpunit
43. Globalcode – Open4education
php business objetos de valor
são objetos simples
encapsulam tipos primitivos
representam o valor
44. Globalcode – Open4education
class Status
{
const PENDING = 'P';
const SENT = 'S';
public function __construct($status)
{
$this->validate($status);
$this->status = $status;
}
// … other methods
public function equalsTo(Status $status)
{
return $status === $this;
}
}
php business objetos de valor
51. Globalcode – Open4education
interface WishlistRepository
{
public function find($id);
public function findAllByEmail($email);
public function add(Wishlist $wishlist);
public function delete(Wishlist $wishlist);
public function findAllToNotify();
}
php business repositórios
52. Globalcode – Open4education
namespace DevelopBusinessApplicationProductWishlistRepositories;
class PdoRepository implements WishlistRepository
{
public function __construct(PDO $driver, Factory $factory);
public function findAllByEmail($email)
{
$query = "find all items by email";
$stm = $this->driver->prepare($query);
$stm->execute([$email]);
return $stm->fetchAll(
PDO::FETCH_FUNC,
[$this->factory, 'create']
);
}
}
php business repositórios
53. Globalcode – Open4education
namespace DevelopBusinessApplicationProductWishlistRepositories;
class RedisRepository implements WishlistRepository
{
public function __construct(Predis $driver, Factory $factory);
public function find($id)
{
$wishlist = $this->driver->get($this->getKey($id));
if (!$wishlist) {
throw WishlistNotFoundException::byIdentifier($id);
}
return $this->factory->fromJson($wishlist);
}
}
php business repositórios
54. Globalcode – Open4education
class PdoRepositoryTest extends PHPUnit_Framework_TestCase
{
public function testAddNewRowSuccessful()
{
$wishlist = $this->factory->fromQueryResult(/* args */);
$pdoSpy = new PDOSpy();
(new Repository($pdoSpy))->add($wishlist);
$this->assertTrue($pdoSpy->beginTransactionCalled);
$this->assertTrue($pdoSpy->commitCalled);
$this->assertEquals(2, $wishlist->getId());
}
}
php business repositórios
55. Globalcode – Open4education
class PDOSpy extends PDO
{
public function beginTransaction()
{
$this->beginTransactionCalled = true;
}
public function prepare($statement, $options = null)
{
if ($statement == INSERT INTO wishlists VALUES (?, ?, ?)') {
return new WriteStatementStub($this->failureOnWrite);
}
throw new InvalidArgumentException(
"None Stub Statement was found for query: {$statement}"
);
}
}
php business repositórios
56. Globalcode – Open4education
function wishlistListAction($email)
{
$db = dbConnect();
$factory = new WishlistFactory();
$repository = new WishlistPdoRepository($db, $factory);
$wishlist = $repository->findAllByEmail($email);
include TEMPLATE_DIR . '/wishlists/list.php';
}
php business repositórios
72. Globalcode – Open4education
class UpdateProductUseCase
{
public function __construct($repository, $factory, $eventDispatcher);
public function execute(Intention $intention)
{
// do something
$this->repository->update($updatedProduct);
$event = new ProductWasUpdated($updatedProduct);
$this->dispatch('product.updated', $event);
if ($this->isStockIncreased($product, $updatedProduct)) {
$this->dispatch('product.stock.increased', $event);
}
return $updatedProduct;
}
}
php business eventos
73. Globalcode – Open4education
class StockListener
{
public function __construct(NotifyProductAvailable $useCase);
public function __invoke(ProductStockIncreasedEvent $event)
{
$productId = $event->getProduct()->getId();
$intention = new NotifyProductIntention($productId);
$this->useCase->execute($intention);
}
}
php business eventos
83. Globalcode – Open4education
Implementing Domain-Driven Design
by Vaughn Vernon
Patterns of Enterprise Application Architecture
by Martin Fowler
Domain-Driven Design
by Eric Evans
DDD in PHP
by Carlos Buenosvinos, Christian Soronellas and Keyvan Akbary
referências