PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL

iMasters
iMastersjornalista, web editor, web writer, tradutora (en-pt/pt-en) at iMasters
MELHORANDO
SUA API COM
DSLS@augustohp
DOMAIN SPECIFIC LANGUAGE
A SEGUIR,
UMA
DSL
VALIDAÇÃO
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL
1 <?php
2
3 use RespectValidationValidator as v;
4
5 v::stringType()
6 ->exactLength(8)
7 ->contains("-")
8 ->contains("/^[A-Z]{3}/")
9 ->contains("/[0-9]{4}$/")
10 ->assert($something);
1 <?php
2
3 namespace EasyTaxiValidationRules;
4
5 use RespectValidationRules as BaseRules;
6
7 class CarPlate extends BaseRulesAllOf
8 {
9 public function __construct()
10 {
11 $this->name = 'Brazilian car plate';
12
13 parent::__construct(
14 new BaseRulesStringType(),
15 new ExactLength(8),
16 new BaseRuleContains("-")->setName('Separator'),
17 new BaseRuleContains("/^[A-Z]{3}/")->setName("Prefix")
18 new BaseRuleContains("/^[0-9]{4}/")->setName("Sufix")
19 );
20 }
21 }
1 <?php
2
3 namespace EasyTaxiValidationRules;
4
5 use RespectValidationRules as BaseRules;
6
7 class CarPlate extends BaseRulesAllOf
8 {
9 public function __construct()
10 {
11 $this->name = 'Brazilian car plate';
12
13 parent::__construct(
14 new BaseRulesStringType(),
15 new ExactLength(8),
16 new BaseRuleContains("-")->setName('Separator'),
17 new BaseRuleContains("/^[A-Z]{3}/")->setName("Prefix")
18 new BaseRuleContains("/^[0-9]{4}/")->setName("Sufix")
19 );
20 }
21 }
1 <?php
2
3 // ... dentro de algum método de um Controller ...
4
5 ValidationValidator::arrayType()
6 ->key('driver_name', v::driverName())
7 ->key('driver_birthdate', v::minimumAge(18))
8 ->key(
9 'driver_car', v::arrayType(
10 v::key("model", v::carModel($this->get('model.vehicle'))),
11 v::key("assembler", v::carAssembler()),
12 v::key("year", v::maximumAge(5)),
13 v::key("plate", v::carPlate())
14 )
15 )
16 ->key('license_number', v::driverLicense())
17 ->key('taxi_permission', v::taxiPermissionNumber())
18 ->key('address', v::address())
19 ->assert($_POST);
COMO
CRIAR
ISSO?
1 <?php
2
3 namespace RespectValidation;
4
5 class Validator
6 {
7 public function stringType() {}
8 public function contains($search) {}
9 public function assert($mixed) {}
10 }
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL
1 <?php
2
3 namespace RespectValidation;
4
5 interface Rule
6 {
7 public function isValid($mixed): bool;
8 }
IMPLEMENTANDO
UMA
REGRA
1 <?php
2
3 namespace RespectValidationRules;
4
5 use RespectValidation;
6
7 class StringType implements ValidationRule
8 {
9 public function isValid($mixed): bool
10 {
11 return is_string($mixed);
12 }
13 }
3 namespace RespectValidationRules;
4
5 use RespectValidation;
6
7 class AllOf implements ValidationRule
8 {
9 protected $rules = [];
10
17 public function __construct(ValidationRule ...$rules)
18 {
19 $this->rules = $rules;
20 }
21
22 public function isValid($mixed): bool
23 {
24 foreach ($this->rules as $rule) {
25 if (false === $rule->isValid($mixed)) {
26 return false;
27 }
28 }
29
30 return true;
31 }
32 }
INSTANCIANDO
REGRAS
1 <?php
2
3 $factory = new RespectValidationRuleFactory;
4 $rule = $factory->createInstance('StringType');
1 <?php
2
3 namespace RespectValidation;
4
5 class RuleFactory
6 {
7 public function createInstance($ruleName, array $args = []): Rule
8 {
9 $ruleNamespace = 'RespectValidationRules';
10 $className = $ruleNamespace . $rule;
11 $reflection = new ReflectionClass($className);
12
13 return $reflection->newInstanceArgs($args);
14 }
15 }
PODEMOS
TER
MENOS
CÓDIGO ?
1 <?php
2
3 namespace RespectValidation;
4
5 class RuleFactory
6 {
7 public function __call($methodName, $methodArguments)
8 {
9 return $this->createInstance($methodName, $methodArguments);
10 }
11
12 public function createInstance($ruleName, array $args = []): Rule
13 {
14 /* ... */
15 }
16 }
1 <?php
2
3 $checkFor = new RespectValidationRuleFactory;
4
5 $isString = $checkFor->StringType();
6
7 $isTwitterUserName = $checkFor->AllOf(
8 $checkFor->AlNum(),
9 $checkFor->NoWhitespace(),
10 $checkFor->Length(1, 15)
11 );
PODEMOS
TER
MENOS
CÓDIGO ?
3 namespace RespectValidation;
4
5 class RuleFactory
6 {
7 private static $factory = null;
8
9 public static function getInstance()
10 {
11 if (is_null(self::$factory)) {
12 self::$factory = new static;
13 }
14
15 return self::$factory;
16 }
17
18 public static function __callStatic($methodName, $methodArguments)
19 {
20 $factory = self::getFactory();
21
22 return $factory->createInstance($methodName, $methodArguments);
23 }
24
25 /* ... */
26 }
1 <?php
2
3 use RespectValidationRuleFactory as v;
4
5 $isTwitterUserName = v::AllOf(
6 v::AlNum(),
7 v::NoWhitespace(),
8 v::Length(1, 15)
9 );
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL
@ANNOTATION
O QUE TEMOS
1 <?php
2
3 namespace EasyTaxiValidation;
4
5 interface Rule
6 {
7 public function isValid($mixed): bool;
8 }
1 <?php
2
3 namespace EasyTaxiValidationRules;
4
5 use EasyTaxiValidation;
6 use RespectValidationValidator as v;
7
8 class PlateValidator implements Rule
9 {
10 public function isValid($mixed): bool
11 {
12 return v::stringType()
13 ->exactLength(8)
14 ->contains("-")
15 ->contains("/^[A-Z]{3}/")
16 ->contains("/[0-9]{4}$/")
17 ->setName('Car plate')
18 ->validate($mixed);
19 }
20 }
O QUE QUEREMOS
1 <?php
2
3 namespace EasyTaxiDriver;
4
5 class Car
6 {
7 /**
8 * @PlateValidator
9 */
10 private $plate = '';
11
12 public function __construct($plate)
13 {
14 $this->plate = $plate;
15 }
16 }
1 <?php
2
3 use EasyTaxiAnnotation;
4 use EasyTaxiValidation;
5
6 $filter = new AnnotationFilter();
7 $factory = new AnnotationFactory($filter);
8 $validator = new ValidationValidator($factory);
9 $fusca = new Car('AAA-1111');
10
11 $validator->annotations($fusca);
FILTRANDO
A PARTE
INTERESSANTE
DE UM
COMENTÁRIO
1 <?php
2
3 namespace EasyTaxiAnnotation;
4
5 class Filter
6 {
7 public function firstAnnotation($doc): string {
8 foreach ($this->breakLines($doc) as $line) {
9 if (false === $this->hasAnnotation($line)) {
10 continue;
11 }
12
13 return $this->filterName($line);
14 }
15 }
16
17 private function breakLines($doc): array {
18 return explode(PHP_EOL, $doc);
19 }
20
21 private function hasAnnotation($line): bool {
22 return false !== strpos($line, '@');
23 }
24
25 private function filterName($line): string {
26 return trim(str_replace(['*', '/', '@'], '', $line));
27 }
28 }
CRIANDO
REGRAS A PARTIR
DE UM
COMENTÁRIO
3 namespace EasyTaxiAnnotation;
4
5 class Factory
6 {
7 private $filter = null;
8
9 public function __construct(Filter $annotationFilter)
10 {
11 $this->filter = $annotationFilter;
12 }
13
14 public function createFromProperty($instance, $propertyName)
15 {
16 $object = new ReflectionObject($instance);
17 $property = $object->getProperty($propertyName);
18
19 return $this->createInstanceFromComment($property->getDocComment());
20 }
21
22 private function createInstanceFromComment($doc)
23 {
24 $annotationClass = $this->filter->firstAnnotation($doc);
25 $class = new ReflectionClass($annotationClass);
26
27 return $class->newInstance();
28 }
29 }
JUNTANDO
TUDO
NUM
MONTINHO
SÓ
3 namespace EasyTaxiValidation;
4
5 use EasyTaxiAnnotation;
6
7 class Validator
8 {
9 private $annotationFactory = null;
10
11 public function __construct(AnnotationFactory $factory) {
12 $this->annotationFactory = $factory;
13 }
14
15 public function annotations($object) {
16 $annotation = $this->annotationFactory;
17 $class = new ReflectionObject($object);
18 $properties = $class->getProperties();
19 foreach ($properties as $property) {
20 $propertyName = $property->getName();
21 $rule = $annotation->createFromProperty($object, $propertyName);
22 if ($rule->isValid($object)) {
23 continue;
24 }
25
26 throw new Exception("$propertyName is not valid.");
27 }
28 }
29 }
1 <?php
2
3 use EasyTaxiAnnotation;
4 use EasyTaxiValidation;
5
6 $filter = new AnnotationFilter();
7 $factory = new AnnotationFactory($filter);
8 $validator = new ValidationValidator($factory);
9 $fusca = new Car('AAA-1111');
10
11 $validator->annotation($fusca);
OUTROS
EXEMPLOS
BEHAT
COMPOSER
PHING
DQL
PHPUNIT MOCK OBJECTS
A VIDA DE
UMA
DSL
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL
DOMÍNIO
DSL
INTERNAO
DSL
EXTERNA
LIMITES DE
UMA
DSL
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL
AUTOMATIZAR
TAREFAS
REPETITIVAS
<TARGET NAME=“TEST”>
<TARGET NAME=“DEPLOY”>
<TARGET NAME=“BUILD”>
<CONDITION>
<CONDITION>
FAIL
A SEGUIR,
UMA
MENSAGEM
1 <?php
2
3 use RespectValidationValidator as v;
4
5 v::stringType()
6 ->exactLength(8)
7 ->contains("-")
8 ->contains("/^[A-Z]{3}/")
9 ->contains("/[0-9]{4}$/")
10 ->assert($something);
A VIDA DE
UMA
MENSAGEM
99% JAPA
MAS
AQUELE 1%
É ITALIANO
PARA
QUEM
VOCÊ ESTÁ
FALANDO
PARA
QUEM
VOCÊ ESTÁ
CODANDO
UMA BOA
MENSAGEM
TEM LIMITES
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL
FAZ USO
DE
CONHECIMENTO
PRÉVIO
FAZ USO
DE UM
VOCABULÁRIO
COMUM
DOMÍNIOS
QUE
#%$!*&
SÃO
DSLS
?
PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL
DSLS
SÃO
BOAS
MENSAGENS
DEPENDEM
DE BONS
DOMÍNIOS
SÃO MAIS
ESPECÍFICAS
DO QUE
LINGUAGENS
GENÉRICAS
POR ISSO
COMUNICAM
MAIS
COISAS
DESENVOLVIMENTO
É SOBRE
COMUNICAÇÃO
PERGUNTAS?
AGRADECIMENTOS
@NELSONSAR
@IVONASCIMENTO
@ALGANET @ITEASYTAXI
HTTP://BIT.LY/PHPX-DSLS
1 of 80

