|
Smarty
WARNING: All discussion is moving to https://reddit.com/r/smarty, please go there! This forum will be closing soon. |
|
View previous topic :: View next topic |
Author |
Message |
chimericdream Smarty n00b
Joined: 04 Feb 2010 Posts: 2 Location: Lawrence, KS
|
Posted: Thu Feb 04, 2010 9:03 pm Post subject: Smarty "singleton" (with code) |
|
|
In our office, we had a need to access the smarty object from within the scope of modifiers. Unfortunately, modifiers do not have the object passed as a reference like functions do. We also do not always have our smarty object in the global scope, so it wouldn't necessarily be accessible via "global $smarty;".
Because of this need, we added a bit of singleton-esque code to the base Smarty class to allow modifiers to access smarty class functions without rewriting the way modifiers work.
Here is that code:
----------------------------------
Smarty.class.php
At the beginning of the configuration section (~line 66), add:
Code: | /**
* Stores the current instance of Smarty for use by modifiers
* (accessed through Smarty::getInstance())
*
* @var null|Smarty
*/
public static $_instance = null;
|
Add the following to the end of the class constructor (~line 580), add:
Code: | // Store the Smarty object into the $_instance variable so that modifiers
// can access it (if necessary)
self::$_instance = $this;
|
Add the following below the class constructor (~line 586), add:
Code: | /**
* Returns the current instance of Smarty for use by modifiers or other
* plugins
*
* @return Smarty
*/
public static function getInstance() {
return self::$_instance;
}
|
----------------------------------
As you can probably see, this is not a true singleton, because you cannot create a Smarty object from the getInstance. Its sole purpose is to provide access to the Smarty object that has already been created (regardless of scope).
Here is a link to the modifier (and its sister function) that we needed this functionality for.
http://www.smarty.net/forums/viewtopic.php?p=62502
Comments are welcome, but hopefully this will help someone else. _________________ Bill Parrott
Web Developer, University of Kansas
Co-Owner and Developer, Eternal Second Designs
Blogger and General Geek, ChimericDream |
|
Back to top |
|
mohrt Administrator
Joined: 16 Apr 2003 Posts: 7368 Location: Lincoln Nebraska, USA
|
|
Back to top |
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|