diff --git a/lib/moodlelib.php b/lib/moodlelib.php index dd68928..37d50e4 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -6679,6 +6679,92 @@ function get_string($identifier, $component = '', $a = NULL) { } /** + * The moodle string class + * + * This class was created especially to aid performance in areas where strings + * were required to be generated but not necessarily used. + * As an example the initial candidate for conversion was the admin tree structure + * which is generated as structure then what is required is displayed. + * For an Admin user this saw a 40% increase in admin tree generation and page load + * time. + * + * The performance advantage of this class is that the string is not actually + * generated/retrieved/constructed until it is required. + * + * You can use this class exactly as you would use get_string, of course you would + * need to qualify it for the new keywords. + * + * @package moodlecore + * + * @copyright 2011 Sam Hemelryk + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class moodle_string { + + /** + * The string identifier + * @var string + */ + protected $identifier; + /** + * The component the string belong to. Defaults to '' + * @var string + */ + protected $component; + /** + * Arguments to supply to the string. + * @var string|object|array + */ + protected $arguments; + /** + * The converted string once it is generated so that we don't need to + * generate it again. + * @var string + */ + protected $string = null; + + /** + * Creates the new moodle string object + * + * @param string $identifier + * @param string $component + * @param string|object|array $arguments + */ + public function __construct($identifier, $component = '', $arguments = null) { + $this->identifier = $identifier; + $this->component = $component; + $this->arguments = $arguments; + + // If the arguments are an object we need to take special precautions + // in order to ensure things don't change due to php5's object referencing. + if (is_object($this->arguments)) { + if (get_class($this->arguments) == 'stdClass') { + // If it is a stdClass we'll assume it is a small class and + // take a clone of it to ensure we keep it in it's current state + $this->arguments = clone($this->arguments); + } else { + // It is another type of object so we had better generate the + // string now just incase things change... ohh well no preformance + // gain here! + $this->string = get_string($this->identifier, $this->component, $this->arguments); + } + } + } + + /** + * Returns the string, generates the string as well if required. + * + * @return string + */ + public function __toString() { + if ($this->string === null) { + $this->string = get_string($this->identifier, $this->component, $this->arguments); + } + return $this->string; + } +} + +/** * Converts an array of strings to their localized value. * * @param array $array An array of strings