Recommended

Melhorando sua API com DSLs by
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLsAugusto Pascutti
1.1K views80 slides
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHP by
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPIPC2010SE Doctrine2 Enterprise Persistence Layer for PHP
IPC2010SE Doctrine2 Enterprise Persistence Layer for PHPGuilherme Blanco
4.5K views79 slides
Workshop unittesting by
Workshop unittestingWorkshop unittesting
Workshop unittestingJoshua Thijssen
1.1K views32 slides
Short Introduction To "perl -d" by
Short Introduction To "perl -d"Short Introduction To "perl -d"
Short Introduction To "perl -d"Workhorse Computing
1.7K views32 slides
Electrify your code with PHP Generators by
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP GeneratorsMark Baker
3.7K views49 slides
Doctrine 2.0 Enterprise Persistence Layer for PHP by
Doctrine 2.0 Enterprise Persistence Layer for PHPDoctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHPGuilherme Blanco
4.8K views46 slides

More Related Content

What's hot

PHPCon 2016: PHP7 by Witek Adamus / XSolve by
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
1K views141 slides
Yapcasia2011 - Hello Embed Perl by
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlHideaki Ohno
1.5K views38 slides
PHP Tips for certification - OdW13 by
PHP Tips for certification - OdW13PHP Tips for certification - OdW13
PHP Tips for certification - OdW13julien pauli
5.8K views31 slides
I, For One, Welcome Our New Perl6 Overlords by
I, For One, Welcome Our New Perl6 OverlordsI, For One, Welcome Our New Perl6 Overlords
I, For One, Welcome Our New Perl6 Overlordsheumann
715 views129 slides
Perl 6 by example by
Perl 6 by examplePerl 6 by example
Perl 6 by exampleAndrew Shitov
1.7K views66 slides
PHP7 is coming by
PHP7 is comingPHP7 is coming
PHP7 is comingjulien pauli
24K views73 slides

