-1

这是我的课程,此类的实例知道何时应该保存该值。您如何看待这个想法以及这种实现的优点和缺点?

class Model_User_Doc extends ArrayObject {

    protected $_id;
    protected $_value;
    protected $_db;
    protected $_changed = FALSE;

    public function __construct($id = NULL) {
        if ($id !== NULL) {
            $this->_id = $id;
            $this->_db = DB::instance();
            $this->_value = $this->_db->get($id);
        }
    }

    public function __set($key, $value) {
        $this->_changed = TRUE;
        $this->_value[$key] = $value;
    }

    public function __get($key) {
        if (isset($this->_value[$key])) {
            return $this->_value[$key];
        }
        return NULL;
    }

    public function __unset($key) {
        $result = FALSE;        
        if (isset($this->_value[$key])) {
            $this->_changed = TRUE;
            unset($this->_value[$key]);
            $result = TRUE;
        }
        return $result;
    }

    public function offsetGet($name) {
        return $this->_value[$name];
    }

    public function offsetSet($name, $value) {
        $this->_changed = TRUE;
        $this->_value[$name] = $value;
    }

    public function offsetExists($name) {
        return isset($this->_value[$name]);
    }

    public function offsetUnset($name) {
        $this->_changed = TRUE;
        unset($this->_value[$name]);
    }

    public function cas() {
        if ($this->_changed === TRUE) {
            $this->save();
        }
    }

    public function save() {
        $this->_db->set($this->_id, $this->_value);
        $this->_changed = FALSE;
    }

    public function __destruct() {
        $this->cas();
    }

}

?>
4

1 回答 1

0

This should work.

There is some challenges with this though.

If a property is an array or object it becomes possible to change keys/properties within the property without ever triggering the __set and thereby triggering the dirty/changed flag.

You don't really have any say in the order in which destructors are called so save operations that require a value from another save operation (for foreign key management for example) can't be done without some monkey business.

There are some situations where the destructor will not be called. Read more here

于 2013-06-05T15:25:06.240 回答