Search code examples
phpfat-free-framework

How to reset data mapper's virtual fields in 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?


Solution

  • 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);
    }