What's hot(20)

PHPCon 2016: PHP7 by Witek Adamus / XSolve by XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
XSolve1K views
Yapcasia2011 - Hello Embed Perl by Hideaki Ohno
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed Perl
Hideaki Ohno1.5K views
PHP Tips for certification - OdW13 by julien pauli
PHP Tips for certification - OdW13PHP Tips for certification - OdW13
PHP Tips for certification - OdW13
julien pauli5.8K views
I, For One, Welcome Our New Perl6 Overlords by heumann
I, For One, Welcome Our New Perl6 OverlordsI, For One, Welcome Our New Perl6 Overlords
I, For One, Welcome Our New Perl6 Overlords
heumann715 views
Php unit the-mostunknownparts by Bastian Feder
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
Bastian Feder1.6K views
OSDC.TW - Gutscript for PHP haters by Lin Yo-An
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP haters
Lin Yo-An2.4K views
The $path to knowledge: What little it take to unit-test Perl. by Workhorse Computing
The $path to knowledge: What little it take to unit-test Perl.The $path to knowledge: What little it take to unit-test Perl.
The $path to knowledge: What little it take to unit-test Perl.
Zend Certification Preparation Tutorial by Lorna Mitchell
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
Lorna Mitchell24.3K views
Just-In-Time Compiler in PHP 8 by Nikita Popov
Just-In-Time Compiler in PHP 8Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8
Nikita Popov1.6K views
What's new in PHP 8.0? by Nikita Popov
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
Nikita Popov3.2K views
The promise of asynchronous PHP by Wim Godden
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
Wim Godden2.6K views
Perl 6 in Context by lichtkind
Perl 6 in ContextPerl 6 in Context
Perl 6 in Context
lichtkind1.2K views
PHP5.5 is Here by julien pauli
PHP5.5 is HerePHP5.5 is Here
PHP5.5 is Here
julien pauli13.6K views
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016) by James Titcumb
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
James Titcumb425 views

Viewers also liked

PHP Experience 2016 - [Palestra] Autenticação em APIs by
PHP Experience 2016 - [Palestra] Autenticação em APIsPHP Experience 2016 - [Palestra] Autenticação em APIs
PHP Experience 2016 - [Palestra] Autenticação em APIsiMasters
1.3K views38 slides
PHP Experience 2016 - [Workshop] Deploy escalável na Amazon AWS by
PHP Experience 2016 - [Workshop] Deploy escalável na Amazon AWSPHP Experience 2016 - [Workshop] Deploy escalável na Amazon AWS
PHP Experience 2016 - [Workshop] Deploy escalável na Amazon AWSiMasters
951 views49 slides
PHP Experience 2016 - [Palestra] Keynote: PHP-7 by
PHP Experience 2016 - [Palestra] Keynote: PHP-7PHP Experience 2016 - [Palestra] Keynote: PHP-7
PHP Experience 2016 - [Palestra] Keynote: PHP-7iMasters
1.1K views49 slides
Waw - Gas by
Waw - GasWaw - Gas
Waw - Gasimpactaeventos
466 views41 slides
PHP Experience 2016 - [Workshop] APIs bem desenhadas como base para integrações by
PHP Experience 2016 - [Workshop] APIs bem desenhadas como base para integraçõesPHP Experience 2016 - [Workshop] APIs bem desenhadas como base para integrações
PHP Experience 2016 - [Workshop] APIs bem desenhadas como base para integraçõesiMasters
1.2K views126 slides
PHP Experience 2016 - [Palestra] Json Web Token (JWT) by
PHP Experience 2016 - [Palestra] Json Web Token (JWT)PHP Experience 2016 - [Palestra] Json Web Token (JWT)
PHP Experience 2016 - [Palestra] Json Web Token (JWT)iMasters
2.1K views33 slides

