Last active
February 1, 2017 14:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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