Skip to content

Instantly share code, notes, and snippets.

@IgorDePaula
Created March 7, 2023 23:26
Show Gist options
  • Save IgorDePaula/afb9eec6e271d6968d20a2ecae8def0e to your computer and use it in GitHub Desktop.
Save IgorDePaula/afb9eec6e271d6968d20a2ecae8def0e to your computer and use it in GitHub Desktop.
Atributo com php
<?php
#[Attribute]
class Validacao {
public function __construct(
public string $regra,
public int $valor
){}
public function validate(int $value)
{
if($value > $this->valor){
throw new Exception('Limite de velocidade excedida');
}
}
}
class Carro {
#[Validacao('max', 110)]
public int $velocidade;
}
$carro = new Carro();
$carro->velocidade = 139;
$informacoesClasseCarro = new reflectionClass($carro);
foreach ($informacoesClasseCarro->getProperties() as $propriedade) {
$value = $propriedade->getValue($carro);
$atributosDaPropriedade = $propriedade->getAttributes(Validacao::class);
foreach ($atributosDaPropriedade as $atributo) {
$atributoInstance = $atributo->newInstance();
$atributoInstance->validate($value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment