<?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>Jam &#38; Cheese on PHPtoast</title>
	<atom:link href="http://jamandcheese-on-phptoast.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://jamandcheese-on-phptoast.com</link>
	<description>A Developer Blog!</description>
	<lastBuildDate>Fri, 22 Nov 2013 09:42:26 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.6.1</generator>
		<item>
		<title>Code Sign error: Certificate identity in Xcode</title>
		<link>http://jamandcheese-on-phptoast.com/2012/07/01/code-sign-error-certificate-identity-in-xcode/</link>
		<comments>http://jamandcheese-on-phptoast.com/2012/07/01/code-sign-error-certificate-identity-in-xcode/#comments</comments>
		<pubDate>Sun, 01 Jul 2012 08:18:30 +0000</pubDate>
		<dc:creator>mohammed</dc:creator>
				<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Xcode]]></category>

		<guid isPermaLink="false">http://jamandcheese-on-phptoast.com/?p=983</guid>
		<description><![CDATA[When my certificate identity expired recently, I had to renew it. This was completed successfully, but when I tried to build/run my new iPhone application, I got the following error: Code Sign error: Certificate identity ‘iPhone Developer: xxxxxxxx’ appears more than once in the keychain. The codesign tool requires there only be one. Ok. So [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>When my certificate identity expired recently, I had to renew it. This was completed successfully, but when I tried to build/run my new iPhone application, I got the following error:</p>
<p>Code Sign error: Certificate identity ‘iPhone Developer: xxxxxxxx’ appears more than once in the keychain. The codesign tool requires there only be one.</p>
<p>Ok. So that sounded simple enough and easy to fix.</p>
<p>I opened the Keychain Access (/Applications/Utilities/Keychain Access) and found 2 certificates under &#8220;My Certificates&#8221;. The expired certificate was marked with a Red “x”. I deleted that certificate and then tried running my app again. No success, and the same error message occurred again.</p>
<p>I checked all of the tabs in the Keychain Access, but still no success to find a second certificate.</p>
<p>I later found the option to show expired certificates (go to: View > Show Expired Certificates). I found the second expired certificate under the System tab.</p>
<p>Problem solved <img src='http://jamandcheese-on-phptoast.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://jamandcheese-on-phptoast.com/2012/07/01/code-sign-error-certificate-identity-in-xcode/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>fputcsv() function with SplFileObject</title>
		<link>http://jamandcheese-on-phptoast.com/2012/06/11/fputcsv-function-with-splfileobject/</link>
		<comments>http://jamandcheese-on-phptoast.com/2012/06/11/fputcsv-function-with-splfileobject/#comments</comments>
		<pubDate>Mon, 11 Jun 2012 08:10:57 +0000</pubDate>
		<dc:creator>mohammed</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://jamandcheese-on-phptoast.com/?p=973</guid>
		<description><![CDATA[The SplFileObject is a replacement object oriented approach for php filesystem functions. Not all of the functions are part of the SPL classes. fputcsv() is only available from PHP 5.4 onwards. However, it is not too hard to replicate the function if you are not using PHP 5.4. Here is how I implemented it, short [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>The <a href="http://php.net/manual/en/class.splfileobject.php" title="The SplFileObject class" target="_blank">SplFileObject </a>is a replacement object oriented approach for php filesystem functions. Not all of the functions are part of the SPL classes.</p>
<p><a href="http://php.net/manual/en/function.fputcsv.php" title="fputcsv" target="_blank">fputcsv()</a> is only available from PHP 5.4 onwards. However, it is not too hard to replicate the function if you are not using PHP 5.4. Here is how I implemented it, short and simple.</p>
<pre class="brush: php; title: ; notranslate">

class SplFileObject extends \SplFileObject
{

    /**
     * Format line as CSV and write to file pointer.
     * This method is only available as of PHP 5.4
     *
     * @return the number of bytes written, or NULL on error.
     */
    public function fputcsv($fields, $delimiter = ',', $enclosure = '&quot;')
    {
        array_walk($fields, function(&amp;$value, $index, $enclosure){
            $value = $enclosure . $value . $enclosure;
        }, $enclosure);

        return $this-&gt;fwrite(utf8_encode(join($delimiter, $fields)) . &quot;\n&quot;);
    }

}
</pre>
<p>Here is what I think is missing from the SPL file handling classes. A wrapper class is useful to manage deleting, copying, moving for file(s), and other functions that could change the location or the status of file(s).</p>
<pre class="brush: php; title: ; notranslate">

class SplFileHandler
{

    /**
     *
     * @var SplFileObject 
     */
    protected $fileObject;

    public function copy($source, $dest)
    {
        
    }

    public function unlink()
    {
        
    }

    //... other functions to handler files
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://jamandcheese-on-phptoast.com/2012/06/11/fputcsv-function-with-splfileobject/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Symfony2 Console Cheat Sheet</title>
		<link>http://jamandcheese-on-phptoast.com/2011/12/18/symfony2-console-cheat-sheet/</link>
		<comments>http://jamandcheese-on-phptoast.com/2011/12/18/symfony2-console-cheat-sheet/#comments</comments>
		<pubDate>Sun, 18 Dec 2011 09:12:34 +0000</pubDate>
		<dc:creator>mohammed</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Symfony2]]></category>

		<guid isPermaLink="false">http://jamandcheese-on-phptoast.com/?p=832</guid>
		<description><![CDATA[Symfony2 has many useful command lines to help you. The command lines can assist you with Symfony2 development and saves time when you are coding. I have listed below a few of the commands that I know of with details of how they can be used. If you know of a command that is missing [&#8230;]]]></description>
				<content:encoded><![CDATA[<style type="text/css">
    .syntaxhighlighter {
        margin:0 !important;
    }
</style>
<p>Symfony2 has many useful command lines to help you. The command lines can assist you with Symfony2 development and saves time when you are coding. I have listed below a few of the commands that I know of with details of how they can be used.<span id="more-832"></span> If you know of a command that is missing from the list, please feel free to add it in the comments. </p>
<p>To run these commands you must open CMD (window) or Terminal (MAC) and navigate to your Symfony2 root directory.</p>
<ul id="command-list">
<li>
<h3>Create a new bundle</h3>
<div class="code">
            <span class="structure">
<pre class="brush: bash; title: Structure; notranslate">php app/console generate:bundle --namespace=[namespace]/[bundle name]Bundle --format=[bundle configuration format]</pre>
<p></span><br />
            <span class="example">
<pre class="brush: bash; title: Example; notranslate">php app/console generate:bundle --namespace=Moo/UserBundle --format=yml</pre>
<p></span>
        </div>
<div class="desc">
<p>namespace is your company name the prefix that will identify your bundles from other bundles that you may have in your application.
<p>bundle name is what is it for? Examples of bundles: Blog bundle, User management bundle, Forum bundle, and so on. Bundle does not have to be accessbile from the web, you could create a bundle to manage internal functions such as integrating <a href="http://jquery.com" target="_blank">jQuery</a> framework. You can create as many as you like of bundles under your company namespace</p>
<p>There are 3 types of configuration format that you can choose from YML, XML &#038; PHP.</p>
</p></div>
</li>
<li>
<h3>Web resources. CSS, javascript &#038; images</h3>
<div class="code">
            <span class="structure">
<pre class="brush: bash; title: For operating system that does support symlinks; notranslate">php app/console assets:install web --symlink</pre>
<p></span><br />
            <span class="structure">
<pre class="brush: bash; title: For operating system that does not support symlinks; notranslate">php app/console assets:install web</pre>
<p></span>
        </div>
<div class="desc">
<p>As I said before bundles can be to manage internal functions (The jQuery bundle). These resources must be located under the directory
<pre class="brush: plain; gutter: false; title: ; toolbar: false; notranslate">/src/[namespace]/[bundle name]Bundle/Resources/public/</pre>
</p>
<p>This command is going to copy your files or create symlinks under
<pre class="brush: plain; gutter: false; title: ; toolbar: false; notranslate">/web/bundles/[namespace][bundle name]</pre>
</p></div>
</li>
<li>
<h3>Clear enviroment cache</h3>
<div class="code">
            <span class="structure">
<pre class="brush: bash; title: Structure; notranslate">php app/console cache:clear --env=[enviroment name]</pre>
<p></span><br />
            <span class="example">
<pre class="brush: bash; title: Example; notranslate">php app/console cache:clear --env=prod</pre>
<p></span>
        </div>
<div class="desc">
<p>&#8211;env is the name of the enviroment you want to remove its cache. Each subdirectory under
<pre class="brush: plain; gutter: false; title: ; toolbar: false; notranslate">/app/cache/</pre>
<p> is an enviroment.</p>
</p></div>
</li>
<li>
<h3>Install/Upgrade bundles and Symfony2</h3>
<div class="code">
            <span class="example">
<pre class="brush: bash; title: ; notranslate">php bin/vendors install</pre>
<p></span>
        </div>
<div class="desc">
<p>This commands installs or upgrade the bundles defined in the file
<pre class="brush: plain; gutter: false; title: ; toolbar: false; notranslate">/deps</pre>
</p></div>
</li>
<li>
<h3>Create database with doctrine2</h3>
<div class="code">
            <span class="example">
<pre class="brush: bash; title: ; notranslate">php app/console doctrine:database:create</pre>
<p></span>
        </div>
<div class="desc">
<p>This command will create the application database based on the parameters defined in
<pre class="brush: plain; gutter: false; title: ; toolbar: false; notranslate">app/config/parameters.ini</pre>
</p>
<p>This command will not create tables, it just create an empty database if it does not exists else it will throw an error.</p>
</p></div>
</li>
<li>
<h3>Mapping doctrine2 entities with the database</h3>
<div class="code">
            <span class="structure">
<pre class="brush: bash; title: Structure; notranslate">php app/console doctrine:generate:entities [namespace]</pre>
<p></span><br />
            <span class="example">
<pre class="brush: bash; title: Example; notranslate">php app/console doctrine:generate:entities Moo</pre>
<p></span>
        </div>
<div class="desc">
<p>You can run this command after changes to the ORM metadata for the entity classes. It will create getter and setter methods. But it will not modify any of the existing methods.</p>
</p></div>
</li>
<li>
<h3>Create tables in the database with doctrine2</h3>
<div class="code">
            <span class="example">
<pre class="brush: bash; title: ; notranslate">php app/console doctrine:schema:create</pre>
<p></span>
        </div>
<div class="desc">
<p>Based on the defined ORM metadata this command will create all of the tables.</p>
<p>If you don&#8217;t want to create the tables but return a dump of the SQL queries, then pass the following option
<pre class="brush: plain; gutter: false; title: ; toolbar: false; notranslate">--dump-sql</pre>
<p> to the right side of the command.</p>
</p></div>
</li>
<li>
<h3>Load fixtures with doctrine2</h3>
<div class="code">
            <span class="example">
<pre class="brush: bash; title: ; notranslate">php app/console doctrine:fixtures:load</pre>
<p></span>
        </div>
<div class="desc">
<p>Pre-requisition to install doctrine fixtures and DoctrineFixturesBundle.
<pre class="brush: plain; title: Add this to the file deps in root directory of Symfony2; notranslate">[doctrine-fixtures]
    git=http://github.com/doctrine/data-fixtures.git

[DoctrineFixturesBundle]
    git=http://github.com/symfony/DoctrineFixturesBundle.git
    target=/bundles/Symfony/Bundle/DoctrineFixturesBundle</pre>
<p>Then upgrade vendors to install the new bundles.</p>
</p></div>
</li>
<li>
<h3>Update schema with doctrine2</h3>
<div class="code">
            <span class="example">
<pre class="brush: bash; title: ; notranslate">php app/console doctrine:schema:update --force</pre>
<p></span>
        </div>
<div class="desc">
<p>This command will update the databse schema, if you have made some changes to a bundle entities and would like to update the schema accordenly.</p>
</p></div>
</li>
<li>
<h3>Data migrations with doctrine2</h3>
<div class="code">
            <span class="example">
<pre class="brush: bash; title: ; notranslate">php app/console doctrine:migrations:diff
php app/console doctrine:migrations:migrate</pre>
<p></span>
        </div>
<div class="desc">
<p>Pre-requisition to install doctrine migrations and DoctrineMigrationsBundle.
<pre class="brush: plain; title: Add this to the file deps in root directory of Symfony2; notranslate">[doctrine-migrations]
    git=http://github.com/doctrine/migrations.git

[DoctrineMigrationsBundle]
    git=http://github.com/symfony/DoctrineMigrationsBundle.git
    target=/bundles/Symfony/Bundle/DoctrineMigrationsBundle</pre>
<p>Then upgrade vendors to install the new bundles.</p>
<p>The first command finds out the differences between the entities and the database schema. The second one preform the migration.</p>
<p>This process will create a tables called &#8220;migration_versions&#8221;. This table stores the migration version numbers.</p>
</p></div>
</li>
<li>
<h3>Create form class with doctrine2</h3>
<div class="code">
            <span class="structure">
<pre class="brush: bash; title: ; notranslate">php app/console generate:doctrine:form [namespace][bundle name]Bundle:[entity name]</pre>
<p></span><br />
            <span class="example">
<pre class="brush: bash; title: ; notranslate">php app/console generate:doctrine:form MooBlogBundle:Comment</pre>
<p></span>
        </div>
<div class="desc">
<p>This command create a form type class based on an entity class</p>
</p></div>
</li>
<li>
<h3>Details on doctrine2 commands</h3>
<div class="code">
            <span class="example">
<pre class="brush: bash; title: ; notranslate">php app/console doctrine:schema:create --help</pre>
<p></span>
        </div>
<div class="desc">
<p>Adding &#8211;help at the end of each command will show you details of all possible options for the current command.</p>
</p></div>
</li>
<li>
<h3>Install ACL</h3>
<div class="code">
            <span class="example">
<pre class="brush: bash; title: ; notranslate">php app/console init:acl</pre>
<p></span>
        </div>
<div class="desc">This commands will create all the needed database tables for ACL to work. More details about ACL can be found in <a href="http://symfony.com/doc/2.0/cookbook/security/acl_advanced.html" target="_blank">Symfony2 Cookbook</a>
        </div>
</li>
<li>
<h3>Entities from an Existing Database</h3>
<div class="desc">
            Details can be found in Symfony2 <a href="http://symfony.com/doc/2.0/cookbook/doctrine/reverse_engineering.html">cookbook</a>
        </div>
</li>
</ul>
<h3>Related reads</h3>
<ul>
<li><a href="http://symfony.com/doc/2.0/book/doctrine.html" target="_blank">Symfony2 The Book (Doctrine)</a></li>
<li><a href="http://tutorial.symblog.co.uk/" target="_blank">Symfony2 Tutorial</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://jamandcheese-on-phptoast.com/2011/12/18/symfony2-console-cheat-sheet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>StackOverflow Answers (WordPress Widget)</title>
		<link>http://jamandcheese-on-phptoast.com/2011/02/03/stackoverflow-answers-widget/</link>
		<comments>http://jamandcheese-on-phptoast.com/2011/02/03/stackoverflow-answers-widget/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 21:56:17 +0000</pubDate>
		<dc:creator>mohammed</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[WordPress Widget]]></category>

		<guid isPermaLink="false">http://jamandcheese-on-phptoast.com/?p=479</guid>
		<description><![CDATA[Latest Version 0.5 Widget to display a summary of answers you have posted in StackOverflow. It will display the question&#8217;s title, the answer&#8217;s score, and the time the answer was last edited. You can limit the number of questions displaying and sort the list based on: Highest score. Oldest answer. Newest answer. ps. The widget [&#8230;]]]></description>
				<content:encoded><![CDATA[<div class="versionbox">Latest Version 0.5</div>
<p>Widget to display a summary of answers you have posted in <a href="http://stackoverflow.com/" target="_blank">StackOverflow</a>. It will display the question&#8217;s title, the answer&#8217;s score, and the time the answer was last edited.</p>
<p>You can limit the number of questions displaying and sort the list based on:</p>
<ul>
<li>Highest score.</li>
<li>Oldest answer.</li>
<li>Newest answer.</li>
</ul>
<p><span id="more-479"></span></p>
<p><strong>ps. The widget uses StackOverflow API version 1.0. The content of this widget is cached and updated every day.</strong></p>
<div style="text-align:center">
<img src="http://jamandcheese-on-phptoast.com/wp-content/uploads/2011/02/osstack-widget.gif" alt="StackOverflow Answers" />
</div>
<h3>Installation:</h3>
<ol>
<li>Upload plugin folder to the wp-content/plugins/ directory.</li>
<li>Go to plugin page in WordPress, and click &#8220;Activate&#8221;.</li>
<li>Go to widgets page in WordPress and drag StackOverflow Answers Widget to a widget area.</li>
<li>Set configuration:
<ul>
<li>Set widget title.</li>
<li>User number can be found in profile URL (http://stackoverflow.com/users/Your User Number]/[Your Username])</li>
<li>Consumer Key can be found by <a href="http://stackapps.com/apps/register" target="_blank">registering</a> your widget. <strong>This is optional</strong>.</li>
<li>Set number of questions to show.</li>
<li>Set how you want to sort the list.</li>
</ul>
</li>
</ol>
<h3>Requirement:</h3>
<ul>
<li>json_decode must be available.</li>
<li>PHP5 or higher.</li>
<li><a href="http://stackapps.com/questions/2/api-hello-world-code" target="_blank">StackOverflow API Key</a> is optional.</li>
</ul>
<h3>Download:</h3>
<p>Download the plugin from <a href="http://wordpress.org/extend/plugins/stackoverflow-answers-widget/" target="_blank">WordPress</a></p>
]]></content:encoded>
			<wfw:commentRss>http://jamandcheese-on-phptoast.com/2011/02/03/stackoverflow-answers-widget/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>New Magento Extension &quot;Moo_CloudZoom&quot;</title>
		<link>http://jamandcheese-on-phptoast.com/2010/09/09/new-magento-extension-moo_cloudzoom/</link>
		<comments>http://jamandcheese-on-phptoast.com/2010/09/09/new-magento-extension-moo_cloudzoom/#comments</comments>
		<pubDate>Thu, 09 Sep 2010 05:22:31 +0000</pubDate>
		<dc:creator>mohammed</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Cloud Zoom]]></category>
		<category><![CDATA[Magento Extension]]></category>

		<guid isPermaLink="false">http://jamandcheese-on-phptoast.com/?p=413</guid>
		<description><![CDATA[Latest Version 1.2.1 Overview I have released a new extension for the Magento E-commerce system. The extension is a replacement for my first extension “Magento JQZoom”. The new extension has more features including: Smooth zoom movement. Define the dimensions of the zoom window. Define the position of the zoom window. Z/Y pixel spaces for the [&#8230;]]]></description>
				<content:encoded><![CDATA[<div class="versionbox">Latest Version 1.2.1</div>
<h3>Overview</h3>
<p>I have released a new extension for the Magento E-commerce system. The extension is a replacement for my first extension “Magento JQZoom”.</p>
<p>The new extension has more features including:</p>
<ul>
<li>Smooth zoom movement.</li>
<li>Define the dimensions of the zoom window.</li>
<li>Define the position of the zoom window.</li>
<li>Z/Y pixel spaces for the zoom window.</li>
<li>Show or Hide the title on top of the zoom window. Also, define the opacity.</li>
<li>Define lens opacity.</li>
<li>Dimensions of the main image.</li>
<li>Soft focus and inner zoom features.</li>
<li>Overlay color and opacity on hover.</li>
</ul>
<p>The the javascript is based on <a target="_blank" href="http://www.professorcloud.com/mainsite/cloud-zoom.htm">Cloud Zoom</a> plugin for JQuery.</p>
<p>You can view the extension in <a target="_blank" href="http://www.magentocommerce.com/extension/packages/module/4224/moo_cloudzoom">Magento connect</a>. Or you can download the file and install it manually from <a target="_blank" href="http://jamandcheese-on-phptoast.com/wp-content/uploads/2013/10/Moo_CloudZoom-1.2.1.zip">here</a>.</p>
<p><span id="more-413"></span></p>
<h3>Manual Install</h3>
<ol>
<li>Download the <a target="_blank" href="http://jamandcheese-on-phptoast.com/wp-content/uploads/2013/10/Moo_CloudZoom-1.2.1.zip">zip file</a>.</li>
<li>Extract the content of the file. </li>
<li>Copy and Paste the folder Moo/ into /app/code/community/</li>
<li>Copy and Paste the folder modules/ into /app/etc/</li>
<li>Copy and Paste the folder skin/ into /[the root directory of your Magento installation]</li>
<li>Copy and Paste the folder design/ into /app/
<li>Login into you admin interface. Go to System > Configuration > Catalog > Moo Product Gallery &#8220;CloudZoom&#8221; to configure the plugin</li>
</ol>
<h3>FAQ</h3>
<dl>
<dt>When I view the configuration page, I get 404 page not found, or 403 access denied?</dt>
<dd>This is common problem when installing any Magento extension. To fix this you need to refresh the role permission. Go to System > Permissions > Roles > Administrators and click Save Role.</dd>
<dt>Does it work with Magento stable 1.5.0.1?</dt>
<dd>Yes</dd>
<dt>I cannot install the extension. I am getting the following error:</p>
<pre class="brush: plain; title: ; notranslate">Failed to download magento-community/Moo_CloudZoom within preferred state &quot;stable&quot;, latest release is version 1.1.1, stability &quot;beta&quot;, use &quot;channel://connect.magentocommerce.com/community/Moo_CloudZoom-1.1.1&quot; to install  
Cannot initialize 'channel://connect.magentocommerce.com/community/Moo_CloudZoom', invalid or missing package file  
Install Errors  
Package &quot;channel://connect.magentocommerce.com/community/Moo_CloudZoom&quot; is not valid  
PEAR ERROR: install failed  </pre>
</dt>
<dd>This is because your Magento Connect is set to install extensions with stable version only. This extension is beta. To fix this in Magento Connect click on the settings tab and change the preferred state to beta.</dd>
</dl>
<p></p>
<p>Enjoy! <img src="http://jamandcheese-on-phptoast.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley"> </p>
]]></content:encoded>
			<wfw:commentRss>http://jamandcheese-on-phptoast.com/2010/09/09/new-magento-extension-moo_cloudzoom/feed/</wfw:commentRss>
		<slash:comments>66</slash:comments>
		</item>
		<item>
		<title>Magento Tips</title>
		<link>http://jamandcheese-on-phptoast.com/2010/07/20/magento-tips/</link>
		<comments>http://jamandcheese-on-phptoast.com/2010/07/20/magento-tips/#comments</comments>
		<pubDate>Tue, 20 Jul 2010 07:57:13 +0000</pubDate>
		<dc:creator>mohammed</dc:creator>
				<category><![CDATA[Magento]]></category>

		<guid isPermaLink="false">http://jamandcheese-on-phptoast.com/?p=374</guid>
		<description><![CDATA[Design customisation for CMS page: Adding custom CSS class name in the body tag Remove a block area_name: is the name of the section in a page layout. For example left, footer, header, etc&#8230;. block_name: is the name of the block you want to remove. For example, breadcrumbs, topMenu, etc&#8230;. Change the logo src and [&#8230;]]]></description>
				<content:encoded><![CDATA[<h3>Design customisation for CMS page:</h3>
<dl>
<dt><strong>Adding custom CSS class name in the body tag</strong></dt>
<dd>
<pre class="brush: xml; title: ; notranslate">
&lt;reference name=&quot;root&quot;&gt;
    &lt;action method=&quot;addBodyClass&quot;&gt;
        &lt;classname&gt;new_class_name&lt;/classname&gt;
    &lt;/action&gt;
&lt;/reference&gt;
</pre>
</dd>
<dt><strong>Remove a block</strong></dt>
<dd>
<pre class="brush: xml; title: ; notranslate">
&lt;reference name=&quot;area_name&quot;&gt;
    &lt;remove name=&quot;block_name&quot; /&gt;
&lt;/reference&gt;
</pre>
<p>area_name: is the name of the section in a page layout. For example left, footer, header, etc&#8230;.<br />
block_name: is the name of the block you want to remove. For example, breadcrumbs, topMenu, etc&#8230;.
</dd>
<p><span id="more-374"></span></p>
<dt><strong>Change the logo src and alternative text</strong></dt>
<dd>
<pre class="brush: xml; title: ; notranslate">
&lt;reference name=&quot;header&quot;&gt;
    &lt;action method=&quot;setLogoSrc&quot;&gt;
        &lt;src&gt;images/new-logo.gif&lt;/src&gt;
    &lt;/action&gt;
    &lt;action method=&quot;setLogoAlt&quot; translate=&quot;alt&quot; module=&quot;catalog&quot;&gt;
        &lt;alt&gt;New alternative text....&lt;/alt&gt;
    &lt;/action&gt;
&lt;/reference&gt;
</pre>
</dd>
<dt><strong>Adding a static block to a CMS page</strong></dt>
<dd>
<pre class="brush: php; title: ; notranslate">
{{block type=&quot;cms/block&quot; block_id=&quot;block_id&quot;}}
</pre>
</dd>
</dl>
<h3>Customise a block</h3>
<p>Lets say that you would like to show a lists of new products in the home page. Then you should add the following code in the CMS homepage content:</p>
<pre class="brush: php; title: ; notranslate">

{{block type=&quot;catalog/product_new&quot; name=&quot;home.catalog.product.new&quot; alias=&quot;product_homepage&quot; template=&quot;catalog/product/new.phtml&quot;}}

</pre>
<p>Now, what if we want to limit the product list based on a category. Then we need to pass a category id to the block class. We can do this by changing the above code to:</p>
<pre class="brush: php; title: ; notranslate">

{{block type=&quot;catalog/product_new&quot; name=&quot;home.catalog.product.new&quot;
           alias=&quot;product_homepage&quot; template=&quot;catalog/product/new.phtml&quot;  category_id=&quot;4&quot;}}

</pre>
<p>Now we can show a list of all new products in category ID 4. The above code will not work as we still need to modify the default block class with our new changes.</p>
<p><strong>Extending the block class</strong></p>
<ol>
<li>
    Create new module configuration file in app/etc/modules/Prefix_Catalog.xml</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;config&gt;
    &lt;modules&gt;
        &lt;Prefix_Catalog&gt;
            &lt;active&gt;true&lt;/active&gt;
            &lt;codePool&gt;local&lt;/codePool&gt;
        &lt;/Prefix_Catalog&gt;
    &lt;/modules&gt;
&lt;/config&gt;
</pre>
</li>
<li>Create a folder named Prefix inside app/code/local</li>
<li>Create a folder inside the Prefix folder named Catalog</li>
<li>Create a folder inside Catalog named etc. Then inside it create an xml file named config.xml
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;config&gt;
    &lt;modules&gt;
        &lt;Prefix_Catalog&gt;
            &lt;version&gt;0.1&lt;/version&gt;
        &lt;/Prefix_Catalog&gt;
    &lt;/modules&gt;
    &lt;global&gt;
    	&lt;blocks&gt;
              &lt;catalog&gt;
                &lt;rewrite&gt;
                        &lt;product_new&gt;Prefix_Catalog_Block_Product_New&lt;/product_new&gt;
                &lt;/rewrite&gt;
            &lt;/catalog&gt;
        &lt;/blocks&gt;
    &lt;/global&gt;
&lt;/config&gt;
&lt;/config&gt;
</pre>
</li>
<li>Create another folder inside Catalog named Block, then another folder inside Block named Product</li>
<li>Create a php file that will contain the block class
<pre class="brush: php; title: ; notranslate">
class Prefix_Catalog_Block_Product_New extends Mage_Catalog_Block_Product_New
{
    protected function _beforeToHtml()
    {
        // if there are no category id provided then use the parent method
        $categoryId = $this-&gt;getCategoryId();
        if (empty($categoryId)) {
            return parent::_beforeToHtml();
        }

        $beforeHtml = parent::_beforeToHtml();

        // filter product collection by category id
        $category = Mage::getModel('catalog/category')-&gt;load($categoryId);
        $collection = $this-&gt;getProductCollection()-&gt;addCategoryFilter($category);
        $this-&gt;setProductCollection($collection);

	return $beforeHtml;
    }

    public function getCategoryId()
    {
    	return (int)$this-&gt;getData('category_id');
    }
}
</pre>
<p>As you can see from the code above, you can retrieve the category id by using the method &#8220;getData&#8221;. Also, we have extended the core class and override the method &#8220;_beforeToHtml&#8221;. We can add extra code to check if we have a category id passed to the block. Then we filter the product collection by that category id.</p>
<p>You can pass any number of parameters to the block.</p>
<pre class="brush: php; title: ; notranslate">

{{block type=&quot;catalog/product_new&quot; name=&quot;home.catalog.product.new&quot; alias=&quot;product_homepage&quot; template=&quot;catalog/product/new.phtml&quot;  category_id=&quot;4&quot; max_price=&quot;20.00&quot;}}

</pre>
<p>To retrieve the new parameter:</p>
<pre class="brush: php; title: ; notranslate">

$this-&gt;getData('max_price');

</pre>
</li>
</ol>
<p>Hope these tips helped.</p>
]]></content:encoded>
			<wfw:commentRss>http://jamandcheese-on-phptoast.com/2010/07/20/magento-tips/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom Module Bootstrap Class</title>
		<link>http://jamandcheese-on-phptoast.com/2010/02/01/custom-module-bootstrap-class/</link>
		<comments>http://jamandcheese-on-phptoast.com/2010/02/01/custom-module-bootstrap-class/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 06:32:49 +0000</pubDate>
		<dc:creator>mohammed</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[Zend_Application]]></category>
		<category><![CDATA[Zend_Application_Module_Bootstrap]]></category>
		<category><![CDATA[Zend_Controller_Plugin_Abstract]]></category>

		<guid isPermaLink="false">http://jamandcheese-on-phptoast.com/?p=292</guid>
		<description><![CDATA[In my Zend Framework application I wanted a bootstrap class for every module. Each bootstrap class will instantiate confirguration specific for each module. You do not have to add a bootstrap class to a module if no confirguration is required for that module. I first looked at Zend_Application_Resource_Modules, but it loads all the bootstrap files [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
In my Zend Framework application I wanted a bootstrap class for every module. Each bootstrap class will instantiate confirguration specific for each module. You do not have to add a bootstrap class to a module if no confirguration is required for that module.
</p>
<p><span id="more-292"></span></p>
<p>
I first looked at <a target="_blank" href="http://framework.zend.com/manual/en/zend.application.available-resources.html#zend.application.available-resources.modules">Zend_Application_Resource_Modules</a>, but it loads all the bootstrap files for each module in my application. This is not what I wanted to achive.
</p>
<h3>Here is my attempt to achieve my goal</h3>
<p>Create a controller plugin. I called it Moo_Controller_Plugin_Init</p>
<pre class="brush: php; title: ; notranslate">
/**
 *
 * @copyright  2009 Mohammed Alsharaf
 * @author      Mohamed Alsharaf 
 * @category   Moo
 * @package    Moo_Controller
 * @copyright  Copyright (c) 2009-2010 Mohammed Alsharaf.
 * @license      http://framework.zend.com/license/new-bsd
 * @version      Release: 0.0.2
 * @link           http://jamandcheese-on-phptoast.com/
 */
class Moo_Controller_Plugin_Init extends Zend_Controller_Plugin_Abstract
{
	public function preDispatch(
            Zend_Controller_Request_Abstract $request) 
    {
            // include bootstrap if it's exists
            $bootstrap = APPLICATION_PATH  . 'modules/' . $module . '/Bootstrap.php';
            if(!file_exists($bootstrap)) {
                return false;
            }
            require_once $bootstrap;

            // format module name
            $module = $this-&gt;_formatModuleName($module);
            // instantiate bootstrap and pass any object/data you want
            $class = $module . '_Bootstrap';
            $moduleBootstrap = new $class();
            $moduleBootstrap-&gt;setRequest($this-&gt;getRequest())
            -&gt;setResponse($this-&gt;getResponse())
            -&gt;init();
	}
    protected function _formateModuleName($module) 
    { 
            if(strpos($module, '-') !== false) {
                $filter = new Zend_Filter_Word_DashToCamelCase();
                $module = $filter-&gt;filter($module);
            } elseif(strpos($module, '_') !== false) {
                $filter = new Zend_Filter_Word_UnderscoreToCamelCase();
                $module = $filter-&gt;filter($module);
            } else {
                $module = ucfirst($module);
            }
            return $module;
    }
}
</pre>
<p>Register the controller plugin in front controller. This will depend on how you have the configuration setup. You can either add the plugin from the application.ini file by adding</p>
<pre class="brush: php; title: ; notranslate">
resources.frontController.plugins.init = &quot;Moo_Controller_Plugin_Init&quot;
</pre>
<p>Or by calling the method &#8220;registerPlugin&#8221; in Zend_Controller_Front.</p>
<pre class="brush: php; title: ; notranslate">
$front = Zend_Controller_Front::getInstance();
$front-&gt;registerPlugin(new Moo_Controller_Plugin_Init, 1);
</pre>
<p>
Each module bootstrap class will extend an abstract class for common methods.
</p>
<pre class="brush: php; title: ; notranslate">
/**
 *
 * @copyright  2009 Mohammed Alsharaf
 * @author     Mohamed Alsharaf 
 * @category   Moo
 * @package    Moo_Application
 * @copyright  Copyright (c) 2009-2010 Mohammed Alsharaf.
 * @license    http://framework.zend.com/license/new-bsd
 * @version    Release: 0.0.1
 * @link       http://jamandcheese-on-phptoast.com/
 */
abstract class Moo_Application_Module_BootstrapAbstract
{
    /**
     * @var Zend_Controller_Request_Abstract
     */
    protected $_request;

    /**
     * @var Zend_Controller_Response_Abstract
     */
    protected $_response;

    /**
     * Set request object
     *
     * @param Zend_Controller_Request_Abstract $request
     * @return Moo_Application_Module_BootstrapAbstract
     */
    public function setRequest(Zend_Controller_Request_Abstract $request)
    {
        $this-&gt;_request = $request;
        return $this;
    }

    /**
     * Get request object
     *
     * @return Zend_Controller_Request_Abstract $request
     */
    public function getRequest()
    {
        return $this-&gt;_request;
    }

    /**
     * Set response object
     *
     * @param Zend_Controller_Response_Abstract $response
     * @return Moo_Application_Module_BootstrapAbstract
     */
    public function setResponse(Zend_Controller_Response_Abstract $response)
    {
        $this-&gt;_response = $response;
        return $this;
    }

    /**
     * Get response object
     *
     * @return Zend_Controller_Response_Abstract $response
     */
    public function getResponse()
    {
        return $this-&gt;_response;
    }
}
</pre>
<p>The bootstrap class looks like</p>
<pre class="brush: php; title: ; notranslate">
/**
 *
 * @copyright  2009 Mohammed Alsharaf
 * @author     Mohamed Alsharaf
 * @copyright  Copyright (c) 2009-2010 Mohammed Alsharaf.
 * @license    http://framework.zend.com/license/new-bsd
 * @version    Release: 0.0.1
 * @link       http://jamandcheese-on-phptoast.com/
 */
class Admin_Bootstrap extends Moo_Application_Module_BootstrapAbstract
{

	public function init()
	{
		// add your code here.
	}
}
</pre>
<p>Any comments appreciated</p>
]]></content:encoded>
			<wfw:commentRss>http://jamandcheese-on-phptoast.com/2010/02/01/custom-module-bootstrap-class/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>On fly elements in Zend_Form</title>
		<link>http://jamandcheese-on-phptoast.com/2009/12/13/on-fly-elements-in-zend_form/</link>
		<comments>http://jamandcheese-on-phptoast.com/2009/12/13/on-fly-elements-in-zend_form/#comments</comments>
		<pubDate>Sun, 13 Dec 2009 00:16:58 +0000</pubDate>
		<dc:creator>mohammed</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[Zend_Form]]></category>
		<category><![CDATA[Zend_Form_Element]]></category>

		<guid isPermaLink="false">http://jamandcheese-on-phptoast.com/?p=247</guid>
		<description><![CDATA[How to create and modify elements in Zend_Form on fly? Lets say we have a form that creates a customer address. The form has the following fields: Country (select element) Street name (text element) Region/State (text element) City (text element) Postal code (text element) When the user selects a country, we want to check our [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
How to create and modify elements in Zend_Form on fly?
</p>
<p>
Lets say we have a form that creates a customer address. The form has the following fields:
</p>
<ul>
<li>Country (select element)</li>
<li>Street name (text element)</li>
<li>Region/State (text element)</li>
<li>City (text element)</li>
<li>Postal code (text element)</li>
</ul>
<p>
When the user selects a country, we want to check our database to see if we have a list of regions that the user can select from. </p>
<p>If we have the list, then the system will replace the current text element for region, to a select element of the regions.
</p>
<p>
Also, we want to maintain the field after we submit the form, so we don&#8217;t lose the regions select element.
</p>
<p><span id="more-247"></span></p>
<h2>Here is the use case :</h2>
<h3>Basic Flow</h3>
<ol>
<li>User selects a country: “New Zealand”.</li>
<li>System sends an Ajax request to the server to check if it has a list of regions.</li>
<li>System finds regions.  Creates a select element then returns it to the browser.</li>
<li>System replaces the current element in the form with the new element from the server.</li>
<li>User fills out all the fields and submits the form.</li>
<li>System saves the form data into the database.</li>
</ol>
<h3>Alternative Flows</h3>
<p><strong>On 3: System could not find regions.</strong></p>
<ul>
<li>System creates a text element and returns it</li>
<li>System replaces the current element in the form with the new element from the server.</li>
</ul>
<p><strong>On 4: System returns that the form input for Postal code is incorrect.</strong></p>
<ul>
<li>System analyses the form submission and renders the form elements correctly. If we have select element for regions, the system will generate it.</li>
</ul>
<h2>How to achieve the above?</h2>
<p><strong>Here is the form class</strong></p>
<pre class="brush: php; title: ; notranslate">
Satrn_Form_Address extends Zend_Form 
{
	public function init()
	{
		// form elements here....
		
		// region element
		$this-&gt;addElement('text', 'region', array(
			'label' =&gt; 'Region',
			'attribs' =&gt; array(
				'maxlength' =&gt; 50
			),
			'validators' =&gt; array(
				array('StringLength', false, array(1,50)),
				array('String'),
			),
		));		
	}
}
</pre>
<p><strong>Here is the controller code</strong></p>
<pre class="brush: php; title: ; notranslate">
class CustomerController extends Zend_Controller_Action
{
   public function newAddressAction()
   {
      $this-&gt;_helper-&gt;pageTitle('Create New Address');
      $form = new Satrn_Form_Address();

      if ($this-&gt;getRequest()-&gt;isPost())  {
         if($form-&gt;isValid($this-&gt;getRequest()-&gt;getPost())) {
            // save
            $model = new Satrn_Model_Customer();
            $id = $model-&gt;saveAddress($form-&gt;getValues());

            $this-&gt;_helper
                 -&gt;messenger('success', 'New Address Saved.');
         }
      }
      $this-&gt;view-&gt;form = $form;
   }
}
</pre>
<p><strong>The code that needs to be added to the form class to do what we require.</strong></p>
<p>First override the method “isValid” in Zend_Form</p>
<pre class="brush: php; title: ; notranslate">
public function isValid($values)
{
	$values = $this-&gt;_modifyElements($values);	
	return parent::isValid($values);
}
</pre>
<p>Then create a method, in my example it is “modifyElements”. Add all the needed code to modify the elements in form class. Code commented.</p>
<pre class="brush: php; title: ; notranslate">
protected function _modifyElements($values)
{ 
        // search for states
        $countryModel = new Satrn_Model_Country();
        $regions = $countryModel-&gt;getRegions($values['country_id']);
        // if we don’t have any regions for the selected country id
       // then no modification needed and return the data.
        if($regions -&gt;count() == 0) {
            return $values;
        }
        // create an array from the Zend_Db_Rowset data. 
        // Where the keys are the ids of the regions
        $options = $regions -&gt;toPairs('region_id', 'region_name');
     
        // remove the current region element
        $this-&gt;removeElement(‘region');
		
	// create a new element. 
	$this-&gt;addElement('select', ' region', array(
		'label' =&gt; 'Regions',
		'attribs' =&gt; array(
			'class' =&gt; 'countryRegionSelect'
		),
		'validators' =&gt; array(
			array('inArray', false, array(array_keys($options)))
		),
		'multiOptions' =&gt; $options,
		'order' =&gt; 2,
		'value' =&gt; $values['region'],
	));
	// add element to a group if you want
	$this-&gt;getDisplayGroup('addressdetails')
	     -&gt;addElement($this-&gt;getElement('region'));
            // if you add an element to a group then unset
            // it from the form elements stack
	unset($this-&gt;_order['region']);
	return $values;
}
</pre>
<p><strong>Why do we add the element to the form,  then add it to a group, then reset it from the form?</strong></p>
<p>Because when you add the element to the group directly, it will not be added to the form elements stack $_order. This means if you validate the form elements with the method “isValid”, your new created element will not be validated. Also, if you use the method “getValues” to return all the values of the form elements, the new element will not be included.</p>
<p>The other method that needs to be modified is the “populate” method</p>
<pre class="brush: php; title: ; notranslate">
public function populate(array $values)
{
	$values = $this-&gt;_modifyElements($values);	
	return parent::populate($values);
}
</pre>
<p>It’s the same as the “isValid” method.</p>
<p>You&#8217;re all done. The form works the way you expected <img src='http://jamandcheese-on-phptoast.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>Any comments?</p>
]]></content:encoded>
			<wfw:commentRss>http://jamandcheese-on-phptoast.com/2009/12/13/on-fly-elements-in-zend_form/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Reduce duplicated code in Zend_Controller_Action</title>
		<link>http://jamandcheese-on-phptoast.com/2009/11/15/reduce-duplicated-code-in-action-controller/</link>
		<comments>http://jamandcheese-on-phptoast.com/2009/11/15/reduce-duplicated-code-in-action-controller/#comments</comments>
		<pubDate>Sun, 15 Nov 2009 04:24:27 +0000</pubDate>
		<dc:creator>mohammed</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[Zend_Controller_Action]]></category>
		<category><![CDATA[Zend_Controller_Action_Helper]]></category>

		<guid isPermaLink="false">http://jamandcheese-on-phptoast.com/?p=208</guid>
		<description><![CDATA[In most of the Zend Framework projects that i worked on, i had some common actions such as, listAction, newAction, and editAction. Each of these actions have similar structure and code lines. The differences are in the name of the model or the form or the messages on a successful submission and errors. listAction Show [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In most of the Zend Framework projects that i worked on, i had some common actions such as, listAction, newAction, and editAction. Each of these actions have similar structure and code lines. The differences are in the name of the model or the form or the messages on a successful submission and errors.</p>
<p><span id="more-208"></span></p>
<dl>
<dt>listAction</dt>
<dd>Show a table view of a collection of entities (products or customers) with functinalities like pagination, sorting, and filtering.</dd>
<dt>newAction</dt>
<dd>Form for creating a new entity. Such as, a form for creating a new product.</dd>
<dt>editAction</dt>
<dd>Form for editing an existing entity. Such as a form for editting an existing product. The product Id sepeified in the url parameter with a name of &#8220;id&#8221;.</dd>
<dl>
<p>I wanted to remove all of the duplicated code and reduce the time I spend on copying and pasting the same code again and again. So I came up with the following action helper to do that. </p>
<p>Class can be found <a href="/file.php?view=1" target="_blank">here</a>.</p>
<h3>How to use it?</h3>
<p><strong>To view a list of products</strong></p>
<pre class="brush: php; title: ; notranslate">
$options = array(
'title' =&gt; 'List Products',
'model' =&gt; array(
'className' =&gt; 'products'
),
);
$this-&gt;_helper-&gt;action($options)-&gt;listAction();
</pre>
<p><strong>To create a new product</strong></p>
<pre class="brush: php; title: ; notranslate">
$options = array(
'title' =&gt; 'Create a new product',
'model' =&gt; array(
'className' =&gt; 'products'
),
'form' =&gt; array(
'className' =&gt; 'createProduct'
),
'message' =&gt; array(
'success' =&gt; 'Product created.',
),
'goto' =&gt; array(
'save'  =&gt; 'admin/products',
'apply' =&gt; 'admin/products/edit/id/{id}'
)
);
$this-&gt;_helper-&gt;action($options)-&gt;formNewAction();
</pre>
<p><strong>To edit a product</strong></p>
<pre class="brush: php; title: ; notranslate">
$options = array(
'title' =&gt; 'Edit a Product ({title})',
'model' =&gt; array(
'className' =&gt; 'products'
),
'form' =&gt; array(
'className' =&gt; 'createProduct'
),
'message' =&gt; array(
'success' =&gt; 'Product created.',
'error'   =&gt; array(
'Product Id is invalid.',
'Unknown product.'
)
),
'goto' =&gt; array(
'save'  =&gt; 'admin/products',
'apply' =&gt; 'admin/products/edit/id/{id}'
)
);
$this-&gt;_helper-&gt;action($options)-&gt;formNewAction();
</pre>
<p><strong>An ajax request</strong></p>
<p>1. in your controller create a public method.</p>
<pre class="brush: php; title: ; notranslate">
public function productPriceAjax() {
    // your code here
    $model = new Model_Product();
    $price = $model-&gt;getPrice();
    $output = array(
         'price' =&gt; $price,
    );
    echo Zend_Json::encode($output);
    return false;
}
</pre>
<p>2. in any controller action you can add the following to convert it into ajax. it will automatically  disable the layout the render view.</p>
<pre class="brush: php; title: ; notranslate">
$this-&gt;_setParam('task', 'productPrice');
$this-&gt;_helper-&gt;action()-&gt;ajaxAction();
</pre>
<p>Any comments?</p>
]]></content:encoded>
			<wfw:commentRss>http://jamandcheese-on-phptoast.com/2009/11/15/reduce-duplicated-code-in-action-controller/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Custom Flash Messenger for Zend Framework</title>
		<link>http://jamandcheese-on-phptoast.com/2009/11/03/custom-flash-messenger-for-zend-framework/</link>
		<comments>http://jamandcheese-on-phptoast.com/2009/11/03/custom-flash-messenger-for-zend-framework/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 19:45:11 +0000</pubDate>
		<dc:creator>mohammed</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[Zend_Controller_Action_Helper]]></category>
		<category><![CDATA[Zend_View]]></category>

		<guid isPermaLink="false">http://jamandcheese-on-phptoast.com/?p=113</guid>
		<description><![CDATA[FlashMessenger is an action helper in Zend Framework used to pass messages for the users on the next request. Thats all good, but what about presenting the messages for the users? how to store different type of messages, System, Error, or Success messages? To achive my goal, i have built two classes, one is an [&#8230;]]]></description>
				<content:encoded><![CDATA[<dl>
<dt>FlashMessenger</dt>
<dd>is an action helper in Zend Framework used to pass messages for the users on the next request.</dd>
</dl>
<p>Thats all good, but what about presenting the messages for the users? how to store different type of messages, System, Error, or Success messages?</p>
<p><span id="more-113"></span><br />
To achive my goal, i have built two classes, one is an action helper and the other one is view helper.</p>
<h3>Action Helper Class</h3>
<p>This action helper class act as a factory and singleton pattern. It store the messages in different namespaces of the flash messenger. You can also, retrieve a namesapce by its key to add another message.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
/**
 *
 * @copyright  2009 Mohammed Alsharaf
 * @author     Mohamed Alsharaf (mohamed.alsharaf@gmail.com)
 * @category   Moo
 * @package    Moo_Controller
 * @copyright  Copyright (c) 2009-2010 Mohammed Alsharaf.
 * @version    Release: 0.0.2
 * @link       http://jamandcheese-on-phptoast.com/
 */
class Moo_Controller_Action_Helper_Messenger extends Zend_Controller_Action_Helper_Abstract
{
    protected $_flashMessenger = null;

    public function messenger($name='error', $message=null)
    {
        if ($name == 'error' &amp;&amp; $message === null) {
            return $this;
        }
        if (!isset($this-&gt;_flashMessenger[$name])) {
            $this-&gt;_flashMessenger[$name] = $this-&gt;getActionController()
                                                 -&gt;getHelper('FlashMessenger')
                                                 -&gt;setNamespace($name.'_message');
        }
        if ($message !== null) {
            $message = $this-&gt;getActionController()-&gt;view-&gt;translate($message);
            $this-&gt;_flashMessenger[$name]-&gt;addMessage($message);
        }
        return $this-&gt;_flashMessenger[$name];
    }

    public function direct($name='error', $message=null)
    {
        return $this-&gt;messenger($name,$message);
    }
}
</pre>
<h3>View Helper Class</h3>
<p>The view helper loops all the namespaces of the flash messenger and render the messages using the <a href="http://framework.zend.com/manual/en/zend.view.helpers.html#htmlList" target="_blank">htmlList</a> view helper</p>
<pre class="brush: php; title: ; notranslate">
/**
 *
 * @copyright  2009 Mohammed Alsharaf
 * @author     Mohamed Alsharaf (mohamed.alsharaf@gmail.com)
 * @category   Moo
 * @package    Moo_View
 * @copyright  Copyright (c) 2009-2010 Mohammed Alsharaf.
 * @version    Release: 0.0.2
 * @link       http://jamandcheese-on-phptoast.com/
 */
class Moo_View_Helper_Messenger extends Zend_View_Helper_Abstract
{
    const DEFAULT_MSG = 'info';

    protected $_messageKeys = array(
        'msg_message',
        'error_message',
        'info_message',
        'success_message',
        'warning_message',
    );

    protected $_flashMessenger = null;

    public function messenger($messages = null)
    {
        if ($messages !== null) {
            return $this-&gt;_renderInjectedMessages($messages);
        }
        $this-&gt;_flashMessenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');

        foreach ($this-&gt;_messageKeys as $messageKey) {
            $messages = $this-&gt;_getMessages($messageKey);
            if ($messages) {
                echo $this-&gt;_renderMessage($messages,$messageKey);
            }
            unset($messages);
        }
    }

    protected function _renderInjectedMessages($messages)
    {
        if (!is_array($messages)) {
            return $this-&gt;_renderMessage((string) $messages,self::DEFAULT_MSG);
        }

        $return = '';
        foreach ($messages as $messageKey =&gt; $message) {
            $return  .= $this-&gt;_renderMessage($message, $messageKey . '_message');
        }
        return $return;
    }
    protected function _getMessages($messageKey)
    {
        $result = array();
        $this-&gt;_flashMessenger-&gt;setNamespace($messageKey);

        if ($this-&gt;_flashMessenger-&gt;hasMessages()) {
            $result = $this-&gt;_flashMessenger-&gt;getMessages();
        }

        // check view object
        if (isset($this-&gt;view-&gt;$messageKey)) {
            array_push($result, $this-&gt;view-&gt;$messageKey);
        }

        //add any messages from this request
        if ($this-&gt;_flashMessenger-&gt;hasCurrentMessages()) {
            $result = array_merge( $result, $this-&gt;_flashMessenger-&gt;getCurrentMessages());
            //we don?t need to display them twice.
            $this-&gt;_flashMessenger-&gt;clearCurrentMessages();
        }
        return $result;
    }

    protected function _renderMessage($message, $name)
    {
        if (!is_array($message)) {
            $message = array($message);
        }
        return $this-&gt;view-&gt;htmlList($message, false, array('class'=&gt;$name), false);
    }
}
</pre>
<h3>Usage:</h3>
<p>In your controller to add a message for the next request</p>
<pre class="brush: php; title: ; notranslate">
// option one
$this-&gt;_helper-&gt;messenger('success',&quot;Your message is here.&quot;);
// another option to add message
$this-&gt;_helper-&gt;messenger('success')-&gt;addMessage('Your message is here.');
</pre>
<p>To add a message in the current view:</p>
<pre class="brush: php; title: ; notranslate">
$this-&gt;view-&gt;info_message = 'stiky message for the current view';
</pre>
<p>In your layout file add the following, so if there are messages to view, the helper will print them.</p>
<pre class="brush: php; title: ; notranslate">
&lt;div id=&quot;messages&quot;&gt;&amp;lt;?php $this-&gt;messenger(); ?&gt;&lt;/div&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://jamandcheese-on-phptoast.com/2009/11/03/custom-flash-messenger-for-zend-framework/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
