jump to navigation

Zend Framework : Passing variables from the Controller to the View April 13, 2011

Posted by Tournas Dimitrios in Zend Framework v1.10.
trackback

We already know that in an MVC based framework the functionality is separated between the three main components : Model , Controller and View . This article will outline three ways to initialize variables within a Controller for use in the View . The developer can choose the one that fits it’s style of coding .

First method :

 public function songlistAction()
{
$songs= array ( "I'm a Fool to Want You (1951)" ,
"I've Got You Under My Skin (1956)" ,
 "The Way You Look Tonight (1964)" ,
 "Fly Me To the Moon (1966)" ,
  "The Way You Look Tonight (1964)");

//Set the view variables
$this->view->totalSongs= count($songs);
$this->view->songs=$songs ;
/**
* Accessing the variables from the View can be done as follows
*/
php
echo $this->totalSongs ;
echo $this->songs[1] ;  //First record in the array

}

Second method :

public function songlistAction()
{
$songs= array ( "I'm a Fool to Want You (1951)" ,
"I've Got You Under My Skin (1956)" ,
 "The Way You Look Tonight (1964)" ,
 "Fly Me To the Moon (1966)" ,
  "The Way You Look Tonight (1964)");
$totalSongs=array("totalSongs" => count($songs));
//Set the view variables
$this->view->assign($totalSongs);
$this->view->assign("songs" , $songs);
/**
* Accessing the variables from the View can be done as previous example
*/
php
echo $this->totalSongs ;
echo $this->songs[1] ;  //First record in the array

}

Third method :Using the StdClass

public function songlistAction()
{
$songs= array ( "I'm a Fool to Want You (1951)" ,
"I've Got You Under My Skin (1956)" ,
 "The Way You Look Tonight (1964)" ,
 "Fly Me To the Moon (1966)" ,
  "The Way You Look Tonight (1964)");
$totalSongs=array("totalSongs" => count($songs));
//Creat the Class
$songsObj = new StdClass;
$songsObj->songs=$songs;
//Set the view variables
$this->view->assign((array)$songsObj);
$this->view->assign($totalSongs);
/**
* Accessing the variables from the View can be done as previous example
*/

Try all three methods and see which one you like best . In all three instances , the information is rendered the same way , so the only thing you have to change is the way you initialize the variables .

Comments»

1. Md Sharif - July 3, 2013

nice (Y)

2. julio castillo - January 22, 2015

Perfect, the second method works at first time.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s