Should I use abstract class or interface?

2

I have a class that connects to Windows machines. I'm leaving it a bit more generic, so I can reuse it for other systems.

I was able to identify four "generic" methods:

  • connect
  • status
  • error message
  • run

With this, I put together a class and an interface, but my question is: In the scenario below, is it better to use an abstract class, or is an interface more than enough?

Connection class:

class Windows implements Conector
{
    /**
     * Armazena um apontamento externo para um recurso
     * 
     * @access private
     * @var object
     */
    private static $conexao;

    /**
     * Armazena a(s) mensagens de erro
     * 
     * @access private
     * @var string
     */
    private static $mensagemErro;

    /**
     * Método de conexão
     * 
     * @param   string $host
     * @param   string $usuario
     * @param   string $senha
     * @param   int $porta
     * @param   int $timeout
     * @return  void
     */
    public static function conectar($host, $usuario = null, $senha = null, $porta = 135, $timeout = 10)
    {
        try
        {
            /**
             * Método utilizado para testar conectividade com o host alvo
             * 
             * @param string $host
             * @param string $porta
             * @param int    $errno valor de sistema
             * @param string $errstr mensagem de sistema
             * @param int    $timeout tempo máximo a esperar por uma tentativa de conexão via socket
             */    
            if (!@fsockopen($host, $porta, $errno, $errstr, $timeout))
            {
                throw new Exception("Erro ({$errno}): Time Out ao chamar o host <b>{$host}</b>!");
            }

            //...

        } catch (Exception $e) {
            self::$mensagemErro =  $e->getMessage();
        }
    }

    public static function status()
    {
        return (self::$conexao !== NULL) ? TRUE : FALSE;
    }

    public static function mensagemErro()
    {
        return self::$mensagemErro;
    }

    public static function executar($acao)
    {
        try
        {
            if (!self::$conexao)
            {
                throw new Exception("Erro: É necessário abrir uma conexão antes de tentar executar qualquer comando!");
            }
             // @see http://php.net/manual/en/ref.com.php
            return self::$conexao->ExecQuery($query);
        }
        catch (Exception $e)
        {
            return $e->getMessage();
        }
    }

}

Interface:

interface Conector
{
    /**
     * Método de conexão para máquinas Windows
     * 
     * @param   string $host
     * @param   string $usuario
     * @param   string $senha
     * @param   int $porta
     * @param   int $timeout
     * @return  void
     */
    public static function conectar($host, $usuario = null, $senha = null, $porta = 135, $timeout = 10);

    public static function status();

    public static function mensagemErro();

    public static function executar($acao);
}
    
asked by anonymous 19.11.2016 / 18:23

1 answer

5

If you want to do it right, neither. At least with the names used. A class calls Windows , which I think is odd, does not seem like it should inherit or implement a Conector . This looks like design error.

But if you want to insist on interface should be preferred whenever possible . It seems that in this case it is possible, so it should do anyway.

If you wanted three standard implementations in these methods then the interface would no longer be possible. But a trait might be the solution (you have ask about it , other ).

If you need states (variables) and not just behaviors (methods), just the abstract class will resolve . Thinking about the class that implements the interface had to create variables. Is that what you wanted? let every implementation detail for the class decide how to do? If so, fine. If it was not the intention, if it wanted to already provide in this way implemented in the class, and who knows let the class overlap or not, then the class should be abstract, at the very least.

If all the behaviors are implemented in this class and you think it is useful to instantiate it in some situation, then the class must be concrete .

One more question already answered answers (there was already another, follow the links >).

Addendum

All these static members seem like a huge mistake. If it is to do this, do everything procedural, it has no advantage doing so.

I consider the use of the exception there in the wrong way, but this is something I almost gave up, almost everyone does wrong. I will not repeat here. In fact this was one of the biggest abuses I've ever seen in codes. In this case it is not only wrong, it is completely unnecessary.

The status method is doing something redundant.

That is, it seems that you are trying to catch an advanced concept when you have not yet mastered basic aspects of language. I would not go that way. But almost no one hears.

As well as make OOP overkill in PHP . See also: PHP mixes object-oriented and procedural language .

    
19.11.2016 / 18:47