PHP - Trait or Extended Class

1

Good afternoon guys, I have a trait that formats data on a MVC system , the system works correctly, however I had a question regarding design pattern and performance, of the trait is correct or should you 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 template :

class User 
{
    const COLUMN = array(

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

    );

    use Model;
}
    
asked by anonymous 04.12.2018 / 19:45

1 answer

0

In this case inheriting would not be a problem if User is actually a specification of the more generic code that is in the trait. So you could turn this trait into an abstract class and inherit it.

It would also be more appropriate to rename the Model class to something more entity-oriented because it contains only code to set data for 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 an MVC layer that contains classes referring to the business rules of the application, so model is not necessarily a class called model, but rather a whole set of classes. Naming a class as a model does not add information to the code.

    
04.12.2018 / 23:31