Archive for February, 2009

Zend_View with variable reference support (aka assign_by_ref)

Posted on 2009-02-25. Filed under: php | Tags: , |

Sometimes it it desired to to assign values to the template namespace by reference instead of making a variable copy.

Because Zend_View lacks support of referenced variables, I wrote a simple class which extends Zend_View and implements this feature.

You may assign a variable of your choice “by reference” at the beginning of your code and modify it, reflecting changes in template variable scope automatically.

Example:

$cmsViewRenderer = new Cms_View();

$myVar="my text";

$cmsViewRenderer->assign("myVarStatic",$myVar);
$cmsViewRenderer->assign_by_ref("myVarReferenced",$myVar);

$myVar="my MODIFIED text";

echo " myVarStatic = "; var_dump($cmsViewRenderer->myVarStatic); echo "\n<br>"; 
echo " myVarReferenced = "; var_dump($cmsViewRenderer->myVarReferenced); echo "\n<br>";

Output:

myVarStatic = string(7) "my text"
myVarReferenced = string(16) "my MODIFIED text" 

Class body:

/**
 * View with the var references support
 * 
 * Inspired by SMARTY assign_by_ref 
 * @see http://smarty.net/manual/en/api.assign.by.ref.php
 * 
 * @author ChieftainY2k@gmail.com
 *
 */
class Cms_View extends Zend_View
{
    /**
     * References storage
     * @var array
     */
    private $_ref_vars = array();
    
    /**
     * Assign variable by reference. 
     * This is used to assign values to the templates by reference instead of making a copy
     * 
     * @param $name variable name
     * @param $data data
     * @return Cms_View
     */
    function assign_by_ref($name,&$data)
    {
        $this->_ref_vars[$name] = &$data;
        return $this;      
    }
    
    public function __get($key)
    {
        if (isset($this->_ref_vars[$key])) return $this->_ref_vars[$key];
        return parent::__get($key);
    }
    
    public function __isset($key)
    {
        if (isset($this->_ref_vars[$key])) return true;
        return parent::__isset($key);
    }
    
    
};

Read Full Post | Make a Comment ( None so far )

Liked it here?
Why not try sites on the blogroll...