Viewers also liked(10)

PHP Experience 2016 - [Palestra] Autenticação em APIs by iMasters
PHP Experience 2016 - [Palestra] Autenticação em APIsPHP Experience 2016 - [Palestra] Autenticação em APIs
PHP Experience 2016 - [Palestra] Autenticação em APIs
iMasters1.3K views
PHP Experience 2016 - [Workshop] Deploy escalável na Amazon AWS by iMasters
PHP Experience 2016 - [Workshop] Deploy escalável na Amazon AWSPHP Experience 2016 - [Workshop] Deploy escalável na Amazon AWS
PHP Experience 2016 - [Workshop] Deploy escalável na Amazon AWS
iMasters951 views
PHP Experience 2016 - [Palestra] Keynote: PHP-7 by iMasters
PHP Experience 2016 - [Palestra] Keynote: PHP-7PHP Experience 2016 - [Palestra] Keynote: PHP-7
PHP Experience 2016 - [Palestra] Keynote: PHP-7
iMasters1.1K views
PHP Experience 2016 - [Workshop] APIs bem desenhadas como base para integrações by iMasters
PHP Experience 2016 - [Workshop] APIs bem desenhadas como base para integraçõesPHP Experience 2016 - [Workshop] APIs bem desenhadas como base para integrações
PHP Experience 2016 - [Workshop] APIs bem desenhadas como base para integrações
iMasters1.2K views
PHP Experience 2016 - [Palestra] Json Web Token (JWT) by iMasters
PHP Experience 2016 - [Palestra] Json Web Token (JWT)PHP Experience 2016 - [Palestra] Json Web Token (JWT)
PHP Experience 2016 - [Palestra] Json Web Token (JWT)
iMasters2.1K views
PHP Experience 2016 - [Workshop] Agile: Test Driven Development by iMasters
PHP Experience 2016 - [Workshop] Agile: Test Driven DevelopmentPHP Experience 2016 - [Workshop] Agile: Test Driven Development
PHP Experience 2016 - [Workshop] Agile: Test Driven Development
iMasters1K views
PHP Experience 2016 - [Palestra] Rumo à Certificação PHP by iMasters
PHP Experience 2016 - [Palestra] Rumo à Certificação PHPPHP Experience 2016 - [Palestra] Rumo à Certificação PHP
PHP Experience 2016 - [Palestra] Rumo à Certificação PHP
iMasters1.1K views
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP by iMasters
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHPPHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
iMasters1.3K views
What I learnt: Elastic search & Kibana : introduction, installtion & configur... by Rahul K Chauhan
What I learnt: Elastic search & Kibana : introduction, installtion & configur...What I learnt: Elastic search & Kibana : introduction, installtion & configur...
What I learnt: Elastic search & Kibana : introduction, installtion & configur...
Rahul K Chauhan1.1K views

Similar to PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL

Adding Dependency Injection to Legacy Applications by
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
1.8K views77 slides
2013 - Benjamin Eberlei - Doctrine 2 by
2013 - Benjamin Eberlei - Doctrine 22013 - Benjamin Eberlei - Doctrine 2
2013 - Benjamin Eberlei - Doctrine 2PHP Conference Argentina
2.8K views44 slides
Fatc by
FatcFatc
FatcWade Arnold
925 views45 slides
PHP 5.3 Overview by
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
492 views38 slides
Unittests für Dummies by
Unittests für DummiesUnittests für Dummies
Unittests für DummiesLars Jankowfsky
1K views28 slides
The Truth About Lambdas in PHP by
The Truth About Lambdas in PHPThe Truth About Lambdas in PHP
The Truth About Lambdas in PHPSharon Levy
1.2K views67 slides

Similar to PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL(20)

Adding Dependency Injection to Legacy Applications by Sam Hennessy
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
Sam Hennessy1.8K views
PHP 5.3 Overview by jsmith92
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
jsmith92492 views
The Truth About Lambdas in PHP by Sharon Levy
The Truth About Lambdas in PHPThe Truth About Lambdas in PHP
The Truth About Lambdas in PHP
Sharon Levy1.2K views
Can't Miss Features of PHP 5.3 and 5.4 by Jeff Carouth
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
Jeff Carouth3.1K views
Why is crud a bad idea - focus on real scenarios by Divante
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
Divante743 views
Bootstrat REST APIs with Laravel 5 by Elena Kolevska
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
Elena Kolevska3.9K views
PHP and Rich Internet Applications by elliando dias
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
elliando dias4K views
Advanced php testing in action by Jace Ju
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
Jace Ju2.1K views
Rich domain model with symfony 2.5 and doctrine 2.5 by Leonardo Proietti
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
Leonardo Proietti12K views
Dependency Injection by Rifat Nabi
Dependency InjectionDependency Injection
Dependency Injection
Rifat Nabi2.8K views
Database Design Patterns by Hugo Hamon
Database Design PatternsDatabase Design Patterns
Database Design Patterns
Hugo Hamon11.4K views
Symfony2 Building on Alpha / Beta technology by Daniel Knell
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
Daniel Knell750 views

