almost 4 years ago
protected/models/user.php
<?php
class User extends CActiveRecord
{ 

    protected $attributeTemps = array();
    protected $referPoint;
    
    const PM = 1;
    const SA = 2;
    const PG = 3;
    
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    
    public function tableName()
    {
        return 'tbl_user';
    }
        
    public function rules()
    {
        return array(
                array('username, password, email, type', 'required'),
                array('photo', 'safe'),
        );
    }
  
    public function getTypeMappers()
    {
        return array(
                self::PM => '專案經理',
                self::SA => '系統分析師',
                self::PG => '程式設計師',
        );
    }
  
    public function getText()
    {
        $attribute = ucfirst($this->referPoint);
        $methodName = "get{$attribute}Mappers";
        $resources = $this->$methodName();
        if (isset($resources[$this->attributeTemps[$this->referPoint]]))
            return $resources[$this->attributeTemps[$this->referPoint]];
        return '';
    }

    public function __call($method, $args)
    {
        if (array_key_exists($method, $this->attributes))
        {
            $this->referPoint = $method;
            $this->attributeTemps[$method] = $this->$method;
            return $this;
        }
        return parent::__call($method, $args);
    }
}

HOW TO USE?

test.php
<?php
$userType = User::PM;
# => 1

$user = User::model()->findById(1);
# => Object User

$user->type;
# => 1

$user->type()->getText();
# => '專案經理';
← PHP Warning: date(): It is not safe to rely on the system's timezone settings.... PHP array key->value 平行化 →