Skip to content

Instantly share code, notes, and snippets.

@Rayne
Last active February 1, 2017 14:29
Show Gist options
  • Save Rayne/fd24f5b664788cdf35956222ce790c02 to your computer and use it in GitHub Desktop.
Save Rayne/fd24f5b664788cdf35956222ce790c02 to your computer and use it in GitHub Desktop.
Fat-Free Framework: Mapper with ONLOAD event and custom derived non-virtual fields
<?php
/**
* This snippet is part of an answer to a StackOverflow question
* and is executable as soon as line 11 gets corrected
* to include Fat-Free Framework's `base.php` file.
*
* @see http://stackoverflow.com/questions/41840876/using-computed-properties-on-fatfree-mapper-object-not-retrieved-from-database
*/
require_once '../../base.php';
/**
* @property string title
*/
class TestMapper extends \DB\SQL\Mapper {
/**
* Custom mapper field which isn't backed and persisted by the database.
*
* @var null|string
*/
public $upper_title;
/**
* @param \DB\SQL $sql
*/
public function __construct(\DB\SQL $sql) {
parent::__construct($sql, 'test');
$this->onload(function (TestMapper $mapper) {
$mapper->upper_title = strtoupper($mapper->title);
});
}
}
// Create SQL environment.
{
$dbFile = 'test.sqlite';
// Reset environment.
if (is_file($dbFile)) {
unlink($dbFile);
}
$sql = new DB\SQL('sqlite:' . $dbFile);
$sql->exec('CREATE TABLE test(title TEXT)');
$sql->exec('INSERT INTO test (title) VALUES ("Hello World")');
/**
* Not compatible with tag `3.5.0`.
*
* > $mapper = new TestMapper($sql);
* > $mapper->title = 'Hello World';
* > $mapper->save();
*/
unset($dbFile);
}
$mapper = new TestMapper($sql);
for ($mapper->load(); !$mapper->dry(); $mapper->next()) {
printf("title: %s\n", $mapper->title);
printf("upper_title: %s\n", $mapper->upper_title);
}
title: Hello World
upper_title: HELLO WORLD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment