douling1936 2016-10-26 10:12
浏览 42
已采纳

如何在Fat Free Framework中重置数据映射器的虚拟字段?

Let's start with an example given on FFF user guide. There is a database table:

CREATE TABLE products (
    productID VARCHAR(30),
    description VARCHAR(255),
    supplierID VARCHAR(30),
    unitprice DECIMAL(10,2),
    quantity INT,
    PRIMARY KEY(productID)
);

And I have a data mapper with a virtual field:

$item=new DB\SQL\Mapper($db,'products');
$item->totalprice='unitprice*quantity';

Let's say that I have performed some queries and I used this virtual field.

Now I would like to remove this virtual field, because I don't need it for further requests and I don't want to overload the data base with useless calculations. Is it possible?

  • 写回答

1条回答 默认 最新

  • duanbipu7601 2016-10-26 14:10
    关注

    The requirement is to remove a 'property' from an 'object instance'.

    The 'standard way' that 'models' are implemented in most PHP 'framework', 'orm' etc. it to implement them so that they can be accessed using 'array syntax'.

    Another approach is to implement some of the magic methods such as __unset.

    i.e. when you call unset($item->property); then the code is run to maintain it correctly.

    To be really flexible then implement both approaches in the 'base models'

    This is what FFF have done.

    see: classes: lib/magic.php and lib/base.php for all the gory details of how it is done.

    Taken from the source for magic.php...

    /**
    *   Alias for offsetunset()
    *   @return NULL
    *   @param $key string
    **/
    function __unset($key) {
        $this->offsetunset($key);
    }
    
    
    /**
    *   Convenience method for removing property value
    *   @return NULL
    *   @param $key string
    **/
    function offsetunset($key) {
        if (Base::instance()->visible($this,$key))
            unset($this->$key);
        else
            $this->clear($key);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?