More from iMasters

O que você precisa saber para modelar bancos de dados NoSQL - Dani Monteiro by
O que você precisa saber para modelar bancos de dados NoSQL - Dani MonteiroO que você precisa saber para modelar bancos de dados NoSQL - Dani Monteiro
O que você precisa saber para modelar bancos de dados NoSQL - Dani MonteiroiMasters
1.4K views40 slides
Postgres: wanted, beloved or dreaded? - Fabio Telles by
Postgres: wanted, beloved or dreaded? - Fabio TellesPostgres: wanted, beloved or dreaded? - Fabio Telles
Postgres: wanted, beloved or dreaded? - Fabio TellesiMasters
603 views51 slides
Por que minha query esta lenta? - Suellen Moraes by
Por que minha query esta lenta? - Suellen MoraesPor que minha query esta lenta? - Suellen Moraes
Por que minha query esta lenta? - Suellen MoraesiMasters
370 views12 slides
Relato das trincheiras: o dia a dia de uma consultoria de banco de dados - Ig... by
Relato das trincheiras: o dia a dia de uma consultoria de banco de dados - Ig...Relato das trincheiras: o dia a dia de uma consultoria de banco de dados - Ig...
Relato das trincheiras: o dia a dia de uma consultoria de banco de dados - Ig...iMasters
298 views9 slides
ORMs heróis ou vilões dentro da arquitetura de dados? - Otávio gonçalves by
ORMs heróis ou vilões dentro da arquitetura de dados? - Otávio gonçalvesORMs heróis ou vilões dentro da arquitetura de dados? - Otávio gonçalves
ORMs heróis ou vilões dentro da arquitetura de dados? - Otávio gonçalvesiMasters
324 views31 slides
SQL e NoSQL trabalhando juntos: uma comparação para obter o melhor de ambos -... by
SQL e NoSQL trabalhando juntos: uma comparação para obter o melhor de ambos -...SQL e NoSQL trabalhando juntos: uma comparação para obter o melhor de ambos -...
SQL e NoSQL trabalhando juntos: uma comparação para obter o melhor de ambos -...iMasters
1.7K views52 slides

More from iMasters(20)

O que você precisa saber para modelar bancos de dados NoSQL - Dani Monteiro by iMasters
O que você precisa saber para modelar bancos de dados NoSQL - Dani MonteiroO que você precisa saber para modelar bancos de dados NoSQL - Dani Monteiro
O que você precisa saber para modelar bancos de dados NoSQL - Dani Monteiro
iMasters1.4K views
Postgres: wanted, beloved or dreaded? - Fabio Telles by iMasters
Postgres: wanted, beloved or dreaded? - Fabio TellesPostgres: wanted, beloved or dreaded? - Fabio Telles
Postgres: wanted, beloved or dreaded? - Fabio Telles
iMasters603 views
Por que minha query esta lenta? - Suellen Moraes by iMasters
Por que minha query esta lenta? - Suellen MoraesPor que minha query esta lenta? - Suellen Moraes
Por que minha query esta lenta? - Suellen Moraes
iMasters370 views
Relato das trincheiras: o dia a dia de uma consultoria de banco de dados - Ig... by iMasters
Relato das trincheiras: o dia a dia de uma consultoria de banco de dados - Ig...Relato das trincheiras: o dia a dia de uma consultoria de banco de dados - Ig...
Relato das trincheiras: o dia a dia de uma consultoria de banco de dados - Ig...
iMasters298 views
ORMs heróis ou vilões dentro da arquitetura de dados? - Otávio gonçalves by iMasters
ORMs heróis ou vilões dentro da arquitetura de dados? - Otávio gonçalvesORMs heróis ou vilões dentro da arquitetura de dados? - Otávio gonçalves
ORMs heróis ou vilões dentro da arquitetura de dados? - Otávio gonçalves
iMasters324 views
SQL e NoSQL trabalhando juntos: uma comparação para obter o melhor de ambos -... by iMasters
SQL e NoSQL trabalhando juntos: uma comparação para obter o melhor de ambos -...SQL e NoSQL trabalhando juntos: uma comparação para obter o melhor de ambos -...
SQL e NoSQL trabalhando juntos: uma comparação para obter o melhor de ambos -...
iMasters1.7K views
Arquitetando seus dados na prática para a LGPD - Alessandra Martins by iMasters
Arquitetando seus dados na prática para a LGPD - Alessandra MartinsArquitetando seus dados na prática para a LGPD - Alessandra Martins
Arquitetando seus dados na prática para a LGPD - Alessandra Martins
iMasters3.3K views
O papel do DBA no mundo de ciência de dados e machine learning - Mauro Pichil... by iMasters
O papel do DBA no mundo de ciência de dados e machine learning - Mauro Pichil...O papel do DBA no mundo de ciência de dados e machine learning - Mauro Pichil...
O papel do DBA no mundo de ciência de dados e machine learning - Mauro Pichil...
iMasters287 views
Desenvolvimento Mobile Híbrido, Nativo ou Web: Quando usá-los - Juliana Chahoud by iMasters
Desenvolvimento Mobile Híbrido, Nativo ou Web: Quando usá-los - Juliana ChahoudDesenvolvimento Mobile Híbrido, Nativo ou Web: Quando usá-los - Juliana Chahoud
Desenvolvimento Mobile Híbrido, Nativo ou Web: Quando usá-los - Juliana Chahoud
iMasters950 views
Use MDD e faça as máquinas trabalharem para você - Andreza Leite by iMasters
 Use MDD e faça as máquinas trabalharem para você - Andreza Leite Use MDD e faça as máquinas trabalharem para você - Andreza Leite
