Would PHP traits be a good solution

I'm working on a MVC application in which the Model is implemented using an abstract base class that all actual models have to extend. In every model there is some info about that model, currently implemented as an array, let call that protected static $info . So, every model has a different $info array. Now, the base class has lots of functions that use data from that array, and at the moment every one of those functions starts with something like the example save() function below.

abstract class BaseModel {
    function save(){
        $className = get_called_class();
        $modelInfo = $className::$info;
        /* lots of other stuff */
    }
}

class User extends BaseModel {
    protected static $info = array("tableName" => "tblUsers", etc...)
}

In my understanding, this can be resolved by making the BaseModel a trait instead of a constructor, since when traits define static properties, each inheriting class does have their own values. I would copy the $info array from the implementation of the Model to the trait, probably in the constructor, so that I can use self::info['tableName'] in all the functions in the BaseModel...

Would this be a good idea?


最简单和最合适的工具是使用晚期静态绑定:

function save(){
    $modelInfo = static::$info;
    /* lots of other stuff */
}
链接地址: http://www.djcxy.com/p/69378.html

上一篇: Symfony2用户实体提供程序中的致命错误

下一篇: PHP特质会是一个很好的解决方案