In the following article we show how to use mapping feature in database context.
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;
}
}
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());
}
}
namespace Test\Models;
use Vegas\Db\Decorator\CollectionAbstract;
class Fake extends CollectionAbstract
{
public function getSource()
{
return 'fake';
}
protected $mappings = array(
'encoded_field' => 'decoder'
);
}
$fake = new Fake();
$fake->encoded_value = base64_encode('test');
$fake->save();
//...
$result = Fake::findFirst();
$this->assertEquals('test', $result->readMapped('encoded_field'));
//....
$this->assertTrue(base64_encode('test'), $result->encoded_field);
$this->assertTrue(base64_encode('test'), $result->readAttribute('encoded_field'));