Doubt over inheritance in classes

2

How do if of the controller return TRUE or FALSE according to check() of Validator?

Currently it returns Boolean for validate(); , but I wanted it to continue until the end of the code, to then return the Boolean.

<?php
# relatorio venda controller
class RelatorioVendaController {
    public function __construct() {
        $form['nome'] = 'Ricardo';
        $form['idade'] = 24;

        if(RelatorioVenda::validate($form)){
            print 'Nenhum erro.';
        }
    }
}

# relatorio venda model
class RelatorioVendaModel extends RelatorioModel {
    public static function validate($form){
        $validators = array(
            "nome" => "required",
            "idade" => "required"
        );
        parent::rules($form, $validators);
    }
}

# relatorio model
class RelatorioModel {
    public static function rules($form, $validators){
        // junta os arrays foreach e executa a validacao
        Validator::check($field, $map['field'], $map['validator']);
    }
}

class Validator {
    public static function check($field, $value, $validator){
        // execute validator(field, value)

        if(no erros)
            return true;
    }
    public function required($field, $value){
        // validator
    }
}
?>
    
asked by anonymous 28.02.2014 / 19:32

2 answers

1

You can use a variável !

    $booleano = RelatorioVenda::validate($form);
    if($booleano){
        print 'Nenhum erro.';
    }
    return $booleano;

Do not forget to use return for the functions to return some result ...

... but remember that invoking a constructor via a new operator always returns a new instance of a class , and never a boolean or any other result type.

So you should move that part of your code to another method of the class.

    
01.03.2014 / 06:33
0

Remember that builders DO NOT RETURN.

The best way to do what you want is through exceptions:

# relatorio venda controller
class RelatorioVendaController {
    public function __construct($form) { //editei essa linha pra fazer sentido
        $form['nome'] = 'Ricardo';
        $form['idade'] = 24;

        if(RelatorioVenda::validate($form)){
            print 'Nenhum erro.';
        } else {
            throw new Exception('Houve algum erro de validação');
        }
    }
}

At the time of use, you do:

try {
    $controller = new RelatorioVendaController($form); // seja lá de onde vem esse $form;
} catch (Exception $e) {
    // tome as providências necessárias
}
    
03.03.2014 / 20:11