DB.PHP - PHP ORM

Implement custom value type

Do you want that your property value was stored in json in database but you had actual structure in your class object? Or do you want that your property value was some string array but stored as string in database? Or generally do you want some custom property value that has custom structure when using and custom form when stored? Than this article is for you.

Let us go with json example. db.php has absract class \db\value. This class has two methods called void set(value) and `mixed get.

And it looks like:

abstract class value
{
    public function set ($value)
    {

    }
    public function get ()
    {
    }
}

Once the property of class implementing this abstract class is saved get method is called. Once property is restored or loaded set method is called.

Imagine you are have some kind of algorithm which crypts string data and also you can decrypt that data. You want plain text for some property when loaded but when stored crypted text. Assuming we have crypt and `decrypt magic methods we can implement this solution in two steps:

First extend \db\value class:

cryptable extends \db\value
{
    public $value;
    public function set ($value)
    {
        $this->value = decrypt($value);
    }
    public function get ()
    {
        return encrypt ($this->value);
    }
}

Second step is to use newly developed class cryptable by specifieng it as a type to a desired property. In this case imagine we are using it in password (and our system is easyly hackable).

class foo
{
    public $id;
    /**
    * @var cryptable
    */
    public $password;
}

Once object of class foo will be saved its property password value will be crypted and stored in table. Once this class object is loaded its field value will be decrypted and stored in property value.

With same trick we can store property value in json:

class json extends \db\value
{
    public $value;
    //orm wants to set your property
    public function set ($value)
    {
        $this->value = json_decode ($value);
    }
    //orm wants to get your property
    public function get ()
    {
        return json_encode ($this->value);
    }
}

Usage:

/**
* @var json
*/
public $somedata;

Just another example with string array:

namespace tools
{
    class listing extends \db\value
    {
        public $value;
        //orm wants to set your property
        public function set ($value)
        {
            $this->value = explode(',',$value);
        }
        //orm wants to get your property
        public function get ()
        {
            return implode (',',$this->value);
        }
    }
}

Additionaly you can set field type for custom value as by default it is char(128) for example like this:

/**
* type text
* @var \tools\listing
*/
public $mylisting;