Use MDD e faça as máquinas trabalharem para você - Andreza Leite
iMasters682 views
Entendendo os porquês do seu servidor - Talita Bernardes by iMasters
Entendendo os porquês do seu servidor - Talita BernardesEntendendo os porquês do seu servidor - Talita Bernardes
Entendendo os porquês do seu servidor - Talita Bernardes
iMasters544 views
Backend performático além do "coloca mais máquina lá" - Diana Arnos by iMasters
Backend performático além do "coloca mais máquina lá" - Diana ArnosBackend performático além do "coloca mais máquina lá" - Diana Arnos
Backend performático além do "coloca mais máquina lá" - Diana Arnos
iMasters477 views
Dicas para uma maior performance em APIs REST - Renato Groffe by iMasters
Dicas para uma maior performance em APIs REST - Renato GroffeDicas para uma maior performance em APIs REST - Renato Groffe
Dicas para uma maior performance em APIs REST - Renato Groffe
iMasters595 views
7 dicas de desempenho que equivalem por 21 - Danielle Monteiro by iMasters
7 dicas de desempenho que equivalem por 21 - Danielle Monteiro7 dicas de desempenho que equivalem por 21 - Danielle Monteiro
7 dicas de desempenho que equivalem por 21 - Danielle Monteiro
iMasters475 views
Quem se importa com acessibilidade Web? - Mauricio Maujor by iMasters
Quem se importa com acessibilidade Web? - Mauricio MaujorQuem se importa com acessibilidade Web? - Mauricio Maujor
Quem se importa com acessibilidade Web? - Mauricio Maujor
iMasters480 views
Service Mesh com Istio e Kubernetes - Wellington Figueira da Silva by iMasters
Service Mesh com Istio e Kubernetes - Wellington Figueira da SilvaService Mesh com Istio e Kubernetes - Wellington Figueira da Silva
Service Mesh com Istio e Kubernetes - Wellington Figueira da Silva
iMasters604 views
Erros: Como eles vivem, se alimentam e se reproduzem? - Augusto Pascutti by iMasters
Erros: Como eles vivem, se alimentam e se reproduzem? - Augusto PascuttiErros: Como eles vivem, se alimentam e se reproduzem? - Augusto Pascutti
Erros: Como eles vivem, se alimentam e se reproduzem? - Augusto Pascutti
iMasters559 views
Elasticidade e engenharia de banco de dados para alta performance - Rubens G... by iMasters
Elasticidade e engenharia de banco de dados para alta performance  - Rubens G...Elasticidade e engenharia de banco de dados para alta performance  - Rubens G...
Elasticidade e engenharia de banco de dados para alta performance - Rubens G...
iMasters569 views
Construindo aplicações mais confiantes - Carolina Karklis by iMasters
Construindo aplicações mais confiantes - Carolina KarklisConstruindo aplicações mais confiantes - Carolina Karklis
Construindo aplicações mais confiantes - Carolina Karklis
iMasters477 views
Monitoramento de Aplicações - Felipe Regalgo by iMasters
Monitoramento de Aplicações - Felipe RegalgoMonitoramento de Aplicações - Felipe Regalgo
Monitoramento de Aplicações - Felipe Regalgo
iMasters709 views

Recently uploaded

INT-244 Topic 6b Confucianism by
INT-244 Topic 6b ConfucianismINT-244 Topic 6b Confucianism
INT-244 Topic 6b ConfucianismS Meyer
45 views77 slides
PRELIMS ANSWER.pptx by
PRELIMS ANSWER.pptxPRELIMS ANSWER.pptx
PRELIMS ANSWER.pptxsouravkrpodder
50 views60 slides
Guess Papers ADC 1, Karachi University by
Guess Papers ADC 1, Karachi UniversityGuess Papers ADC 1, Karachi University
Guess Papers ADC 1, Karachi UniversityKhalid Aziz
99 views17 slides
JRN 362 - Lecture Twenty-Three (Epilogue) by
JRN 362 - Lecture Twenty-Three (Epilogue)JRN 362 - Lecture Twenty-Three (Epilogue)
JRN 362 - Lecture Twenty-Three (Epilogue)Rich Hanley
41 views57 slides
StudioX.pptx by
StudioX.pptxStudioX.pptx
StudioX.pptxNikhileshSathyavarap
101 views18 slides
Volf work.pdf by
Volf work.pdfVolf work.pdf
Volf work.pdfMariaKenney3
89 views43 slides

Recently uploaded(20)

