SlideShare a Scribd company logo
1 of 80
Download to read offline
MELHORANDO
SUA API COM
DSLS@augustohp
DOMAIN SPECIFIC LANGUAGE
A SEGUIR,
UMA
DSL
VALIDAÇÃO
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 }
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 );
@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
DOMÍNIO
DSL
INTERNAO
DSL
EXTERNA
LIMITES DE
UMA
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
FAZ USO
DE
CONHECIMENTO
PRÉVIO
FAZ USO
DE UM
VOCABULÁRIO
COMUM
DOMÍNIOS
QUE
#%$!*&
SÃO
DSLS
?
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

More Related Content

What's hot

Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongersbrian d foy
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Advanced modulinos trial
Advanced modulinos trialAdvanced modulinos trial
Advanced modulinos trialbrian d foy
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6 brian d foy
 
Yapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlHideaki Ohno
 
Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinosbrian d foy
 
Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)brian d foy
 
A new way to develop with WordPress!
A new way to develop with WordPress!A new way to develop with WordPress!
A new way to develop with WordPress!David Sanchez
 
OSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersLin Yo-An
 
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)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)James Titcumb
 
Parsing JSON with a single regex
Parsing JSON with a single regexParsing JSON with a single regex
Parsing JSON with a single regexbrian d foy
 
Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Workhorse Computing
 
Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Nikita Popov
 

What's hot (20)

Metadata-driven Testing
Metadata-driven TestingMetadata-driven Testing
Metadata-driven Testing
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongers
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Bag of tricks
Bag of tricksBag of tricks
Bag of tricks
 
Advanced modulinos trial
Advanced modulinos trialAdvanced modulinos trial
Advanced modulinos trial
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 
PHP7 Presentation
PHP7 PresentationPHP7 Presentation
PHP7 Presentation
 
Yapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed Perl
 
Advanced modulinos
Advanced modulinosAdvanced modulinos
Advanced modulinos
 
Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)
 
A new way to develop with WordPress!
A new way to develop with WordPress!A new way to develop with WordPress!
A new way to develop with WordPress!
 
OSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP haters
 
Workshop unittesting
Workshop unittestingWorkshop unittesting
Workshop unittesting
 
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)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
Perl6 in-production
Perl6 in-productionPerl6 in-production
Perl6 in-production
 
Parsing JSON with a single regex
Parsing JSON with a single regexParsing JSON with a single regex
Parsing JSON with a single regex
 
Get your teeth into Plack
Get your teeth into PlackGet your teeth into Plack
Get your teeth into Plack
 
Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.Keeping objects healthy with Object::Exercise.
Keeping objects healthy with Object::Exercise.
 
Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8Just-In-Time Compiler in PHP 8
Just-In-Time Compiler in PHP 8
 

Similar to Melhorando sua API com DSLs

Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
The Truth About Lambdas in PHP
The Truth About Lambdas in PHPThe Truth About Lambdas in PHP
The Truth About Lambdas in PHPSharon Levy
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Can't Miss Features of PHP 5.3 and 5.4
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.4Jeff Carouth
 
Why is crud a bad idea - focus on real scenarios
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 scenariosDivante
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Elena Kolevska
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Rich domain model with symfony 2.5 and doctrine 2.5
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.5Leonardo Proietti
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionRifat Nabi
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design PatternsHugo Hamon
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 

Similar to Melhorando sua API com DSLs (20)

Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
2013 - Benjamin Eberlei - Doctrine 2
2013 - Benjamin Eberlei - Doctrine 22013 - Benjamin Eberlei - Doctrine 2
2013 - Benjamin Eberlei - Doctrine 2
 
Fatc
FatcFatc
Fatc
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
The Truth About Lambdas in PHP
The Truth About Lambdas in PHPThe Truth About Lambdas in PHP
The Truth About Lambdas in PHP
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Can't Miss Features of PHP 5.3 and 5.4
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
 
Why is crud a bad idea - focus on real scenarios
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
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Rich domain model with symfony 2.5 and doctrine 2.5
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
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
Oops in php
Oops in phpOops in php
Oops in php
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 

More from Augusto Pascutti

Logs: O que comem, onde vivem e como se reproduzem.
Logs: O que comem, onde vivem e como se reproduzem.Logs: O que comem, onde vivem e como se reproduzem.
Logs: O que comem, onde vivem e como se reproduzem.Augusto Pascutti
 
TDD - Test Driven Development (em PHP)
TDD - Test Driven Development (em PHP)TDD - Test Driven Development (em PHP)
TDD - Test Driven Development (em PHP)Augusto Pascutti
 
Guia do mochileiro para escalabilidade
Guia do mochileiro para escalabilidadeGuia do mochileiro para escalabilidade
Guia do mochileiro para escalabilidadeAugusto Pascutti
 
