<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Refreshingly Blue &#187; Zend Framework</title>
	<atom:link href="http://www.refreshinglyblue.com/category/zend-framework/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.refreshinglyblue.com</link>
	<description>Notes by Lee Blue</description>
	<lastBuildDate>Sun, 29 Aug 2010 03:50:13 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>How To Count Rows With Zend_Db_Table</title>
		<link>http://www.refreshinglyblue.com/2009/11/18/how-to-count-rows-with-zend_db_table/</link>
		<comments>http://www.refreshinglyblue.com/2009/11/18/how-to-count-rows-with-zend_db_table/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 20:53:05 +0000</pubDate>
		<dc:creator>Lee</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.refreshinglyblue.com/?p=160</guid>
		<description><![CDATA[This is just a quick tip but seems to stump a lot of people, probably because it is not at all clear in the Zend Reference how to do this. So if you want to count the number of rows in a table using SQL you would write something like:
SELECT count(*) FROM myTableName WHERE someColumn='someValue';
But [...]]]></description>
			<content:encoded><![CDATA[<p>This is just a quick tip but seems to stump a lot of people, probably because it is not at all clear in the Zend Reference how to do this. So if you want to count the number of rows in a table using SQL you would write something like:</p>
<pre name="code" class="sql">SELECT count(*) FROM myTableName WHERE someColumn='someValue';</pre>
<p>But when you are using a Zend_Db_Table it&#8217;s a little confusing how to get the &#8220;count(*)&#8221; part to work because Zend_Db_Table likes to throw errors saying that it can&#8217;t be joined with other tables. So, in your Zend_Db_Table class, here is the syntax you can use:</p>
<pre name="code" class="php">
$sql = $this->select()
       ->from($this, 'COUNT(*)')
       ->where('parent_id=?', $this->id);
echo $this->fetchRow($sql)->num;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.refreshinglyblue.com/2009/11/18/how-to-count-rows-with-zend_db_table/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Zend_Db_Table Not Returning Last Insert Id</title>
		<link>http://www.refreshinglyblue.com/2008/11/03/zend_db_table-not-returning-last_insert_id/</link>
		<comments>http://www.refreshinglyblue.com/2008/11/03/zend_db_table-not-returning-last_insert_id/#comments</comments>
		<pubDate>Mon, 03 Nov 2008 23:50:40 +0000</pubDate>
		<dc:creator>Lee</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.refreshinglyblue.com/?p=75</guid>
		<description><![CDATA[I just discovered a significant &#8220;gotcha&#8221; debugging some code today. Judging from the comments on a variety of blogs and forums I think many of us have had this question. To cut to the chase, if you aren&#8217;t getting your last insert id returned when you do a Zend_Db_Table insert, make sure that the array [...]]]></description>
			<content:encoded><![CDATA[<p>I just discovered a significant &#8220;gotcha&#8221; debugging some code today. Judging from the comments on a variety of blogs and forums I think many of us have had this question. To cut to the chase, if you aren&#8217;t getting your last insert id returned when you do a Zend_Db_Table insert, make sure that the array that you are inserting does not have an empty string or a zero set in the primary key field. So, if your primary key column in your database is `id` then this will cause you problems:</p>
<pre name="code" class="php">
//NOTE: $table is an instance of class that extends Zend_Db_Table_Abstract
$data = array('id'=>'', 'color'=>'blue', 'size'=>'large');
$id = $table->insert($data);
echo $id; // --> will print an empty string
</pre>
<p>If you have to include the name of your primary key column as a key in the array you are tyring to insert, make sure it&#8217;s set to <em>null</em> NOT an empty string or zero.</p>
<pre name="code" class="php">
//NOTE: $table is an instance of class that extends Zend_Db_Table_Abstract
$data = array('id'=>null, 'color'=>'blue', 'size'=>'large')'
$id = $table->insert($data);
echo $id; // --> will print the id of the newly inserted row
</pre>
<p>The reason for this is line 822 in the Zend_Db_Table_Abstract class:</p>
<pre name="code" class="php">
if ($this->_sequence === true &#038;&#038; !isset($data[$pkIdentity])) {
  $data[$pkIdentity] = $this->_db->lastInsertId();
}
</pre>
<p>Notice the <em>isset()</em> condition. If primary key value in the data array you are inserting contains anything other than null then <em>isset()</em> will return true causing the lastInsertId() function to not get called. Hopefully this will clear things up and save us all alot of debugging time!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.refreshinglyblue.com/2008/11/03/zend_db_table-not-returning-last_insert_id/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Zend Framework: Redirect &#8211; The Easy Way</title>
		<link>http://www.refreshinglyblue.com/2008/10/28/zend-framework-redirect-the-easy-way/</link>
		<comments>http://www.refreshinglyblue.com/2008/10/28/zend-framework-redirect-the-easy-way/#comments</comments>
		<pubDate>Tue, 28 Oct 2008 17:30:47 +0000</pubDate>
		<dc:creator>Lee</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.refreshinglyblue.com/?p=63</guid>
		<description><![CDATA[It is common to need to redirect from one controller action to another or even from one controller to another when coding with the Zend Framework. From my code reviews, I find that many people are using the _redirect() method from Zend_Controller_Action. This function takes a url and an optional array of options. This is [...]]]></description>
			<content:encoded><![CDATA[<p>It is common to need to redirect from one controller action to another or even from one controller to another when coding with the Zend Framework. From my code reviews, I find that many people are using the <a href="http://framework.zend.com/apidoc/core/Zend_Controller/Zend_Controller_Action.html">_redirect() method from Zend_Controller_Action</a>. This function takes a url and an optional array of options. This is a fine choice if you need to redirect to a completely different website but the vast majority of redirect in a web application is to another action within the same application.</p>
<p>The lesser known, and much easier, way to redirect within the Zend Framework is to use the <a href="http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.redirector">Redirector Zend Controller Action Helper</a></p>
<p>The syntax is much easier since you don&#8217;t have to reconstruct a complete url, you just pass in the action and controller names. In fact, the only <em>required</em> parameter is the name of the action. If only an action name is given then the current controller is assumed to be the target controller. Here is a quick example.</p>
<pre name="code" class="php">
<?php
class exampleController extends Zend_Controller_Action {

  public function indexAction() {
    $this->_helper->redirector('target', 'example');
    // NOTE: 'example' is optional since the default target controller
    // is the current controller
  }

  public function targetAction() {
    // Do some things...
  }

}
?>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.refreshinglyblue.com/2008/10/28/zend-framework-redirect-the-easy-way/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Zend Framework: How To Disable A View In An Action</title>
		<link>http://www.refreshinglyblue.com/2008/09/17/zend-framework-how-to-disable-a-view-in-an-action/</link>
		<comments>http://www.refreshinglyblue.com/2008/09/17/zend-framework-how-to-disable-a-view-in-an-action/#comments</comments>
		<pubDate>Thu, 18 Sep 2008 02:27:35 +0000</pubDate>
		<dc:creator>Lee</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.refreshinglyblue.com/?p=58</guid>
		<description><![CDATA[Sometimes, especially when just testing things out, I don&#8217;t want to go to the trouble of having to create view script for my Controller Action and instead I just want to print something to the screen right from my Controller Action function. I guess because it&#8217;s sort of hard to find out how to do [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes, especially when just testing things out, I don&#8217;t want to go to the trouble of having to create view script for my Controller Action and instead I just want to print something to the screen right from my Controller Action function. I guess because it&#8217;s sort of hard to find out how to do this in the <a href="http://framework.zend.com/manual/en/zend.controller.action.html">ZF Documentation</a> this is one of the most common questions I get asked &#8211; even from somewhat seasoned developers. The answer is in the Controller documentation and it&#8217;s easy to think that you ought to search under the View documentation to figure out how to turn this stuff off. Whatever the case, here&#8217;s the trick.</p>
<p><span id="more-58"></span></p>
<p>In the action of your Controller, via your Zend Controller Action Helper Broker, call the setNoRender() function of your viewRenderer passing <strong>true</strong> as the parameter like this:</p>
<p>[php]<br />
<?php<br />
require_once('Zend/Controller/Action.php');</p>
<p>class SiteController extends Zend_Controller_Action {</p>
<p>  public function indexAction() {<br />
    $this->_helper->viewRenderer->setNoRender(true);<br />
    echo &#8220;Hello World!&#8221;;<br />
  }<br />
}</p>
<p>?><br />
[/php]</p>
<p>If you want to disable the View rendering for all of your actions, just call the setNoRender() function in your Controller&#8217;s init() function and none of the actions in your controller will render views. If you want to kill the entire idea of automatically rendering views in your application, you can globally disable the viewRenderer by setting the <strong>noViewRenderer</strong> parameter to <strong>true</strong> with your Front Controller in your bootstrap file &#8211; <strong>prior to calling dispatch()</strong>. Your code might look like this:</p>
<p>[php]<br />
<?php<br />
// This is your bootstrap file:<br />
// Perhaps your index.php file in your public directory</p>
<p>$frontController = Zend_Controller_Front::getInstance();<br />
$frontController->setParam(&#8216;noViewRenderer&#8217;, true);</p>
<p>?><br />
[/php]</p>
]]></content:encoded>
			<wfw:commentRss>http://www.refreshinglyblue.com/2008/09/17/zend-framework-how-to-disable-a-view-in-an-action/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Ecommerce with CodeIgniter</title>
		<link>http://www.refreshinglyblue.com/2008/05/15/ecommerce-with-codeigniter/</link>
		<comments>http://www.refreshinglyblue.com/2008/05/15/ecommerce-with-codeigniter/#comments</comments>
		<pubDate>Thu, 15 May 2008 23:06:00 +0000</pubDate>
		<dc:creator>Lee</dc:creator>
				<category><![CDATA[CodeIgniter]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.refreshinglyblue.com/2008/05/15/ecommerce-with-codeigniter/</guid>
		<description><![CDATA[Ironically the Zend Framework is marketed with the phrase &#8220;Extreme Simplicity &#38; Productivity&#8221;. I have developed a few sites with it now and I find it to be anything but simple and productive. It&#8217;s complicated, has a steep learning curve, and (in my opinion) needs a lot more work. I realize that I&#8217;m coming from [...]]]></description>
			<content:encoded><![CDATA[<p>Ironically the Zend Framework is marketed with the phrase &#8220;Extreme Simplicity &#38; Productivity&#8221;. I have developed a few sites with it now and I find it to be anything but simple and productive. It&#8217;s complicated, has a steep learning curve, and (in my opinion) needs a lot more work. I realize that I&#8217;m coming from a RoR background and that is a lot for a <span class="caps">PHP</span> framework to try to match. Nevertheless, I am quitting all Zend Framework development until more work can be done on the framework. Then, maybe I&#8217;ll reconsider.</p>
<p>I have found <a href="http://www.codeigniter.com">CodeIgniter</a> and have now built 3 sites with it. It&#8217;s simple, easy to use, speeds up development, has great documentation and, best of all, has won me as a fan. My most recent CodeIgniter project is an educational/e-commerce site about <a href="http://www.g-forcehealth.com">Rebounding with the Cellerciser</a> While developing the site and reading the site content, I was convinced of the many <a href="http://www.g-forcehealth.com/site/why-cellercise">reasons to use a Cellerciser</a> I&#8217;ve now been using a Cellerciser for about 3 months and I love this thing!</p>
<p><span id="more-22"></span></p>
<p>All this is to say that I&#8217;m developing with CodeIgniter now and I&#8217;m customizing my development for <span class="caps">PHP5</span>. Even though CodeIgniter is not strictly a <span class="caps">PHP5</span> framework (it will run under <span class="caps">PHP4</span> or <span class="caps">PHP5</span>) it does try to detect if it&#8217;s being run under <span class="caps">PHP5</span> and has several chunksk of <span class="caps">PHP5</span> specific code that get loaded if you are using <span class="caps">PHP5</span>. Then, you can code your own models and libraries using strict <span class="caps">PHP5</span> syntax &#8211; taking advantage of all the goodness that <span class="caps">PHP5</span> brings to the table.</p>
<p>I took a day or two to look into <a href="http://kohanaphp.com/home.html">Kohana</a> which is basically the <span class="caps">PHP5</span> only version of CodeIgniter. Kohana, being pure <span class="caps">PHP5</span>, has a few advantages over CodeIgniter. Here is <a href="http://thislab.com/2008/02/23/notes-on-choosing-a-php-framework-a-quick-comparison-of-codeigniter-and-kohana/">a great reivew comparing Kohana and CodeIgniter</a> In the review there are also a few tips on integrating the Zend Framework in with you CodeIgniter project &#8211; a much better use of the Zend Framework than building exclusively upon it.</p>
<p>Even though I exclusively use <span class="caps">PHP5</span> and Kohana takes much better advantage of <span class="caps">PHP5</span> than CodeIgniter does, I ended up sticking with CodeIgniter for the following reasons:</p>
<ul>
<li>Better documentation (although Kohana&#8217;s is very good too)</li>
<li>I felt like CodeIgniter had a more secure and substantial user base</li>
<li>Kohana does not have any unit testing (but it is coming in the next release)</li>
<li>More add-ons (ignited code) for CodeIgniter adding any &#8220;missing&#8221; feature you can think of</li>
</ul>
<p>My biggest complaint with CodeIgniter is the session handling. Session data is stored on the client side in a cookie. So you are limitted to 4kb of data. I prefer to store session data on the server side in a database. There are several add-ons for CodeIgniter that give you server side, database storage for session data.</p>
<p>If you have any questions about CodeIgniter, or comments about CodeIgniter vs Kohana, please feel free to share your thoughts!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.refreshinglyblue.com/2008/05/15/ecommerce-with-codeigniter/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>How To Sort A Zend_Db_Table_Rowset</title>
		<link>http://www.refreshinglyblue.com/2008/02/14/how-to-sort-a-zend_db_table_rowset/</link>
		<comments>http://www.refreshinglyblue.com/2008/02/14/how-to-sort-a-zend_db_table_rowset/#comments</comments>
		<pubDate>Thu, 14 Feb 2008 20:53:02 +0000</pubDate>
		<dc:creator>Lee</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.refreshinglyblue.com/2008/02/14/how-to-sort-a-zend_db_table_rowset/</guid>
		<description><![CDATA[So you figured out how to define the relationships between your Zend_Db_Tables and you have issued a call to findDependentRowset(). You get your Rowset back but you need to sort the results by one of the columns in the dependent table. How do you do that?
The short answer is, you can&#8217;t! Unfortunately, this functionality won&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>So you figured out how to define the <a href="http://framework.zend.com/manual/en/zend.db.table.relationships.html">relationships between your Zend_Db_Tables</a> and you have issued a call to findDependentRowset(). You get your Rowset back but you need to sort the results by one of the columns in the dependent table. How do you do that?</p>
<p>The short answer is, <strong>you can&#8217;t!</strong> Unfortunately, this functionality won&#8217;t be available until the 1.5 release of the Zend Framework. But you can write your own utitlity function to sort your Rowset for you.</p>
<p><span id="more-20"></span></p>
<p>In my project I am working with Patients and their Medications. There is a one to many relationship between patients and medications. One patient can have many medications but a medication belongs to only one patient. I have the following database tables and classes (stripped down for the sake of this example):</p>
<p>[mysql]<br />
CREATE TABLE patients (<br />
  id int auto_increment not null,<br />
  name varchar(50),<br />
  PRIMARY KEY(id)<br />
);</p>
<p>CREATE TABLE medications (<br />
  id int auto_increment not null,<br />
  patient_id int,<br />
  name varchar(50),<br />
  PRIMARY KEY(id)<br />
);<br />
[/mysql]</p>
<p>[php]<br />
// file: Patients.php</p>
<p>class Patients extends Zend_Db_Table_Abstract {<br />
  protected $_name = &#8220;patients&#8221;;<br />
  protected $_dependentTables = array(&#8220;Medications&#8221;);<br />
}<br />
[/php]</p>
<p>[php]<br />
// file: Medications.php</p>
<p>class Medications extends Zend_Db_Table_Abstract {<br />
  protected $_name = &#8220;medications&#8221;;<br />
  protected $_referenceMap = array(<br />
    &#8216;Patient&#8217; => array(<br />
      &#8216;columns&#8217;=>&#8217;patient_id&#8217;,<br />
      &#8216;refTableClass&#8217;=>&#8217;Patients&#8217;,<br />
      &#8216;refColumns&#8217;=>&#8217;id&#8217;<br />
    )<br />
  )<br />
}<br />
[/php]</p>
<p>Suppose then that you want to get an alphabetical list of all the medications a particular patient is taking. The code looks like this:</p>
<p>[php]<br />
// Make sure your Zend_Db_Table class is loaded<br />
Zend_Loader::loadClass(&#8220;Patients&#8221;);</p>
<p>// Instantiate your Zend_Db_Table class<br />
$patients = new Patients();</p>
<p>// Select Zend_Db_Table_Row for patient with id of 12<br />
$patient = $patients->find(12)->current();</p>
<p>// Select all of the medications for the patient<br />
$medications = $patient->findDependentRowset(&#8216;Medications&#8217;);<br />
[/php]</p>
<p>At this point, $medications now contains a Zend_Db_Table_Rowset that holds a list of Zend_Db_Table_Row objects representing the medications associated with our patient. Suppose now you want to sort the list of medications alphabetically by the name of the medication.</p>
<p>I was irked to learn that there was no way to tell <em>findDependentRowset()</em> to <em>order by</em> one of the selected columns. So I decided to start a Utilities class of static methods that I can use for situation such as this. I wrote the function sortRowsetBy()</p>
<p>[php]<br />
class DU_Utils {</p>
<p>  /**<br />
   * Sort a Zend_Db_Table_Rowset by the specified column<br />
   *<br />
   * @param Zend_Db_Table_Rowset &#8211; The Rowset to sort<br />
   * @param String $colName &#8211; The name of the column by which to sort the Rowset<br />
   * @return Array &#8211; An sorted array of Zend_Db_Table_Row objects<br />
   */<br />
  public static function sortRowsetBy($rowSet, $colName, $direction=&#8217;desc&#8217;) {<br />
    foreach($rowSet as $key => $row) {<br />
      $rows[] = $row; // Convert Rowset into an array of rows<br />
      $vals[$key] = $row->$colName; // Create array out of specified column name<br />
    }<br />
    // Sort the $rows array based on the $vals array<br />
    ($direction == &#8220;desc&#8221;) ? array_multisort($vals, SORT_DESC, $rows) : array_multisort($vals, SORT_ASC, $rows);</p>
<p>    return $rows;<br />
  }</p>
<p>}<br />
[/php]</p>
<p>The function makes use of a little known <span class="caps">PHP</span> function called <a href="http://us3.php.net/manual/en/function.array-multisort.php">array_multisort()</a>. This is a peculiar little function to grasp but it&#8217;s worth figuring out because of it&#8217;s power. There is a good bit of <a href="http://us3.php.net/manual/en/function.array-multisort.php">documentation on the <span class="caps">PHP</span> website</a> about what the parameters mean and what the function does. In a nutshell, this function sorts one array by another. In our context, the first array is essentially the column you want to sort by and the second array is the table you want to sort. In between the two arrays you can pass some flags to specify how you want to sort the array &#8211; ascending or descending &#8211; and the type of sort you want to perform &#8211; regular, numeric, or string. Note, that both arrays must be the same size in order for <em>array_mulitsort()</em> to do its job.</p>
<p>In conclusion, here is the code to sort our Rowset of medications alphabetically by the name of the medication.</p>
<p>[php]<br />
// Make sure your Zend_Db_Table class is loaded<br />
Zend_Loader::loadClass(&#8220;Patients&#8221;);</p>
<p>// Instantiate your Zend_Db_Table class<br />
$patients = new Patients();</p>
<p>// Select Zend_Db_Table_Row for patient with id of 12<br />
$patient = $patients->find(12)->current();</p>
<p>// Select all of the medications for the patient<br />
$medications = $patient->findDependentRowset(&#8216;Medications&#8217;);</p>
<p>// Sort the medications<br />
$medications = DU_Utils::sortRowsetBy($medications, &#8216;name&#8217;);</p>
<p>// Note that medications is now an array of Zend_Db_Table_Row objects<br />
// not a Zend_Db_Table_Rowset after the sort.</p>
<p>// Loop throught the sort list of medications<br />
foreach($medications as $med) {<br />
  // Do something with each medication<br />
  print($med->name);<br />
  print(&#8220;<br/>&#8220;);<br />
}<br />
[/php]</p>
]]></content:encoded>
			<wfw:commentRss>http://www.refreshinglyblue.com/2008/02/14/how-to-sort-a-zend_db_table_rowset/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How To Implement Partials In Zend Framework 1.0.3</title>
		<link>http://www.refreshinglyblue.com/2008/02/11/how-to-implement-partials-in-zend-framework-103/</link>
		<comments>http://www.refreshinglyblue.com/2008/02/11/how-to-implement-partials-in-zend-framework-103/#comments</comments>
		<pubDate>Tue, 12 Feb 2008 02:44:37 +0000</pubDate>
		<dc:creator>Lee</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.refreshinglyblue.com/2008/02/11/how-to-implement-partials-in-zend-framework-103/</guid>
		<description><![CDATA[The pre release of Zend Framework 1.5 has been out for a few days and includes an implementation for partials &#8211; among other things. But the GA release is still at least a few weeks off and I&#8217;ve got a project that needs to go live very soon. So, I&#8217;m using version 1.0.3 of the [...]]]></description>
			<content:encoded><![CDATA[<p>The pre release of Zend Framework 1.5 has been out for a few days and includes an <a href="http://framework.zend.com/manual/en/zend.view.helpers.html#zend.view.helpers.initial.partial">implementation for partials</a> &#8211; among <a href="http://devzone.zend.com/article/3020-Zend-Framework-1.5.0-Preview-Release-now-available">other things</a>. But the GA release is still at least a few weeks off and I&#8217;ve got a project that needs to go live very soon. So, I&#8217;m using version 1.0.3 of the Zend Framework released on 11/30/2007, and I want to make use of partials in my project. The trick involves three steps.</p>
<ol>
<li>Create a View Helper</li>
<li>Access your Zend_View object from the View Helper (or instantiate a new one)</li>
<li>Render a view script from within the View Helper</li>
</ol>
<p><span id="more-19"></span></p>
<h1>View Helpers</h1>
<p>Zend View Helpers were designed to make it easier to render somewhat complicated output that you might need to repeat multiple times throught your application. The Zend Framework comes with a handful of View Helpers for things like rendering form buttons, form fields, urls, and html lists. The Zend Framework Documentation, however, seems to suggest that View Helpers bundle their application logic with their presentation markup. For example, here is the code from the FormText.php view helper that comes with the Zend Framework.</p>
<p>[php]<br />
public function formText($name, $value = null, $attribs = null)<br />
{<br />
    $info = $this->_getInfo($name, $value, $attribs);<br />
    extract($info); // name, value, attribs, options, listsep, disable</p>
<p>    // build the element<br />
    if ($disable) {<br />
        // disabled<br />
        $xhtml = $this->_hidden($name, $value)<br />
               . $this->view->escape($value);<br />
    } else {<br />
        // enabled<br />
        $xhtml = &#8216;<br />
<input type="text"'<br />
               . ' name="' . $this->view->escape($name) . &#8216;&#8221;&#8216;<br />
               . &#8216; id=&#8221;&#8216; . $this->view->escape($id) . &#8216;&#8221;&#8216;<br />
               . &#8216; value=&#8221;&#8216; . $this->view->escape($value) . &#8216;&#8221;&#8216;<br />
               . $this->_htmlAttribs($attribs)<br />
               . &#8216; />&#8217;;<br />
    }</p>
<p>    return $xhtml;<br />
}<br />
[/php]</p>
<p>Notice in the <em>else</em> block how the markup is written out and stored in the $xhtml variable. For simple snippets, this is ok but if you have a complex view that you want to work with then you really need to break the presentation markup out of your View Helper and into a View Script.</p>
<h1>Access The View From Your ViewRenderer Or Instantiate A New Zend View</h1>
<p>The next thing the View Helper needs is a Zend_View object so that it can render the view script that holds the presentation markup. I chose to reuse the globally available Zend_View by accessing it from the ViewRenderer Helper like this.</p>
<p>[php]<br />
$view = Zend_Controller_Action_HelperBroker::getExistingHelper(&#8216;viewRenderer&#8217;)->view;<br />
[/php]</p>
<p>The benefits of reusing the Zend_View that you already have is that you do not have to worry with setting the basepath or the script path. Also, if you have done any customization of your Zend_View then you have access to the customizations from your View Helper. Note, however, that since you are litterally using the same Zend_View in your View Helper as you are using in your Controllers, you need to be mindful of variable clashes since everything is all in the same namespace. For example, if you set</p>
<p>[php]$this->view->someVariable = &#8220;some value&#8221;;[/php]</p>
<p>in your controller then you have access to this variable in your View Helper and the view script that your View Helper is rendering.</p>
<p>If you prefer to set up a new namespace for your View Helper and it&#8217;s view script, you can instantiate a new Zend_View in your View Helper. This also let&#8217;s you set up a different directory for storing the view scripts for your View Helper if you so wish. If you want to create a new Zend_View, you can do it like this.</p>
<p>[php]<br />
$config = Zend_Registry::get(&#8216;config&#8217;);<br />
$view = new Zend_View();<br />
$view->setScriptPath($config->basepath . &#8220;app/views/scripts&#8221;);<br />
[/php]</p>
<p>Note that I am storing my basepath in a config file for the sake of portability.</p>
<h1>Render A View Script From Your View Helper</h1>
<p>The last piece of the puzzle is rendering the markup code that we decoupled from the View Helper logic. The presentation markup for the View Helper is stored in a view script &#8211; just like the view scripts for your Controller&#8217;s actions. I store the view scripts for my partials in applications app/views/scripts/controllerName directory along with all my other view scripts. If you have a lot of view scripts or partials, feel free to store them in their own directory or however you want to organize them.</p>
<p>I am working on a project that manages medical records. I need to display a list of allergies for each patient in my system. I created a partial to which I pass the patient and the type of allergy list to display &#8211; drug allergies or other allergies. So, when all the pieces are put together, the code looks like this:</p>
<p>[php]<br />
/** The View Helper<br />
 * file: app/views/helpers/AllergyList.php<br />
*/</p>
<p>class Zend_View_Helper_AllergyList {</p>
<p>  public function allergyList($patient, $allergyType) {<br />
    $view = Zend_Controller_Action_HelperBroker::getExistingHelper(&#8216;viewRenderer&#8217;)->;view;<br />
    $view->patient = $patient;<br />
    $view->allergyType = $allergyType;<br />
    $out = $view->render(&#8220;vitalkey/prtlAllergy.phtml&#8221;);<br />
    return $out;<br />
  }<br />
}<br />
[/php]</p>
<p>[php]<br />
/** The View Helper&#8217;s View Script<br />
 * file: app/views/scripts/vitalkey/prtlAllergy.phtml<br />
*/</p>
<p><?php foreach($this->patient->getAllergies() as $allergy): ?><br />
  <?php if($allergy->allergy_type == $this->allergyType): ?></p>
<h1>
      <?php if(!empty($allergy->diagnosed_on)): ?><br />
        <span class="diagnosedDate">Diagnosed: <?= date("m/Y", strtotime($allergy->diagnosed_on)) ?></span><br />
      <?php endif; ?><br />
      <?= $allergy->name ?><br />
    </h1>
<p>    //&#8230; other code to display allergic reaction details</p>
<p>[/php]</p>
<p>[php]<br />
/** The View Script for the Controller Action<br />
 * file: app/views/scripts/vitalkey/patientData.phtml<br />
*/</p>
<p>//&#8230; Lots of patient data markup</p>
<h2>Drug Allergies</h2>
<div class="patientDataBox">
  <?= $this->allergyList($this->patient, &#8220;drug&#8221;); ?>
</div>
<h2>Other Allergies</h2>
<div class="patientDataBox">
  <?= $this->allergyList($this->patient, &#8220;other&#8221;); ?>
</div>
<p>//&#8230; Lots more patient data markup<br />
[/php]</p>
<p>So that is how I handle partials with Zend Framework 1.0.3. Let me know if you have any tips on how to improve any of this. Thanks for reading!mat</p>
]]></content:encoded>
			<wfw:commentRss>http://www.refreshinglyblue.com/2008/02/11/how-to-implement-partials-in-zend-framework-103/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Implement A Ruby on Rails style before_filter With The PHP Zend Framework</title>
		<link>http://www.refreshinglyblue.com/2008/01/30/how-to-implement-a-ruby-on-rails-style-before_filter-with-the-php-zend-framework/</link>
		<comments>http://www.refreshinglyblue.com/2008/01/30/how-to-implement-a-ruby-on-rails-style-before_filter-with-the-php-zend-framework/#comments</comments>
		<pubDate>Wed, 30 Jan 2008 17:17:55 +0000</pubDate>
		<dc:creator>Lee</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.refreshinglyblue.com/2008/01/30/how-to-implement-a-ruby-on-rails-style-before_filter-with-the-php-zend-framework/</guid>
		<description><![CDATA[I often use this when implementing a simple login screen for a password protected section of my application. In a Zend Framework application you can implement a preDispatch() function in a Zend_Controller_Action which will run before an action is dispatched. This lets you setup your filter to check to see if the visitor is logged [...]]]></description>
			<content:encoded><![CDATA[<p>I often use this when implementing a simple login screen for a password protected section of my application. In a <a href="http://framework.zend.com">Zend Framework</a> application you can implement a <a href="http://framework.zend.com/manual/en/zend.controller.plugins.html">preDispatch()</a> function in a Zend_Controller_Action which will run before an action is dispatched. This lets you setup your filter to check to see if the visitor is logged in or not. If the visitor is not logged in, you can redirect them to the login screen of your application.</p>
<h2>Setting Up Exceptions For preDispatch</h2>
<p>If your login screen is managed by a different controller, the setup described above is fine. If, however, your login screen is managed by an action in the same controller as the protected actions, you will want to allow unauthenticated access to the login screen. To do this, we need to exclude certain actions from the authentication check. Ruby on Rails let&#8217;s you define :except =&gt; :actionName to allow certain actions to skip the before_filter. With the Zend Framework, we have to implement that functionality on our own&#8230; but it&#8217;s easy.</p>
<h2>What Action Is Being Called?</h2>
<p>To set up your preDispatch function to skip checking to see if a user is logged in for certain actions you need to know which action is being called. You do that like this&#8230;</p>
<pre>
$action = $this-&gt;_request-&gt;getActionName();
</pre>
<h2>Example Code</h2>
<p>Now all you have to do is see if the action that is being called is one of the actions that you want to skip. I set up a private function called <em>verify()</em> to check whether or not the visitor is logged in. If the user is not logged in, I forward them to the loginAction() function. Since an unauthenticated user needs to be able to access the login screeen, we tell the <em>preDispatch()</em> function not to verify visitors requesting the login action. My controller ends up looking someting like this.</p>
<pre>
class AccountController extends Zend_Controller_Action {

  function preDispatch() {
    // Discover what action is being requested
    $action = $this-&gt;_request-&gt;getActionName();

    // Create a list of actions which allow unauthenticated access
    $exclusions = array("login");
    if(!in_array($action, $exclusions)) {
      $this-&gt;verify();
    }
  }

  /**
   * Check to see if the visitor is logged in. If not, send to loginAction
  */
  private function verifty() {
    $auth = Zend_Auth::getInstance();
    if(!$auth-&gt;hasIdentity()) {
      $this-&gt;_forward("login");
    }
  }

  function loginAction() {
    // Display your login screen
  }

  // Continue the rest of your class...
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.refreshinglyblue.com/2008/01/30/how-to-implement-a-ruby-on-rails-style-before_filter-with-the-php-zend-framework/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>QuietHeadphones.com Goes To Zend Framework</title>
		<link>http://www.refreshinglyblue.com/2008/01/24/quietheadphonescom-goes-to-zend-framework/</link>
		<comments>http://www.refreshinglyblue.com/2008/01/24/quietheadphonescom-goes-to-zend-framework/#comments</comments>
		<pubDate>Thu, 24 Jan 2008 07:59:34 +0000</pubDate>
		<dc:creator>Lee</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.refreshinglyblue.com/2008/01/24/quietheadphonescom-goes-to-zend-framework/</guid>
		<description><![CDATA[A while back I wrote about using Ruby on Rails to develop ]]></description>
			<content:encoded><![CDATA[<p>A while back I wrote about using Ruby on Rails to develop <a href="http://www.QuietHeadphones.com>QuietHeadphones.com</a>, a website that sells high quality <a href="http://www.quietheadphones.com>noise reduction headphones</a>. Tonight, we made the move to the Zend Framework. We did this for a variety of reasons including the fact that we are now hosting our site on a dedicated server with RackSpace. RackSpace is the absolute best hosting company on the planet provided you can afford their rates. RackSpace does not &#8220;officially&#8221; support Ruby on Rails. This was one of the significant factors in choosing the Zend Framework. Check back soon and I will have a fairly comprehensive comparison of our experience in developing an ecommerce website with the PHP Zend Framework versus our experience building the exact same site with Ruby on Rails.</p>
<p>In the meantime, we have two new products on the website. By popular demand, we now have an amazing set of <a href="http://www.quietheadphones.com/product/hp-25">speakerless noise reduction headphones</a>. We also have a great budget set of <a href="http://www.quietheadphones.com/product/ex-25">noise canceling headphones</a> that are smaller than our premier <a href="http://www.quietheadphones.com/product/ex-29">EX-29 Extreme Isolation Headphones</a>. This makes them <a href="">great for travel</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.refreshinglyblue.com/2008/01/24/quietheadphonescom-goes-to-zend-framework/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Add View Helper Paths For Entire Zend Framework Application</title>
		<link>http://www.refreshinglyblue.com/2008/01/17/add-view-helper-paths-for-entire-zend-framework-application/</link>
		<comments>http://www.refreshinglyblue.com/2008/01/17/add-view-helper-paths-for-entire-zend-framework-application/#comments</comments>
		<pubDate>Thu, 17 Jan 2008 19:53:47 +0000</pubDate>
		<dc:creator>Lee</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.refreshinglyblue.com/2008/01/17/add-view-helper-paths-for-entire-zend-framework-application/</guid>
		<description><![CDATA[I have been writing several Zend_View_Helpers to aid in the development of my Zend Framework Application. The helpers are very generic and are used in many of my Views throught my applications. So, naturally, I want an easy way to configure my Views to have access to my custom View Helpers. You don&#8217;t want to [...]]]></description>
			<content:encoded><![CDATA[<p>I have been writing several Zend_View_Helpers to aid in the development of my Zend Framework Application. The helpers are very generic and are used in many of my Views throught my applications. So, naturally, I want an easy way to configure my Views to have access to my custom View Helpers. You don&#8217;t want to override the init() function in <span class="caps">ALL</span> of your controllers to set the View Helper path. Instead, set it in the bootstrap file &#8211; your index.php file in the root directory of your website. You do it like this:</p>
<pre>
$view = new Zend_View();
$view-&gt;addHelperPath("DU/View/Helper", "DU_View_Helper");
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer-&gt;setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
</pre>
<p>Put those lines of code in your index.php file somewhere before you call dispatch() on your front controller and all of you view scripts will have access to your own library of View Helpers.</p>
<p>My company&#8217;s name is  Digital Underware so I have my library set up just like the Zend library in the lib directory of my application. The path to my View Helpers is lib/DU/View/Helper just like the path to the built-in Zend View Helpers is lib/Zend/View/Helper.</p>
<p>If you are interested in seeing a complete example, take a look at <a href="http://svn.spotsec.com/filedetails.php?repname=spotsecng-backup&#038;path=%2Fbranches%2Fpotatobob%2Fsrc%2Fwebconsole%2Fhtdocs%2Findex.php">this bootstrap file</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.refreshinglyblue.com/2008/01/17/add-view-helper-paths-for-entire-zend-framework-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
