Merge pull request #8795 from creative-commoners/pulls/4.3/improve-foreign-key-form-field-scaffolding

FIX Caching the result of counting a foreign list for performance
This commit is contained in:
Robbie Averill 2019-02-12 15:56:11 +07:00 committed by GitHub
commit 7a508af387
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -43,6 +43,13 @@ class DBForeignKey extends DBInt
private static $default_search_filter_class = 'ExactMatchFilter';
/**
* Cache for multiple subsequent calls to scaffold form fields with the same foreign key object
*
* @var array
*/
protected static $foreignListCache = [];
public function __construct($name, $object = null)
{
$this->object = $object;
@ -74,8 +81,21 @@ class DBForeignKey extends DBInt
// Don't scaffold a dropdown for large tables, as making the list concrete
// might exceed the available PHP memory in creating too many DataObject instances
$threshold = self::config()->get('dropdown_field_threshold');
if ($list->count() < $threshold) {
$field = new DropdownField($this->name, $title, $list->map('ID', $titleField));
// Add the count of the list to a cache for subsequent calls
if (!isset(static::$foreignListCache[$hasOneClass])) {
static::$foreignListCache[$hasOneClass] = [
'count' => $list->count(),
];
}
if (static::$foreignListCache[$hasOneClass]['count'] < $threshold) {
// Add the mapped list for the cache
if (!isset(static::$foreignListCache[$hasOneClass]['map'])) {
static::$foreignListCache[$hasOneClass]['map'] = $list->map('ID', $titleField);
}
$field = new DropdownField($this->name, $title, static::$foreignListCache[$hasOneClass]['map']);
$field->setEmptyString(' ');
} else {
$field = new NumericField($this->name, $title);