INT-244 Topic 6b Confucianism by S Meyer
INT-244 Topic 6b ConfucianismINT-244 Topic 6b Confucianism
INT-244 Topic 6b Confucianism
S Meyer45 views
Guess Papers ADC 1, Karachi University by Khalid Aziz
Guess Papers ADC 1, Karachi UniversityGuess Papers ADC 1, Karachi University
Guess Papers ADC 1, Karachi University
Khalid Aziz99 views
JRN 362 - Lecture Twenty-Three (Epilogue) by Rich Hanley
JRN 362 - Lecture Twenty-Three (Epilogue)JRN 362 - Lecture Twenty-Three (Epilogue)
JRN 362 - Lecture Twenty-Three (Epilogue)
Rich Hanley41 views
Pharmaceutical Analysis PPT (BP 102T) by yakshpharmacy009
Pharmaceutical Analysis PPT (BP 102T) Pharmaceutical Analysis PPT (BP 102T)
Pharmaceutical Analysis PPT (BP 102T)
yakshpharmacy009108 views
Retail Store Scavenger Hunt.pptx by jmurphy154
Retail Store Scavenger Hunt.pptxRetail Store Scavenger Hunt.pptx
Retail Store Scavenger Hunt.pptx
jmurphy15452 views
ANGULARJS.pdf by ArthyR3
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdf
ArthyR351 views
Career Building in AI - Technologies, Trends and Opportunities by WebStackAcademy
Career Building in AI - Technologies, Trends and OpportunitiesCareer Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy45 views
Nelson_RecordStore.pdf by BrynNelson5
Nelson_RecordStore.pdfNelson_RecordStore.pdf
Nelson_RecordStore.pdf
BrynNelson546 views
11.30.23A Poverty and Inequality in America.pptx by mary850239
11.30.23A Poverty and Inequality in America.pptx11.30.23A Poverty and Inequality in America.pptx
11.30.23A Poverty and Inequality in America.pptx
mary850239130 views
CUNY IT Picciano.pptx by apicciano
CUNY IT Picciano.pptxCUNY IT Picciano.pptx
CUNY IT Picciano.pptx
apicciano64 views