Falhando miseralvelmente com PHP
Falhando miseralvelmente com PHPFalhando miseralvelmente com PHP
Falhando miseralvelmente com PHPAugusto Pascutti
 
Como escalar aplicações PHP
Como escalar aplicações PHPComo escalar aplicações PHP
Como escalar aplicações PHPAugusto Pascutti
 
PHP - O que, porquê e como
PHP - O que, porquê e comoPHP - O que, porquê e como
PHP - O que, porquê e comoAugusto Pascutti
 
Testar é bom, integrar é ainda melhor
Testar é bom, integrar é ainda melhorTestar é bom, integrar é ainda melhor
Testar é bom, integrar é ainda melhorAugusto Pascutti
 
PHPSC Conference 2010 - Testar é bom, integrar é melhor ainda!
PHPSC Conference 2010 - Testar é bom, integrar é melhor ainda!PHPSC Conference 2010 - Testar é bom, integrar é melhor ainda!
PHPSC Conference 2010 - Testar é bom, integrar é melhor ainda!Augusto Pascutti
 
Orientação a Objetos com PHP
Orientação a Objetos com PHPOrientação a Objetos com PHP
Orientação a Objetos com PHPAugusto Pascutti
 
Boas Práticas, Práticas !
Boas Práticas, Práticas !Boas Práticas, Práticas !
Boas Práticas, Práticas !Augusto Pascutti
 
Mão na Massa: Orientação a Objetos na Prática
Mão na Massa: Orientação a Objetos na PráticaMão na Massa: Orientação a Objetos na Prática
Mão na Massa: Orientação a Objetos na PráticaAugusto Pascutti
 

More from Augusto Pascutti (20)

Errors
ErrorsErrors
Errors
 
Porque VIM?
Porque VIM?Porque VIM?
Porque VIM?
 
Logs: O que comem, onde vivem e como se reproduzem.
Logs: O que comem, onde vivem e como se reproduzem.Logs: O que comem, onde vivem e como se reproduzem.
Logs: O que comem, onde vivem e como se reproduzem.
 
TDD - Test Driven Development (em PHP)
TDD - Test Driven Development (em PHP)TDD - Test Driven Development (em PHP)
TDD - Test Driven Development (em PHP)
 
Guia do mochileiro para escalabilidade
Guia do mochileiro para escalabilidadeGuia do mochileiro para escalabilidade
Guia do mochileiro para escalabilidade
 
Falhando miseralvelmente com PHP
Falhando miseralvelmente com PHPFalhando miseralvelmente com PHP
Falhando miseralvelmente com PHP
 
Orientação a objetos v2
Orientação a objetos v2Orientação a objetos v2
Orientação a objetos v2
 
Under engineer
Under engineerUnder engineer
Under engineer
 
Como escalar aplicações PHP
Como escalar aplicações PHPComo escalar aplicações PHP
Como escalar aplicações PHP
 
The small things
The small thingsThe small things
The small things
 
Somos jardineiros
Somos jardineirosSomos jardineiros
Somos jardineiros
 
PHP - O que, porquê e como
PHP - O que, porquê e comoPHP - O que, porquê e como
PHP - O que, porquê e como
 
Frameworks PHP
Frameworks PHPFrameworks PHP
Frameworks PHP
 
Testar é bom, integrar é ainda melhor
Testar é bom, integrar é ainda melhorTestar é bom, integrar é ainda melhor
Testar é bom, integrar é ainda melhor
 
PHPSC Conference 2010 - Testar é bom, integrar é melhor ainda!
PHPSC Conference 2010 - Testar é bom, integrar é melhor ainda!PHPSC Conference 2010 - Testar é bom, integrar é melhor ainda!
PHPSC Conference 2010 - Testar é bom, integrar é melhor ainda!
 
Segurança em PHP
Segurança em PHPSegurança em PHP
Segurança em PHP
 
Orientação a Objetos com PHP
Orientação a Objetos com PHPOrientação a Objetos com PHP
Orientação a Objetos com PHP
 
Boas Práticas, Práticas !
Boas Práticas, Práticas !Boas Práticas, Práticas !
Boas Práticas, Práticas !
 
Mitos do PHP
Mitos do PHPMitos do PHP
Mitos do PHP
 
Mão na Massa: Orientação a Objetos na Prática
Mão na Massa: Orientação a Objetos na PráticaMão na Massa: Orientação a Objetos na Prática
Mão na Massa: Orientação a Objetos na Prática
 

Recently uploaded

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 

Recently uploaded (20)

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 

Melhorando sua API com DSLs

  • 5.
  • 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 }
  • 12.
  • 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 );
  • 26.
  • 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
  • 48.
  • 53.
  • 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);
  • 67.
  • 72.