2012年2月28日 星期二

[PHP] DataMapper 範例寫法

建立User model

class User{

    protected name;

    public function __construct(array $options = null)
    {
        if (is_array($options)) {
            $this->setOptions($options);
        }
    }
 
    public function __set($name, $value)
    {
        $method = 'set' . $name;
        if (('mapper' == $name) || !method_exists($this, $method)) {
            throw new Exception('Invalid guestbook property');
        }
        $this->$method($value);
    }
 
    public function __get($name)
    {
        $method = 'get' . $name;
        if (('mapper' == $name) || !method_exists($this, $method)) {
            throw new Exception('Invalid guestbook property');
        }
        return $this->$method();
    }
 
    public function setOptions(array $options)
    {
        $methods = get_class_methods($this);
        foreach ($options as $key => $value) {
            $method = 'set' . ucfirst($key);
            if (in_array($method, $methods)) {
                $this->$method($value);
            }
        }
        return $this;
    }

    public function setName($text)
    {
        $this->name = (string) $text;
        return $this;
    }

    public function getName()
    {
        return $this->name;
    }
}

建立User mapper

class UserMapper{
    public function fetch($ID, $User)
    {
        $result = $SQL ...
        //自行設定
        $User->setOptions($result);
        //OR
        $result = $this->setup($result);
        $User->setOptions($result);
        //欄位名稱必須與Model定義的變數名稱相同。
    }
    
    public function setup($result)
    {
        $data = array(
           ...
        );
        return $data;
    }
}

Controller 的使用

function user()
{
    $User = new User();
    $userMapper = new UserMapper();
    $userMapper->fetch($ID, $User);
    
    echo $User->getName();
}

//Output
//Ciao Chiang(Name)
//看資料庫的資料是甚麼

沒有留言:

張貼留言