Address validations / class / method

Asked

Viewed 61 times

2

Setting

I use a method to dynamically instantiate classes and methods.

Properties received:

  • modulo = name of briefcase with the files .class.php
  • ferramenta = name of filing cabinet .class.php
  • acao = name of method

Method executing the request:

private function executar()
{
    try {
        # Monta o patch e faz require da classe
        $classe     = DIR_MODULOS . $this -> modulo . DS . $this -> ferramenta . '.class.php';
        require_once $classe;
        # Instancia o objeto e executa o método
        $obj        = new $this -> ferramenta();
        $resposta   = $obj -> {$this -> acao}($this -> dados);
        # Retorna a resposta
        $this -> retorno = $resposta;

        } catch (Exception $e) {

            $this -> error =  $e->getMessage();
    }
}

Problems

  • If the property modulo incorrect, will not find the folder path.
    • Error: Warning and Fatal Error of require.
  • If the property ferramenta incorrect, will not find the class file.
    • Error: Warning and Fatal Error of require.
  • If the property acao is incorrect, you will not find the method in the class.
    • Error: Error in method call: Fatal error: Call to Undefined method

Doubt

  • How best to deal with mistakes since the try-catch does not treat them?

    (preferably native functions)


Goal

The idea is to return only one string simple according to error.

Example:

  • "Invalid module"
  • "Invalid tool"
  • "Invalid action"

2 answers

2

The use of try-catch then it’s already wrong. I answer that in several questions here at Sopt (recommend following the links strongly). Do not capture Exception except in the final code output and do not capture an exception to do anything useful.

What it is reporting is a programming error, and programming errors we correct and do not try to recover. Exception is to recover from an unexpected failure but not a programming error.

In codes of dynamic nature, and in dynamic typing language everything is more or less dynamic in nature, you should check what you will use before using. The check just doesn’t need to be done where it’s guaranteed to work.

The programming error there is not to consider that the data may be wrong. So before you use something with the potential to be wrong, make sure you’re right and decide what to do if you’re wrong. Only execute if everything is correct. Almost always the if is your friend.

Who knows one day I write a book on the subject :). Yes, to master exception and error handling needs a book. That’s why most people won’t learn, almost everyone nowadays doesn’t want to read, doesn’t want to spend time learning, does what’s simple, even if it’s wrong and if it works, fine. It is very complicated to treat errors correctly, and even more to use exception. One thing I always talk about is that if you don’t master a resource, don’t use it, and this is the exception, so I have a talk called "Exception - the goto of the 21st century" since it is the mechanism that causes more problems for people, causes much more than the goto that everyone knows is not to use.

  • I understood what you meant, but I like to treat any "possible" error, even if it will still be I who make the requisitions. But I would like to make the return as simple as possible. The "module" and "tool" I am already dealing with the file_exists, I have not yet looked at the "action" that is the method request. The idea would be to treat them, I do not want to change the code. I may have typo, so why not facilitate the return of the reason for the error!?

  • 1

    Depending on how you do you have a huge security hole. Like I do not argue, I always speak of what is right, when it is done by taste ,anything serves.

  • I agree, the more dynamic, the more possible failures. But those I’m going to treat in a previous layer, considering that if you go beyond it, you can execute the rest.

0


I was able to solve using the file_exists, class_exists and method_exists.

PS: As cited by Maniero, being dynamic can bring security holes. In my case treated before reaching that method, but security is never much.


As it turned out:

private function executar()
{
    # Verifica ...
    if (...) {

        # Verifica propriedades mínimas
        if (...) {

            # Monta o path do diretório
            $dir  = DIR_MODULOS . $this -> modulo;
            # Verifica se existe o diretório
            if (file_exists($dir)) {

                # Monta o path do arquivo
                $classe  = DIR_MODULOS . $this -> modulo . DS . $this -> ferramenta . '.class.php';
                # Verifica se existe o arquivo
                if (file_exists($classe)) {

                    # Inclui a classe
                    require_once $classe;
                    # Verifica se existe a classe no arquivo
                    if (class_exists($this -> ferramenta)) {

                        # Cria objeto
                        $obj = new $this -> ferramenta();
                        # Verifica se o método existe
                        if (method_exists($obj, $this -> acao)) {

                            # Executa o método
                            $retorno = $obj -> {$this -> acao}($this -> dados);
                            # Retorna a resposta
                            $this -> retorno = $retorno;

                        } else {
                            $this -> error = "Ação inexistente.";
                        }

                    } else {
                        $this -> error = "Ferramenta inválida 2.";
                    }

                } else {
                    $this -> error = "Ferramenta inválida 1.";
                }

            } else {
                $this -> error = "Módulo inválido.";
            }

        } else {
            $this -> error = "Erro na estrutura JSON.";
        }

    } else {
        $this -> error = "Erro ...!";
    }

}

Useful links:

file_exists

class_exists

method_exists

  • A detail: file_exists does not guarantee that the class exists.

  • @Andersoncarloswoss But the "module" and "tool" is what composes the path. So if there is none of the 2, it is already wrong. And the class has the same name as the file. Example: "Producao.class.php", the class is "Producao".

  • What if the file Producao.class.php exist but do not possess the class Producao?

  • Therefore, the class has the prefix of the file: "And the class has the same name as the file. Example: "Producao.class.php", the class is "Producao" ". Since the class is the "tool", what will change will only be the methods ("action").

  • 1

    But this does not prevent you from error of the programmer, which defines the class "Produgato" within the file "Producao.class.php". It will be interesting to verify the existence of the class with class_exists also.

  • Good, true! Implemented!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.