PHP - Trait or Extended Class

Asked

Viewed 207 times

2

Good afternoon, you guys, I have a trait that format data from Models in a MVC system, the system works correctly, however came to me a doubt in relation to Pattern design and performance, in case, the use of the trait is correct or should consider extending a model class instead of using it as trait?

trait model:

trait Model
{
    function __construct($attributes=array())
    {
        if(sizeof($attributes) > 0){
            foreach ($attributes as $key => $value) {
                $this->$key = $value;
            }
        }
    }

    function __set($name, $value)
    {
        if(in_array($name, self::COLUMN)){
            $this->$name = $value;
        }
    }

    function __get($name)
    {
        if(isset($this->$name)){
            return $this->$name;
        }
    }

    function __unset($name)
    {
        if(isset($this->$name)){
            unset($this->name);
        }
    }
}

user model:

class User 
{
    const COLUMN = array(

        'iduser',
        'name',
        'email',
        'password',
        'permission',
        'status',
        'date_created'

    );

    use Model;
}
  • As stated in the PHP manual itself: "A Feature is intended to reduce some limitations of single inheritance by allowing a developer to freely reuse sets of methods in several independent classes residing in different class hierarchies.". Apparently this is not your case. So, no! Do not use Trait.

2 answers

4


To answer your questions we need to make it clear what they are Traits.

What is a Trait?

Traits are individual pieces of code that define methods that can be used by different classes to provide additional functionality. This is a feature introduced in PHP 5.4.

Traits are very similar to abstract classes, with some differences allowing them to be used by several independent classes at the same time. When I think of traits, I imagine a set of tools like screwdrivers (screwdrivers). If a class wants to use them, just ask.

Source: Imasters

It’s very interesting to think about the example of the hardware box, because that’s the idea. Roughly speaking, you would have with Traits, ways to create a set of functions that can be easily accessed by the classes. You know those functions that you build and end up using in several classes, but then you declare it within each class and consequently end up having a repeat of the code? Your troubles are over, the Traits are here to bring code reuse to your life.


Example:

trait Validacoes {

    public function validarCPF($cpf) {
        // Aqui vai a lógica de validação e retorna o resultado da mesma
        return true;
    }

    public function validarEmail($email) {
        // Aqui vai a lógica de validação e retorna o resultado da mesma
        return true;
    }

    public function validarCNPJ($cnpj) {
        // Aqui vai a lógica de validação e retorna o resultado da mesma
        return true
    }
}

In this trait for example I have ways to perform certain validations. I could use it in my class Usuario to validate data entries.

class Usuario {
    use Validacoes;

    private $cpf;
    private $email;
    private $cnpj;

    public function salvar($dados) {
        $this->cpf = $this->validarCPF($dados->cpf) ? $dados->cpf : '';
        $this->email = $this->validarEmail($dados->email) ? $dados->email : '';
        $this->cnpj = $this->validarCNPJ($dados->cnpj) ? $dados->cnpj : '';
    }
}

Could still use other traits within my class, just using use Validacoes, Utilidades;, in case I want to call another Trait called Utilities. It is worth noting that this is one of the advantages of this resource. An extended class has unique inheritance, but using traits, you can use as many as you like, even making it possible to resolve conflicts if different traits have the same function.

Unlike when you simply wear one include, calls a file with functions and uses them directly within the classes, the traits are compatible with the POO (Object Oriented Programming), this is a great advantage also in your case, because we are talking about a universe MVC.


Answering questions considering the MVC scope:

When thinking about the MVC universe, we could use the traits within a model or controller, depending on the need. In the specific case presented, which is better or more correct, use those functions you created within the trait or extend a model class? As already stated the main goal of the trait is to reuse code, so the answer to your question is simple, if your code is repeated in several classes, be they controller or model, use the trait, will facilitate maintenance.

About performance will simply not affect anything.


Completion

It is recommended to use traits whenever there are functions that are repeated in two or more classes, thus enabling code reuse.

0

In that case, inheriting would not be a problem if User is actually a specification of the most generic code that is in the trait. So you could turn this trait into an abstract class and inherit from it, because the inheritance relationship makes sense in these classes.

It would also be more appropriate to rename the class Model to something more for the entity, because it contains only code to set data to a given entity. In my view the name is the problem and not the fact that you are using a trait.

NOTE: It is important to remember that model is a layer of MVC that contains classes referring to the application’s business rules, so model is not necessarily a class called model, but a whole set of classes. Naming a class as a model does not add information to the code.

Browser other questions tagged

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