PHP Experience 2016 - [Palestra] Melhorando a comunicação da API através de DSL

  • 6. 1 <?php 2 3 use RespectValidationValidator as v; 4 5 v::stringType() 6 ->exactLength(8) 7 ->contains("-") 8 ->contains("/^[A-Z]{3}/") 9 ->contains("/[0-9]{4}$/") 10 ->assert($something);
  • 7. 1 <?php 2 3 namespace EasyTaxiValidationRules; 4 5 use RespectValidationRules as BaseRules; 6 7 class CarPlate extends BaseRulesAllOf 8 { 9 public function __construct() 10 { 11 $this->name = 'Brazilian car plate'; 12 13 parent::__construct( 14 new BaseRulesStringType(), 15 new ExactLength(8), 16 new BaseRuleContains("-")->setName('Separator'), 17 new BaseRuleContains("/^[A-Z]{3}/")->setName("Prefix") 18 new BaseRuleContains("/^[0-9]{4}/")->setName("Sufix") 19 ); 20 } 21 }
  • 8. 1 <?php 2 3 namespace EasyTaxiValidationRules; 4 5 use RespectValidationRules as BaseRules; 6 7 class CarPlate extends BaseRulesAllOf 8 { 9 public function __construct() 10 { 11 $this->name = 'Brazilian car plate'; 12 13 parent::__construct( 14 new BaseRulesStringType(), 15 new ExactLength(8), 16 new BaseRuleContains("-")->setName('Separator'), 17 new BaseRuleContains("/^[A-Z]{3}/")->setName("Prefix") 18 new BaseRuleContains("/^[0-9]{4}/")->setName("Sufix") 19 ); 20 } 21 }
  • 9. 1 <?php 2 3 // ... dentro de algum método de um Controller ... 4 5 ValidationValidator::arrayType() 6 ->key('driver_name', v::driverName()) 7 ->key('driver_birthdate', v::minimumAge(18)) 8 ->key( 9 'driver_car', v::arrayType( 10 v::key("model", v::carModel($this->get('model.vehicle'))), 11 v::key("assembler", v::carAssembler()), 12 v::key("year", v::maximumAge(5)), 13 v::key("plate", v::carPlate()) 14 ) 15 ) 16 ->key('license_number', v::driverLicense()) 17 ->key('taxi_permission', v::taxiPermissionNumber()) 18 ->key('address', v::address()) 19 ->assert($_POST);
  • 11. 1 <?php 2 3 namespace RespectValidation; 4 5 class Validator 6 { 7 public function stringType() {} 8 public function contains($search) {} 9 public function assert($mixed) {} 10 }
  • 13. 1 <?php 2 3 namespace RespectValidation; 4 5 interface Rule 6 { 7 public function isValid($mixed): bool; 8 }
  • 15. 1 <?php 2 3 namespace RespectValidationRules; 4 5 use RespectValidation; 6 7 class StringType implements ValidationRule 8 { 9 public function isValid($mixed): bool 10 { 11 return is_string($mixed); 12 } 13 }
  • 16. 3 namespace RespectValidationRules; 4 5 use RespectValidation; 6 7 class AllOf implements ValidationRule 8 { 9 protected $rules = []; 10 17 public function __construct(ValidationRule ...$rules) 18 { 19 $this->rules = $rules; 20 } 21 22 public function isValid($mixed): bool 23 { 24 foreach ($this->rules as $rule) { 25 if (false === $rule->isValid($mixed)) { 26 return false; 27 } 28 } 29 30 return true; 31 } 32 }
  • 18. 1 <?php 2 3 $factory = new RespectValidationRuleFactory; 4 $rule = $factory->createInstance('StringType');
  • 19. 1 <?php 2 3 namespace RespectValidation; 4 5 class RuleFactory 6 { 7 public function createInstance($ruleName, array $args = []): Rule 8 { 9 $ruleNamespace = 'RespectValidationRules'; 10 $className = $ruleNamespace . $rule; 11 $reflection = new ReflectionClass($className); 12 13 return $reflection->newInstanceArgs($args); 14 } 15 }
  • 21. 1 <?php 2 3 namespace RespectValidation; 4 5 class RuleFactory 6 { 7 public function __call($methodName, $methodArguments) 8 { 9 return $this->createInstance($methodName, $methodArguments); 10 } 11 12 public function createInstance($ruleName, array $args = []): Rule 13 { 14 /* ... */ 15 } 16 }
  • 22. 1 <?php 2 3 $checkFor = new RespectValidationRuleFactory; 4 5 $isString = $checkFor->StringType(); 6 7 $isTwitterUserName = $checkFor->AllOf( 8 $checkFor->AlNum(), 9 $checkFor->NoWhitespace(), 10 $checkFor->Length(1, 15) 11 );
  • 24. 3 namespace RespectValidation; 4 5 class RuleFactory 6 { 7 private static $factory = null; 8 9 public static function getInstance() 10 { 11 if (is_null(self::$factory)) { 12 self::$factory = new static; 13 } 14 15 return self::$factory; 16 } 17 18 public static function __callStatic($methodName, $methodArguments) 19 { 20 $factory = self::getFactory(); 21 22 return $factory->createInstance($methodName, $methodArguments); 23 } 24 25 /* ... */ 26 }
  • 25. 1 <?php 2 3 use RespectValidationRuleFactory as v; 4 5 $isTwitterUserName = v::AllOf( 6 v::AlNum(), 7 v::NoWhitespace(), 8 v::Length(1, 15) 9 );
  • 29. 1 <?php 2 3 namespace EasyTaxiValidation; 4 5 interface Rule 6 { 7 public function isValid($mixed): bool; 8 }
  • 30. 1 <?php 2 3 namespace EasyTaxiValidationRules; 4 5 use EasyTaxiValidation; 6 use RespectValidationValidator as v; 7 8 class PlateValidator implements Rule 9 { 10 public function isValid($mixed): bool 11 { 12 return v::stringType() 13 ->exactLength(8) 14 ->contains("-") 15 ->contains("/^[A-Z]{3}/") 16 ->contains("/[0-9]{4}$/") 17 ->setName('Car plate') 18 ->validate($mixed); 19 } 20 }
  • 32. 1 <?php 2 3 namespace EasyTaxiDriver; 4 5 class Car 6 { 7 /** 8 * @PlateValidator 9 */ 10 private $plate = ''; 11 12 public function __construct($plate) 13 { 14 $this->plate = $plate; 15 } 16 }
  • 33. 1 <?php 2 3 use EasyTaxiAnnotation; 4 use EasyTaxiValidation; 5 6 $filter = new AnnotationFilter(); 7 $factory = new AnnotationFactory($filter); 8 $validator = new ValidationValidator($factory); 9 $fusca = new Car('AAA-1111'); 10 11 $validator->annotations($fusca);
  • 35. 1 <?php 2 3 namespace EasyTaxiAnnotation; 4 5 class Filter 6 { 7 public function firstAnnotation($doc): string { 8 foreach ($this->breakLines($doc) as $line) { 9 if (false === $this->hasAnnotation($line)) { 10 continue; 11 } 12 13 return $this->filterName($line); 14 } 15 } 16 17 private function breakLines($doc): array { 18 return explode(PHP_EOL, $doc); 19 } 20 21 private function hasAnnotation($line): bool { 22 return false !== strpos($line, '@'); 23 } 24 25 private function filterName($line): string { 26 return trim(str_replace(['*', '/', '@'], '', $line)); 27 } 28 }
  • 36. CRIANDO REGRAS A PARTIR DE UM COMENTÁRIO
  • 37. 3 namespace EasyTaxiAnnotation; 4 5 class Factory 6 { 7 private $filter = null; 8 9 public function __construct(Filter $annotationFilter) 10 { 11 $this->filter = $annotationFilter; 12 } 13 14 public function createFromProperty($instance, $propertyName) 15 { 16 $object = new ReflectionObject($instance); 17 $property = $object->getProperty($propertyName); 18 19 return $this->createInstanceFromComment($property->getDocComment()); 20 } 21 22 private function createInstanceFromComment($doc) 23 { 24 $annotationClass = $this->filter->firstAnnotation($doc); 25 $class = new ReflectionClass($annotationClass); 26 27 return $class->newInstance(); 28 } 29 }
  • 39. 3 namespace EasyTaxiValidation; 4 5 use EasyTaxiAnnotation; 6 7 class Validator 8 { 9 private $annotationFactory = null; 10 11 public function __construct(AnnotationFactory $factory) { 12 $this->annotationFactory = $factory; 13 } 14 15 public function annotations($object) { 16 $annotation = $this->annotationFactory; 17 $class = new ReflectionObject($object); 18 $properties = $class->getProperties(); 19 foreach ($properties as $property) { 20 $propertyName = $property->getName(); 21 $rule = $annotation->createFromProperty($object, $propertyName); 22 if ($rule->isValid($object)) { 23 continue; 24 } 25 26 throw new Exception("$propertyName is not valid."); 27 } 28 } 29 }
  • 40. 1 <?php 2 3 use EasyTaxiAnnotation; 4 use EasyTaxiValidation; 5 6 $filter = new AnnotationFilter(); 7 $factory = new AnnotationFactory($filter); 8 $validator = new ValidationValidator($factory); 9 $fusca = new Car('AAA-1111'); 10 11 $validator->annotation($fusca);
  • 42. BEHAT
  • 44. PHING
  • 45. DQL
  • 61. 1 <?php 2 3 use RespectValidationValidator as v; 4 5 v::stringType() 6 ->exactLength(8) 7 ->contains("-") 8 ->contains("/^[A-Z]{3}/") 9 ->contains("/[0-9]{4}$/") 10 ->assert($something);