|
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 |
mohrt Administrator
Joined: 16 Apr 2003 Posts: 7368 Location: Lincoln Nebraska, USA
|
Posted: Wed Dec 30, 2009 4:01 pm Post subject: Accessing Smarty 3 Instance |
|
|
It is often helpful to access the Smarty object from anywhere in your code. Although you could use a global variable, globals are not adequate for larger projects. The singleton pattern ensures that there is one and only one instance of the object available.
Implementation is quite trivial, just add one static method to your extended Smarty class:
Code: | <?php
require('Smarty.class.php');
class MySmarty extends Smarty
{
public static function getInstance($newInstance = null)
{
static $instance = null;
if(isset($newInstance))
$instance = $newInstance;
if ( $instance == null )
$instance = new MySmarty();
return $instance;
}
public function __construct()
{
parent::__construct();
// initialize smarty here
}
}
?>
|
To obtain an instance of the class:
Code: | // initialize smarty object
$smarty = MySmarty::getInstance();
// now obtain same object from anywhere
$smarty = MySmarty::getInstance(); |
The first time this is called a new instance will be created. Thereafter, the same instance is handed back. You can also set the instance manually:
Code: | // create new smarty object
$smarty = new MySmarty();
// set the instance object
MySmarty::getInstance($smarty);
// now obtain same object from anywhere
$smarty = MySmarty::getInstance(); |
|
|
Back to top |
|
SammyDC Smarty n00b
Joined: 02 Feb 2012 Posts: 1
|
Posted: Thu Feb 02, 2012 3:22 pm Post subject: |
|
|
Thanks this is helpful. |
|
Back to top |
|
koenpunt Smarty n00b
Joined: 22 Aug 2012 Posts: 1
|
Posted: Wed Aug 22, 2012 12:14 pm Post subject: |
|
|
Creating the static property $instance outside of your function call is probably better?
Code: |
<?php
require('Smarty.class.php');
class MySmarty extends Smarty
{
static $instance = null;
public static function getInstance($newInstance = null)
{
if( !is_null($newInstance) )
self::$instance = $newInstance;
if ( is_null(self::$instance) )
self::$instance = new MySmarty();
return self::$instance;
}
public function __construct()
{
parent::__construct();
// initialize smarty here
}
}
?>
|
|
|
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
|