Database mappers

In the following article we show how to use mapping feature in database context.

Create mappers

Database mappers is a simple mechanism, that provides auto-conversion the values stored in indicated field/column in database.
In the following example, we create a simple mapper, that decodes value using base64_decode function.
You can put this class to the lib/Vegas/Db/Mapping directory.

mkdir -p lib/Vegas/Db/Mapping
touch lib/Vegas/Db/Mapping/Decoder.php

namespace Vegas\Db\Mapping\Decoder;

use Vegas\Db\MappingInterface;

class Decoder implements MappingInterface
{
    /**
    * {@inheritdoc}
    */
    public function getName()
    {
        return 'decoder';
    }

    /**
    * {@inheritdoc}
    */
    public function resolve(& $value)
    {
        $value = base64_decode($value);

        return $value;
    }
}

Once we create mapper class, we can add a mapper to the application.
Update the application Bootstrap class, as follows:

use Vegas\Db\Mapping\Decoder;
use Vegas\Db\MappingManager;

class Bootstrap extends \Vegas\Mvc\Bootstrap
{
    public function setup()
    {
        parent::setup();
        $this->initDbMappings();

        return $this;
    }

    protected function initDbMappings()
    {
        $mappingManager = new MappingManager();
        $mappingManager->add(new Decoder());
    }
}

The last thing to make mapper enabled, is add a mapping to the model class.

namespace Test\Models;

use Vegas\Db\Decorator\CollectionAbstract;

class Fake extends CollectionAbstract
{
    public function getSource()
    {
        return 'fake';
    }

    protected $mappings = array(
        'encoded_field' =>  'decoder'
    );
}

Now, when you find record/document in the database, use method readMapped to retrieve converted value.

$fake = new Fake();
$fake->encoded_value = base64_encode('test');
$fake->save();
//...
$result = Fake::findFirst();
$this->assertEquals('test', $result->readMapped('encoded_field'));

The original value stored in database is still available:

//....
$this->assertTrue(base64_encode('test'), $result->encoded_field);
$this->assertTrue(base64_encode('test'), $result->readAttribute('encoded_field'));