<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Pablo Viquez Blog</title>
	
	<link>http://www.pabloviquez.com</link>
	<description>Mi vida y cosas relacionadas</description>
	<lastBuildDate>Thu, 10 Dec 2009 17:08:18 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/PabloViquezBlog" /><feedburner:info uri="pabloviquezblog" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:feedFlare href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare href="http://feeds.my.aol.com/add.jsp?url=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://o.aolcdn.com/favorites.my.aol.com/webmaster/ffclient/webroot/locale/en-US/images/myAOLButtonSmall.gif">Subscribe with My AOL</feedburner:feedFlare><feedburner:feedFlare href="http://www.bloglines.com/sub/http://feeds.feedburner.com/PabloViquezBlog" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><feedburner:feedFlare href="http://www.plusmo.com/add?url=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://plusmo.com/res/graphics/fbplusmo.gif">Subscribe with Plusmo</feedburner:feedFlare><feedburner:feedFlare href="http://www.thefreedictionary.com/_/hp/AddRSS.aspx?http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://img.tfd.com/hp/addToTheFreeDictionary.gif">Subscribe with The Free Dictionary</feedburner:feedFlare><feedburner:feedFlare href="http://www.bitty.com/manual/?contenttype=rssfeed&amp;contentvalue=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://www.bitty.com/img/bittychicklet_91x17.gif">Subscribe with Bitty Browser</feedburner:feedFlare><feedburner:feedFlare href="http://www.newsalloy.com/?rss=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://www.newsalloy.com/subrss3.gif">Subscribe with NewsAlloy</feedburner:feedFlare><feedburner:feedFlare href="http://www.live.com/?add=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://tkfiles.storage.msn.com/x1piYkpqHC_35nIp1gLE68-wvzLZO8iXl_JMledmJQXP-XTBOLfmQv4zhj4MhcWEJh_GtoBIiAl1Mjh-ndp9k47If7hTaFno0mxW9_i3p_5qQw">Subscribe with Live.com</feedburner:feedFlare><feedburner:feedFlare href="http://mix.excite.eu/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://image.excite.co.uk/mix/addtomix.gif">Subscribe with Excite MIX</feedburner:feedFlare><feedburner:feedFlare href="http://download.attensa.com/app/get_attensa.html?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://www.attensa.com/blogs/attensa/WindowsLiveWriter/BadgeredintoBadges_10C02/attensa_feed_button5.gif">Subscribe with Attensa for Outlook</feedburner:feedFlare><feedburner:feedFlare href="http://www.webwag.com/wwgthis.php?url=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://www.webwag.com/images/wwgthis.gif">Subscribe with Webwag</feedburner:feedFlare><feedburner:feedFlare href="http://www.podcastready.com/oneclick_bookmark.php?url=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://www.podcastready.com/images/podcastready_button.gif">Subscribe with Podcast Ready</feedburner:feedFlare><feedburner:feedFlare href="http://www.flurry.com/pushRssFeed.do?r=fb&amp;url=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://www.flurry.com/images/flurry_rss_logo2.gif">Subscribe with Flurry</feedburner:feedFlare><feedburner:feedFlare href="http://www.wikio.com/subscribe?url=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://www.wikio.com/shared/img/add2wikio.gif">Subscribe with Wikio</feedburner:feedFlare><feedburner:feedFlare href="http://www.dailyrotation.com/index.php?feed=http%3A%2F%2Ffeeds.feedburner.com%2FPabloViquezBlog" src="http://www.dailyrotation.com/rss-dr2.gif">Subscribe with Daily Rotation</feedburner:feedFlare><item>
		<title>Zend_Log, FirePHP and Zend_Application. How to</title>
		<link>http://feedproxy.google.com/~r/PabloViquezBlog/~3/8bep8JF8gj8/</link>
		<comments>http://www.pabloviquez.com/2009/11/zend_log-firebug-and-zend_application-another-how-to/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 22:23:36 +0000</pubDate>
		<dc:creator>Pablo Viquez</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[tech]]></category>
		<category><![CDATA[firebug]]></category>
		<category><![CDATA[firephp]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.pabloviquez.com/?p=243</guid>
		<description><![CDATA[I wanted to enable logging of exceptions to my PHP log file and also display them using FireBug.
On a standard setup of Zend Framework, the Zend error handler plugin (Zend_Controller_Plugin_ErrorHandler) enable by default and it was designed for:

Errors due to missing controllers or actions
Errors occurring within action controllers

I wanted to keep using the error handler [...]]]></description>
			<content:encoded><![CDATA[<p>I wanted to enable logging of exceptions to my PHP log file and also display them using FireBug.</p>
<p>On a standard setup of Zend Framework, the Zend error handler plugin (Zend_Controller_Plugin_ErrorHandler) enable by default and it was designed for:</p>
<ul>
<li>Errors due to missing controllers or actions</li>
<li>Errors occurring within action controllers</li>
</ul>
<p>I wanted to keep using the error handler plugin and didn&#8217;t want to log the exceptions by using: <em>Zend_Controller_Front::throwExceptions()</em> or <em>Zend_Controller_Response_Abstract::renderExceptions()</em> or any other way since eventually might get complicated, besides, I think that the error handler plugin works fine and if it gets updated in the future, I won&#8217;t have to do a major refactor.</p>
<p>So this is how  I did it:</p>
<h2>Create the Zend Log Object</h2>
<p>Using Zend_Application can be very helpful here, because you can init the logger and automatically store the object in the registry, making available to the controllers later on.</p>
<p>Summary, if you want an object created on the boostrap class, to be available on the controllers later, you need to return it from the init method, in this case, we&#8217;re initializing the Zend_Log, so we need to return the object.</p>
<pre class="brush: php">
&lt;?php
class App_Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

    /**
     * Initializes the logging on the application
     *
     * We&#039;re using 2 ways for logging exceptions:
     * 1. PHP Error log file.
     * 2. Firebug for Development environments only.
     *
     * @return Zend_Log
     */
    protected function _initLogger()
    {
        // Create the Zend_Log object
        $logger = new Zend_Log();

        // Create the resource for the error log file
        // if you dont want to use the error suppressor &quot;@&quot;
        // you can always use: is_writable
        // http://php.net/manual/function.is-writable.php
        $stream = @fopen(ini_get(&#039;error_log&#039;), &#039;a&#039;);
        if ($stream) {
            $stdWritter = new Zend_Log_Writer_Stream($stream);
            $stdWritter-&gt;addFilter(Zend_Log::DEBUG);
            $stdWritter-&gt;addFilter(Zend_Log::INFO);
            $logger-&gt;addWriter($stdWritter);
        }

        // Create the Firebug writter - Development only
        if ($this-&gt;_application-&gt;getEnvironment() != &#039;production&#039;) {
            // Init firebug logging
            $fbWriter = new Zend_Log_Writer_Firebug();
            $logger-&gt;addWriter($fbWriter);
        }

        return $logger;
    }
</pre>
<p>I have now the log object but I&#8217;m not logging anything yet, so I need to implement the logging part.</p>
<h2>Log the Exception</h2>
<p>For this part, I thought in 2 ways to do it:</p>
<ol>
<li>Extend the error handler plugin and log errors there.</li>
<li>Log the errors on the error controller.</li>
</ol>
<p>I choose the second one for several reasons:</p>
<ol>
<li>Easier.</li>
<li>If the error handler changes somehow, you dont have to change your code.</li>
<li>Extending the error plugin, might lead to repeated code and eventually deprecated code.</li>
</ol>
<p>By default, Zend_Controller_Plugin_ErrorHandler will forward to ErrorController::errorAction() in the default module.</p>
<p>Now in order to retrieve a resource created in the bootstrap we need to access the bootstrap registered in the front controller, and from there we can get our logger:</p>
<pre class="brush: php">
// The method _initLogger on the class App_Bootstrap
// returns a Zend_Log object that is available
// on the Zend_Registry. To retrieve it we need to request the
// bootstrap from the Front controller and then get the logger.
$boot = $this-&gt;getInvokeArg(&#039;bootstrap&#039;);
if ($boot-&gt;hasResource(&#039;logger&#039;)) {
    $log_object = $boot-&gt;getResource(&#039;logger&#039;);
}
</pre>
<p>So using the <a href="http://framework.zend.com/manual/en/zend.controller.plugins.html#zend.controller.plugins.standard.errorhandler.fourohfour" target="_blank">Zend Framework default error controller</a> (the one provided on the reference), with the logging will be something like this:</p>
<pre class="brush: php">
class ErrorController extends Zend_Controller_Action
{
    /**
     * Error action. This method is called by
     * Zend_Controller_Plugin_ErrorHandler
     *
     * @see Zend_Controller_Plugin_ErrorHandler
     * @return void
     */
    public function errorAction()
    {
        $errors = $this-&gt;_getParam(&#039;error_handler&#039;);

        // Log the Error.
        $boot = $this-&gt;getInvokeArg(&#039;bootstrap&#039;);
        if ($boot-&gt;hasResource(&#039;logger&#039;)) {
            $boot-&gt;getResource(&#039;logger&#039;)-&gt;err($errors-&gt;exception);
        }

        // Default error handling...
        switch ($errors-&gt;type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:

                // 404 error -- controller or action not found
                $this-&gt;getResponse()-&gt;setHttpResponseCode(404);
                $this-&gt;view-&gt;message = &#039;Page not found&#039;;
                break;
            default:
                // application error
                $this-&gt;getResponse()-&gt;setHttpResponseCode(500);
                $this-&gt;view-&gt;message = &#039;Application error&#039;;
                break;
        }

        $this-&gt;view-&gt;exception = $errors-&gt;exception;
        $this-&gt;view-&gt;request   = $errors-&gt;request;
    }
}
</pre>
<h2>Result</h2>
<p>The final result looks like this:</p>
<h3>Firefox with Firebug enabled:</h3>
<p><img class="size-full wp-image-245" title="Firebug Screenshot" src="http://www.pabloviquez.com/wp-content/uploads/2009/11/firebug.gif" alt="Firefox Screenshot with Firebug enabled" width="851" height="511" /></p>
<h3>PHP error log file:</h3>
<pre class="brush: shell">
[pviquez /usr/home/pviquez]$ cat php_error.log
2009-11-25T15:23:19-06:00 ERR (3): exception &#039;Zend_Exception&#039; with message &#039;The logging is working!&#039; in /usr/home/pviquez/app/deploy/application/modules/admin/controllers/IndexController.php:33
Stack trace:
#0 /usr/home/pviquez/app/deploy/library/Zend/Controller/Action.php(513): Admin_IndexController-&gt;indexAction()
#1 /usr/home/pviquez/app/deploy/library/Zend/Controller/Dispatcher/Standard.php(289): Zend_Controller_Action-&gt;dispatch(&#039;indexAction&#039;)
#2 /usr/home/pviquez/app/deploy/library/Zend/Controller/Front.php(946): Zend_Controller_Dispatcher_Standard-&gt;dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#3 /usr/home/pviquez/app/deploy/library/Zend/Application/Bootstrap/Bootstrap.php(77): Zend_Controller_Front-&gt;dispatch()
#4 /usr/home/pviquez/app/deploy/library/Zend/Application.php(346): Zend_Application_Bootstrap_Bootstrap-&gt;run()
#5 /usr/home/pviquez/app/deploy/public/index.php(23): Zend_Application-&gt;run()
#6 {main}
</pre>
<h2>References</h2>
<ul>
<li>Install Firebug on Firefox <a href="https://addons.mozilla.org/firefox/addon/1843">Firebug Add-on</a></li>
<li>Error Handler Plugin: <a href="http://framework.zend.com/manual/en/zend.controller.plugins.html#zend.controller.plugins.standard.errorhandler">http://framework.zend.com/manual/en/zend.controller.plugins.html#zend.controller.plugins.standard.errorhandler</a></li>
<li>MVC Exceptions: <a href="http://framework.zend.com/manual/en/zend.controller.exceptions.html">http://framework.zend.com/manual/en/zend.controller.exceptions.html</a></li>
</ul>
<img src="http://feeds.feedburner.com/~r/PabloViquezBlog/~4/8bep8JF8gj8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pabloviquez.com/2009/11/zend_log-firebug-and-zend_application-another-how-to/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://www.pabloviquez.com/2009/11/zend_log-firebug-and-zend_application-another-how-to/</feedburner:origLink></item>
		<item>
		<title>Export Excel Spreadsheets using Zend Framework</title>
		<link>http://feedproxy.google.com/~r/PabloViquezBlog/~3/eykAumd-Ldg/</link>
		<comments>http://www.pabloviquez.com/2009/08/export-excel-spreadsheets-using-zend-framework/#comments</comments>
		<pubDate>Mon, 24 Aug 2009 20:04:11 +0000</pubDate>
		<dc:creator>Pablo Viquez</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[tech]]></category>
		<category><![CDATA[Excel Spreadsheets]]></category>
		<category><![CDATA[pear]]></category>
		<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.pabloviquez.com/?p=224</guid>
		<description><![CDATA[Last week, I had to allow the user to export a given report into an MS Excel file format.
The application uses Zend Framework 1.9.1 and so far ZF does not support for &#8220;Office&#8221; formats, so after searching for a nice implementation, I found a PEAR module called Spreadsheet Excel Writter, which looked pretty good, it [...]]]></description>
			<content:encoded><![CDATA[<p>Last week, I had to allow the user to export a given report into an MS Excel file format.</p>
<p>The application uses <a href="http://www.zendframework.com/" target="_blank">Zend Framework 1.9.1</a> and so far ZF does not support for &#8220;Office&#8221; formats, so after searching for a nice implementation, I found a PEAR module called <a href="http://pear.php.net/package/Spreadsheet_Excel_Writer/" target="_blank">Spreadsheet Excel Writter</a>, which looked pretty good, it had very good documentation and the code was clean and well structured so I wanted to give it a shot.</p>
<h2>1. PEAR Setup</h2>
<p>I used the web interface for the PEAR setup which worked pretty good! (Not covering PEAR installation here). </p>
<p>If you want more info on how to install PEAR, go here: http://pear.php.net/manual/en/installation.getting.php and for the web setup: http://pear.php.net/go-pear</p>
<p><b>ONCE INSTALLED, REMEMBER TO ADD THE PEAR PATH TO YOUR INCLUDE PATH</b></p>
<h2>2. Following the MVC pattern.</h2>
<div class="wp-caption alignright" style="width: 331px"><img title="Model View Controller" src="http://www.pabloviquez.com/images/ModelViewControllerDiagram.png" alt="Model View Controller" width="321" height="151" /><p class="wp-caption-text">Model View Controller Diagram</p></div>
<p>I love the architecture following <a href="http://framework.zend.com/docs/quickstart" target="_blank">MVC (Model View Controller)</a> and if I follow the MVC pattern, excel file will go as VIEW, this because the data is being presented  an excel file.</p>
<p>Also, the controller does not care which format does the info gets display, the controller should care about manipulating modules, getting the data, controlling the flow of the application not about the presentation layer.</p>
<h3>So what did I do?</h3>
<p>Zend Framework offers a nice feature called <a href="http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.contextswitch" target="_blank">&#8220;Context Switch&#8221;</a>. This is an <a href="http://framework.zend.com/manual/en/zend.controller.actionhelpers.html" target="_blank">action helper</a> that detects requested output and calls the specific view for the required format.</p>
<p>In my case, I wanted to enable this feature to the user controller, which had 3 actions:</p>
<ul>
<li>user/index</li>
<li>user/new</li>
<li>user/report</li>
</ul>
<p>Now, I wanted to give the option to export the data as excel only for the &#8220;report&#8221; action, so I did this on the controller init method:</p>
<pre class="brush: php">
class UserController extends Zend_Controller_Action
{
    /**
     * Initializes the controller
     *
     * @return void
     */
    public function init()
    {
        // Optional added for consistency
        parent::init();

        // Excel format context
        $excelConfig =
            array(
                &#039;excel&#039; =&gt; array(
                    &#039;suffix&#039;  =&gt; &#039;excel&#039;,
                    &#039;headers&#039; =&gt; array(
                        &#039;Content-type&#039; =&gt; &#039;application/vnd.ms-excel&#039;)),
            );

        // Init the Context Switch Action helper
        $contextSwitch = $this-&gt;_helper-&gt;contextSwitch();

        // Add the new context
        $contextSwitch-&gt;setContexts($excelConfig)

        // Set the new context to the reports action
        $contextSwitch-&gt;addActionContext(&#039;report&#039;, &#039;excel&#039;)

        // Initializes the action helper
        $contextSwitch-&gt;initContext();
    }

    public function indexAction() { /* ... */ }
    public function newAction() { /* ... */ }
    public function reportAction() { /* ... */ }
}
</pre>
<p>What this code does is that it tells the controller to search on the parameters (GET/POST) for token &#8220;format&#8221; and the value &#8220;excel&#8221;. In other words, If the report action get requested like this:</p>
<p>/user/report?format=excel or /user/report/format/excel instead of loading the view: report.phtml will load the view report.excel.phtml and here is where the magic happens!</p>
<p>In the setup of the Context Switch, the &#8220;suffix&#8221; is what will be appended to the view file.</p>
<p>The report action, just gets the report and sets a variable on the view so it&#8217;s accesible as follow:</p>
<pre class="brush: php">
class UserController extends Zend_Controller_Action
{
    public function init() { /* ... */ }
    public function indexAction() { /* ... */ }
    public function newAction() { /* ... */ }

    /**
     * Report action
     *
     * @return void
     */
    public function reportAction()
    {
        // Proof of concept
        // Lets say that the result have the following structure
        //
        // array(
        //     [USER ID] =&gt; array(
        //                      &#039;name&#039;  =&gt; &#039;Pablo Víquez&#039;,
        //                      &#039;email&#039; =&gt; &#039;email@domain.com&#039;,
        //                  ),
        //     [USER_ID] =&gt; array(...),
        //     ...
        // )
        $this-&gt;view-&gt;users = User_Model_Name::getReport();
    }
}
</pre>
<h3>Now the view&#8230;</h3>
<p>I need to have 2 files for this action:</p>
<ul>
<li>report.phtml &#8211; Output will be regular HTML</li>
<li>report.excel.phtml &#8211; Output will be an MS Excel spreadsheet</li>
</ul>
<h3>report.phtml</h3>
<p>This is the HTML format.</p>
<pre class="brush: html">
&lt;h1&gt;Users report&lt;/h1&gt;

&lt;table&gt;
    &lt;thead&gt;
        &lt;tr&gt;
            &lt;th&gt;User Id&lt;/th&gt;
            &lt;th&gt;Name&lt;/th&gt;
            &lt;th&gt;Email&lt;/th&gt;
        &lt;/tr&gt;
    &lt;/thead&gt;
&lt;!--
    Variable set on the controller, if there&#039;s no data to display
    the count will be 0.
--&gt;
&lt;?php if(count($this-&gt;users) &gt; 0) : ?&gt;
&lt;?php foreach ($this-&gt;users as $userId =&gt; $user) : ?&gt;
    &lt;tr&gt;
        &lt;td&gt;&lt;?php echo $userId; ?&gt;&lt;/td&gt;
        &lt;td&gt;&lt;?php echo $user[&#039;name&#039;]; ?&gt;&lt;/td&gt;
        &lt;td&gt;&lt;?php echo $user[&#039;email&#039;]; ?&gt;&lt;/td&gt;
    &lt;/tr&gt;
&lt;?php endforeach; ?&gt;
&lt;?php endif; ?&gt;
&lt;/table&gt;
</pre>
<h3>report.excel.phtml</h3>
<pre class="brush: php">

// Change error reporting for compatibility
// Spreadsheet Excel Writter was built using PHP4,
// so there&#039;s a lot of DEPRECATED notices
error_reporting(E_ERROR | E_WARNING | E_PARSE);

/**
 * PEAR package
 *
 * @link http://pear.php.net/package/Spreadsheet_Excel_Writer
 * @see PEAR/Spreadsheet/Excel/Writer.php
 */
require_once &#039;Spreadsheet/Excel/Writer.php&#039;;

// Lets define some custom colors codes
define(&#039;CUSTOM_DARK_BLUE&#039;, 20);
define(&#039;CUSTOM_BLUE&#039;, 21);
define(&#039;CUSTOM_LIGHT_BLUE&#039;, 22);
define(&#039;CUSTOM_YELLOW&#039;, 23);
define(&#039;CUSTOM_GREEN&#039;, 24);

// First, we create a Workbook
$workbook = new Spreadsheet_Excel_Writer();

// Add one sheet, called: Users Report
$worksheet = &amp;$workbook-&gt;addWorksheet(&#039;Users Report&#039;);

// Create the custom colors on our new workbook
// This function takes 4 params:
//    - Code index [1 to 64]
//    - RGB colors (0-255)
$workbook-&gt;setCustomColor(CUSTOM_DARK_BLUE, 31, 73, 125);
$workbook-&gt;setCustomColor(CUSTOM_BLUE, 0, 112, 192);
$workbook-&gt;setCustomColor(CUSTOM_LIGHT_BLUE, 184, 204, 228);
$workbook-&gt;setCustomColor(CUSTOM_YELLOW, 255, 192, 0);
$workbook-&gt;setCustomColor(CUSTOM_GREEN, 0, 176, 80);

// Lets hide gridlines
$worksheet-&gt;hideScreenGridlines();

// Lets create some custom styles
$formatHeader = &amp;$workbook-&gt;addFormat();
$formatHeader =
    &amp;$workbook-&gt;addFormat(
        array(&#039;Size&#039;    =&gt; 16,
              &#039;VAlign&#039;  =&gt; &#039;vcenter&#039;,
              &#039;HAlign&#039;  =&gt; &#039;center&#039;,
              &#039;Bold&#039;    =&gt; 1,
              &#039;Color&#039;   =&gt; &#039;white&#039;,
              &#039;FgColor&#039; =&gt; CUSTOM_DARK_BLUE));

$formatReportHeader =
    &amp;$workbook-&gt;addFormat(
        array(&#039;Size&#039;     =&gt; 9,
              &#039;VAlign&#039;   =&gt; &#039;bottom&#039;,
              &#039;HAlign&#039;   =&gt; &#039;center&#039;,
              &#039;Bold&#039;     =&gt; 1,
              &#039;FgColor&#039;  =&gt; CUSTOM_LIGHT_BLUE,
              &#039;TextWrap&#039; =&gt; true));

$formatData =
    &amp;$workbook-&gt;addFormat(
        array(
            &#039;Size&#039;   =&gt; 8,
            &#039;HAlign&#039; =&gt; &#039;center&#039;,
            &#039;VAlign&#039; =&gt; &#039;vcenter&#039;));

/**
 * First, format the worksheet, adding the headers
 * and row/columns custom sizes
 */

// Create a nice header with a dark blue background
// The function setRow takes 3 parameters:
//    - row index
//    - row height
//    - Format to apply to row [Optional]
$worksheet-&gt;setRow(0, 11, $formatHeader);
$worksheet-&gt;setRow(1, 46, $formatHeader);
$worksheet-&gt;setRow(2, 11, $formatHeader);

// Set the size of the columns
// The function setColumn takes 5 params:
//     - First column
//     - Last column
//     - Column Width
//     - Format [Optional, default = 0]
//     - Hidden [Optional, default = 0]
$worksheet-&gt;setColumn(0, 0, 7); // User Id, shrink it to 7
$worksheet-&gt;setColumn(1, 1, 12); // Name, set the width to 12
$worksheet-&gt;setColumn(1, 1, 15); // Email, set the width to 15

/**
 *
 * Once we have the format ready, add the text to the spreadsheet
 *
 */
// Write a text header
$worksheet-&gt;write(1, 1, &#039;Users report&#039;, $formatHeader);

// Create the header for the data starting @ row 4
$indexCol = 0;
$indexRow = 4;
$worksheet-&gt;write($indexRow, $indexCol++, &#039;User Id&#039;, $formatReportHeader);
$worksheet-&gt;write($indexRow, $indexCol++, &#039;Name&#039;, $formatReportHeader);
$worksheet-&gt;write($indexRow, $indexCol++, &#039;Email&#039;, $formatReportHeader);

$indexRow++;   // Advance to the next row
$indexCol = 0; // Start @ column 0

// Print the report data
if(count($this-&gt;users) == 0) {
    // No data
    $worksheet-&gt;write(
        $indexRow,
        $indexCol,
        &#039;No data to display&#039;,
        $formatData);

} else {
    // Write the data
    foreach ($this-&gt;users as $userId =&gt; $user) {
        $worksheet-&gt;writeNumber(
            $indexRow,
            $indexCol++,
            $userId,
            $formatData);

        $worksheet-&gt;write(
            $indexRow,
            $indexCol++,
            $user[&#039;name&#039;],
            $formatData);

        $worksheet-&gt;write(
            $indexRow,
            $indexCol++,
            $user[&#039;email&#039;],
            $formatData);

        // Advance to the next row
        $indexRow++;
    }
}

/**
 *
 * Response with the excel file
 *
 */

// Sends HTTP headers for the Excel file.
$workbook-&gt;send(&#039;report.xls&#039;);

// Calls finalization methods.
// This method should always be the last one to be called on every workbook
$workbook-&gt;close();
</pre>
<img src="http://feeds.feedburner.com/~r/PabloViquezBlog/~4/eykAumd-Ldg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pabloviquez.com/2009/08/export-excel-spreadsheets-using-zend-framework/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<feedburner:origLink>http://www.pabloviquez.com/2009/08/export-excel-spreadsheets-using-zend-framework/</feedburner:origLink></item>
		<item>
		<title>Proxima reunión</title>
		<link>http://feedproxy.google.com/~r/PabloViquezBlog/~3/qnOtYIsjvRs/</link>
		<comments>http://www.pabloviquez.com/2009/08/proxima-reunin/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 22:54:44 +0000</pubDate>
		<dc:creator>Pablo Viquez</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[costa rica php]]></category>
		<category><![CDATA[costa rica]]></category>

		<guid isPermaLink="false">http://www.pabloviquez.com/2009/08/proxima-reunin/</guid>
		<description><![CDATA[Ya se anunció la próxima reunión del grupo de PHP. (Ver anuncio)
Esta es la información del evento:
Donde: Auditorio Universidad Latina de Costa Rica
Cuando: Martes 11 de Agosto, 7:00pm

El tema de Unit Testing e Integración Continua la verdad está muy bueno, recomendado.
]]></description>
			<content:encoded><![CDATA[<p>Ya se anunció la próxima reunión del grupo de PHP. (<a title="Comunidad PHP" href="http://www.costaricaphp.org/archives/68" target="_blank">Ver anuncio</a>)</p>
<p>Esta es la información del evento:</p>
<p><strong>Donde: </strong>Auditorio Universidad Latina de Costa Rica</p>
<p><strong>Cuando:</strong> Martes 11 de Agosto, 7:00pm</p>
<p><img title="reunion_2009-08-11" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="397" alt="reunion_2009-08-11" src="http://www.pabloviquez.com/wp-content/uploads/2009/08/reunion_20090811.gif" width="576" border="0" /></p>
<p>El tema de Unit Testing e Integración Continua la verdad está muy bueno, recomendado.</p>
<img src="http://feeds.feedburner.com/~r/PabloViquezBlog/~4/qnOtYIsjvRs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pabloviquez.com/2009/08/proxima-reunin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pabloviquez.com/2009/08/proxima-reunin/</feedburner:origLink></item>
		<item>
		<title>How to use json_encode with ISO-8859-1 data – Part2</title>
		<link>http://feedproxy.google.com/~r/PabloViquezBlog/~3/62XC2kUGkUE/</link>
		<comments>http://www.pabloviquez.com/2009/07/json-iso-8859-1-and-utf-8-%e2%80%93-part2/#comments</comments>
		<pubDate>Fri, 31 Jul 2009 18:04:22 +0000</pubDate>
		<dc:creator>Pablo Viquez</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[iso 8859-1]]></category>
		<category><![CDATA[utf-8]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[i18n]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[json_encode]]></category>

		<guid isPermaLink="false">http://www.pabloviquez.com/?p=200</guid>
		<description><![CDATA[To continue with the previous post.
Problem: Function json_encode does not support ISO-8859-1 encoded data.
One solution that I did, in order to preserve the character set was to encode the
data before using the json_encode function to use just A-Z, a-z and 0-9 characters,
instead of sending text with accents or symbols.
One encoding that fits perfectly in this [...]]]></description>
			<content:encoded><![CDATA[<p>To continue with <a title="JSON, ISO 8859-1 and UTF-8 – Part1" href="http://www.pabloviquez.com/2009/07/json-iso-8859-1-and-utf-8-part1/">the previous post</a>.</p>
<p><strong>Problem:</strong> Function json_encode does not support ISO-8859-1 encoded data.</p>
<p>One solution that I did, in order to preserve the character set was to encode the<br />
data before using the json_encode function to use just A-Z, a-z and 0-9 characters,<br />
instead of sending text with accents or symbols.</p>
<p>One encoding that fits perfectly in this schema, is Base64 Content-Transfer-Encoding. (see base 64 explanation below)</p>
<p>This leads me to the solution: Encode the ISO-8859-1 using base64 and decoded in the client using JavaScript.</p>
<p>Now, this lead me to another issue, what&#8217;s the algorithim to implement the base64_decode function in JavaScript?</p>
<p>Luckly enough, I was looking at the site: http://phpjs.org/ which ported most of the PHP functions to JavaScript and problem solved!</p>
<p><a href="http://www.pabloviquez.com/demo_files/Encoding-JSON.zip">Download the demo files here</a></p>
<h2>Solution</h2>
<p>So my solution will look like this (using the demo files from my previous post):</p>
<p><b>prueba_ansi.php</b></p>
<pre class="brush: php">
&lt;?php
$id =
    base64_encode(
        utf8_encode(&#039;iso-8859-1&#039;));
$name =
    base64_encode(
        utf8_encode(&#039;Pablo Víquez - This is an ISO-8859-1 encoded text&#039;));
$notes =
    base64_encode(
        utf8_encode(&#039;Test with JSON encoding. á é í ó ú, ñ, Ñ.&#039;));

$customer =
    array(
        &#039;id&#039;    =&gt; $id,
        &#039;name&#039;  =&gt; $name,
        &#039;notes&#039; =&gt; $notes
);

echo json_encode($customer);
</pre>
<p>As you can see, I used 2 functions to encode the data: base64_encode and utf8_encode.</p>
<p>I used these 2, mostly because the JavaScript implementation of base64_decode asumes<br />
that the data is UTF-8 encoded, by doing </i>base64_encode(utf8_encode(&#8216;iso-8859-1&#8242;))</i><br />
I&#8217;m acctually first encoding the data to be UTF-8 first and then encoding it using Base64.</p>
<p><b>base64_encode</b><br />
Encodes data with MIME base64, and has the following description:</p>
<pre class="brush: php">string base64_encode ( string $data )</pre>
<p><b>utf8_encode</b><br />
Encodes an ISO-8859-1 string to UTF-8, and has the following description:</p>
<pre class="brush: php">string utf8_encode  ( string $data  )</pre>
<h2>Client Side</h2>
<p>I used JQuery to retrieve the JSON data, and the phpjs.org implementation for the<br />
base64_decode and utf8_decode functions.</p>
<p><b>index.html</b></p>
<pre class="brush: html">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.1//EN&quot; &quot;http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;title&gt;JSON Consumer&lt;/title&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=iso-8859-1&quot; /&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
$(document).ready(function(){
    $(&quot;#query_data_iso&quot;).click(
        function(){
            getIsoData();
        }
    );

    $(&quot;#query_data_utf8&quot;).click(
        function(){
            getUtfData();
        }
    );
});

function getUtfData() {
    $.ajax({
        type:       &quot;GET&quot;,
        dataType:   &quot;json&quot;,
        url:        &quot;prueba_utf8.php&quot;,
        success:    function(response){
            $(&quot;#customer_data_id&quot;).html(response.id);
            $(&quot;#customer_data_name&quot;).html(response.name);
            $(&quot;#customer_data_notes&quot;).html(response.notes);
        },
    });
}

/**
 * Gets a JSON response from the server.
 * Expectes a base64 encoded response with: id, name and notes all base64 encoded.
 */
function getIsoData() {
    $.ajax({
        type:       &quot;GET&quot;,
        dataType:   &quot;json&quot;,
        url:        &quot;prueba_ansi.php&quot;,
        success:    function(response){
            $(&quot;#customer_data_id&quot;).html(base64_decode(response.id));
            $(&quot;#customer_data_name&quot;).html(base64_decode(response.name));
            $(&quot;#customer_data_notes&quot;).html(base64_decode(response.notes));
        },
    });
}

/**
 * Decodes string using MIME base64 algorithm
 * @see http://phpjs.org/functions/base64_decode
 */
function base64_decode( data ) {
    var b64 = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=&quot;;
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = &quot;&quot;, tmp_arr = [];

    if (!data) {
        return data;
    }

    data += &#039;&#039;;

    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1&lt;&lt;18 | h2&lt;&lt;12 | h3&lt;&lt;6 | h4;

        o1 = bits&gt;&gt;16 &amp; 0xff;
        o2 = bits&gt;&gt;8 &amp; 0xff;
        o3 = bits &amp; 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i &lt; data.length);

    dec = tmp_arr.join(&#039;&#039;);
    dec = this.utf8_decode(dec);
    return dec;
}

/**
 * Converts a UTF-8 encoded string to ISO-8859-1
 * @see http://phpjs.org/functions/utf8_decode
 */
function utf8_decode ( str_data ) {
    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;

    str_data += &#039;&#039;;

    while ( i &lt; str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 &lt; 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 &gt; 191) &amp;&amp; (c1 &lt; 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 &amp; 31) &lt;&lt; 6) | (c2 &amp; 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 &amp; 15) &lt;&lt; 12) | ((c2 &amp; 63) &lt;&lt; 6) | (c3 &amp; 63));
            i += 3;
        }
    }

    return tmp_arr.join(&#039;&#039;);
}
&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;
    &lt;h1&gt;ISO 8859-1, JSON consumer&lt;/h1&gt;

    &lt;p&gt;
        &lt;a href=&quot;#&quot; id=&quot;query_data_iso&quot;&gt;Query for ISO-8859-1 data&lt;/a&gt; |
        &lt;a href=&quot;#&quot; id=&quot;query_data_utf8&quot;&gt;Query for UTF-8&lt;/a&gt;
    &lt;/p&gt;
    &lt;table border=&quot;1&quot;&gt;
        &lt;tr&gt;
            &lt;td&gt;Id&lt;/td&gt;
            &lt;td&gt;Name&lt;/td&gt;
            &lt;td&gt;Notes&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;&lt;div id=&quot;customer_data_id&quot;&gt;&lt;/div&gt;&lt;/td&gt;
            &lt;td&gt;&lt;div id=&quot;customer_data_name&quot;&gt;&lt;/div&gt;&lt;/td&gt;
            &lt;td&gt;&lt;div id=&quot;customer_data_notes&quot;&gt;&lt;/div&gt;&lt;/td&gt;
        &lt;/tr&gt;
    &lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>Downsize</h2>
<p>The downsize to this solution will be the size of the encoded transfer, this because Base64-encoded data takes about 33% more space than the original data.</p>
<h2>References</h2>
<h3>Base64 Content-Transfer-Encoding</h3>
<p>http://tools.ietf.org/html/rfc2045</p>
<p>Normally, many media types which could be usefully transported via email are<br />
represented, in their &#8220;natural&#8221; format, as 8bit character or binary data.<br />
Such data cannot be transmitted over some transfer protocols.</p>
<p>For example, email. The SMTP (simple mail transfer protocol) restricts mail<br />
messages to 7bit US-ASCII data with lines no longer than 1000 characters<br />
including any trailing CRLF line separator.</p>
<h3>PHP JS</h3>
<ul>
<li><b>base64_decode</b> &#8211; http://phpjs.org/functions/base64_decode</li>
<li><b>utf8_decode</b> &#8211; http://phpjs.org/functions/utf8_decode</li>
</ul>
<img src="http://feeds.feedburner.com/~r/PabloViquezBlog/~4/62XC2kUGkUE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pabloviquez.com/2009/07/json-iso-8859-1-and-utf-8-%e2%80%93-part2/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://www.pabloviquez.com/2009/07/json-iso-8859-1-and-utf-8-%e2%80%93-part2/</feedburner:origLink></item>
		<item>
		<title>How to use json_encode with ISO-8859-1 data – Part1</title>
		<link>http://feedproxy.google.com/~r/PabloViquezBlog/~3/qBHhe2qKfpE/</link>
		<comments>http://www.pabloviquez.com/2009/07/json-iso-8859-1-and-utf-8-part1/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 19:51:34 +0000</pubDate>
		<dc:creator>Pablo Viquez</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[iso 8859-1]]></category>
		<category><![CDATA[utf-8]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[i18n]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[json_encode]]></category>

		<guid isPermaLink="false">http://www.pabloviquez.com/?p=190</guid>
		<description><![CDATA[Download the demo files
While I was looking at some AJAX calls, I started to have a problem, for some reason, when I tried to query a JSON service I did using JQuery, the result was null for some fields.
Going a little deeper, I notice that the records from the DB were OK, and the JavaScript [...]]]></description>
			<content:encoded><![CDATA[<p><a title="Demo Files" href="http://www.pabloviquez.com/demo_files/Encoding-JSON.zip">Download the demo files</a></p>
<p>While I was looking at some AJAX calls, I started to have a problem, for some reason, when I tried to query a JSON service I did using JQuery, the result was null for some fields.</p>
<p>Going a little deeper, I notice that the records from the DB were OK, and the JavaScript was OK to, so what was the problem? <strong>The JSON Encode!</strong></p>
<p>So take for instance this code:</p>
<pre class="brush: php">
$customer =
    array(
        &#039;id&#039;    =&gt; 1,
        &#039;name&#039;  =&gt; &#039;Pablo Víquez&#039;,
        &#039;notes&#039; =&gt; &#039;Pruebas de encoding con JSON. á é í ó ú, ñ, Ñ&#039;
);

echo json_encode();
</pre>
<p>If I save it as a ISO-8859-1, the result is the following:</p>
<pre class="brush: php">
{&quot;id&quot;:1,&quot;name&quot;:null,&quot;notes&quot;:null}
</pre>
<p>Now, using the same code, but saving the PHP file as UTF-8 I got this result:</p>
<pre class="brush: php">
{&quot;id&quot;:1,&quot;name&quot;:&quot;Pablo V\u00edquez&quot;,&quot;notes&quot;:&quot;Pruebas de encoding con JSON. \u00e1 \u00e9 \u00ed \u00f3 \u00fa, \u00f1, \u00d1&quot;}
</pre>
<p>The problem that I had was that the site was built using ISO 8859-1 not UTF-8, and changing it to UTF-8 is not an option, andn the AJAX call must return a JSON response.</p>
<h3>json_encode documentation</h3>
<p>string json_encode ( mixed $value  [, int $options= 0  ] )</p>
<ul>
<li>$value: The value being encoded. Can be any type except a resource.<br />
<span style="text-decoration: underline;"><strong>This function only works with UTF-8 encoded data.</strong></span></li>
<li>$options (PHP 5.3 ONLY): Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_FORCE_OBJECT. Defaults to 0.</li>
</ul>
<p>&nbsp;</p>
<img src="http://feeds.feedburner.com/~r/PabloViquezBlog/~4/qBHhe2qKfpE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pabloviquez.com/2009/07/json-iso-8859-1-and-utf-8-part1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.pabloviquez.com/2009/07/json-iso-8859-1-and-utf-8-part1/</feedburner:origLink></item>
		<item>
		<title>PHP 5.3 with improved Type Hinting and type casting</title>
		<link>http://feedproxy.google.com/~r/PabloViquezBlog/~3/qeNrZFecqLI/</link>
		<comments>http://www.pabloviquez.com/2009/07/php-5-3-with-improved-type-hinting-and-type-casting/#comments</comments>
		<pubDate>Thu, 09 Jul 2009 15:58:46 +0000</pubDate>
		<dc:creator>Pablo Viquez</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[tech]]></category>
		<category><![CDATA[php 5.3]]></category>
		<category><![CDATA[type hinting]]></category>

		<guid isPermaLink="false">http://www.pabloviquez.com/?p=176</guid>
		<description><![CDATA[From Illia Alshanetsky blog post:
There has been a lot of comments both on this blog and the internals list. There seems to be a fairly large group of core developers who like the idea as well as surpassingly large support base on the user level too (wow, didn&#8217;t think that this many people want type [...]]]></description>
			<content:encoded><![CDATA[<p><a title="Ilia Alshanetsky Blog" href="http://ilia.ws/archives/206-Type-hinting-rehashed-now-with-type-casting-support.html" target="_blank">From Illia Alshanetsky blog post:</a></p>
<blockquote><p>There has been a lot of comments both on this blog and the internals list. There seems to be a fairly large group of core developers who like the idea as well as surpassingly large support base on the user level too (wow, didn&#8217;t think that this many people want type hinting). Unfortunately, there have also been, as is typically on the internals list a few people complaining for the sake of complaining. Their arguments have ranged from type hinting is against PHP&#8217;s loosely typed nature and people will mis-use it and make PHP into something that it is not, to I don&#8217;t need or will use it, so no one should get it.</p>
<p>…Here is the quick changelog.</p>
<ol>
<li>Added support for &#8220;object&#8221; type hint</li>
<li>Modified the patch not to break binary compatibility so you can now use patched PHP without having to re-compile your extensions or having issues with binary ones.</li>
<li>Added full reflection support, which I appropriated from Felipe&#8217;s earlier work on type hinting</li>
<li>Added support for type casting, where by you can do things like this function a((int)$foo), which will force PHP to cast the value of $foo to an integer</li>
<li>Added tests, which again I partially appropriated from Felipe&#8217;s earlier work.</li>
</ol>
</blockquote>
<p>The types that could be used (according to the proposed patch) are:</p>
<table border="0">
<tr>
<td align="center"><b>Boolean</b></td>
<td align="center"><b>String</b></td>
<td align="center"><b>Integers</b></td>
<td align="center"><b>Floats</b></td>
<td align="center"><b>Others</b></td>
</tr>
<tr>
<td valign="top">
<ul>
<li>bool</li>
<li>boolean</li>
</ul>
</td>
<td valign="top">
<ul>
<li>string</li>
<li>binary</li>
<li>unicode</li>
</ul>
</td>
<td valign="top">
<ul>
<li>int</li>
<li>integer</li>
<li>long</li>
</ul>
</td>
<td valign="top">
<ul>
<li>real</li>
<li>double</li>
<li>float</li>
</ul>
</td>
<td valign="top">
<ul>
<li>resource</li>
<li>numeric</li>
<li>scalar</li>
<li>object</li>
</ul>
</td>
</tr>
</table>
<p>So, how do that will look like? Here some examples of how this will look like:</p>
<h2>Type Casting on function definition:</h2>
<pre class="brush: php">
function printMe((int) $value) {
    var_dump($value);
}

// Output:
// int(50)
printMe(50);

// Output:
// int(123)
printMe(&#039;123&#039;);

// Output:
// int(0)
printMe(&#039;Testing&#039;);

// Output:
// int(0)
printMe(null);
</pre>
<h3>Or using String as type casting</h3>
<pre class="brush: php">
function printMeAgain((string) $value) {
    var_dump($value);
}

// Output:
// string(2) &quot;50&quot;
printMeAgain(50);

// Output:
// string(3) &quot;123&quot;
printMeAgain(&#039;123&#039;);

// Output:
// string(7) &quot;Testing&quot;
printMeAgain(&#039;Testing&#039;);

// Output:
// string(0) &quot;&quot;
printMeAgain(null);
</pre>
<h2>Type Hinting</h2>
<pre class="brush: php">
function test_int(int $a = 1) {
    var_dump($a);
}

// Output:
// int(1)
test_int();

// Output:
// int(123)
test_int(123);

// Output:
// Catchable fatal error: Argument 2 passed to test_int()
// must be of the type integer, string given
test_int(&quot;123&quot;);
</pre>
<h3>With doubles:</h3>
<pre class="brush: php">
function test_double(real $a) {
    var_dump($a);
}

// Output:
// float(1)
test_double(1);

// Output:
// float(1.123)
test_double(1.123);

// Output:
// Catchable fatal error: Argument 1 passed to
// test_double() must be of the type double,
// string given.
test_double(&quot;123&quot;);
</pre>
<h3>With Strings:</h3>
<pre class="brush: php">
function test_string(string $a) {
    var_dump($a);
}

// Output:
// string(10) &quot;Hola Mundo&quot;
test_double(&quot;Hola Mundo&quot;);

// Output:
// Catchable fatal error: Argument 1 passed to
// test_string() must be of the type string,
// int given
test_double(123);

// Output:
// Catchable fatal error: Argument 1 passed to
// test_string() must be of the type string,
// null given
test_str(null);
</pre>
<img src="http://feeds.feedburner.com/~r/PabloViquezBlog/~4/qeNrZFecqLI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pabloviquez.com/2009/07/php-5-3-with-improved-type-hinting-and-type-casting/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.pabloviquez.com/2009/07/php-5-3-with-improved-type-hinting-and-type-casting/</feedburner:origLink></item>
		<item>
		<title>Cannes Festival Touchwall</title>
		<link>http://feedproxy.google.com/~r/PabloViquezBlog/~3/MzSVIFkxQlM/</link>
		<comments>http://www.pabloviquez.com/2009/06/cannes-festival-touchwall/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 16:15:21 +0000</pubDate>
		<dc:creator>Pablo Viquez</dc:creator>
				<category><![CDATA[schematic]]></category>

		<guid isPermaLink="false">http://www.pabloviquez.com/?p=171</guid>
		<description><![CDATA[I wanted to share another video on the Touchwall.
It was made for the Cannes Lions Festival which is the largest advertising and PR conference of the year.

]]></description>
			<content:encoded><![CDATA[<p>I wanted to share another video on the Touchwall.</p>
<p>It was made for the <a title="Cannes Lions Festiva" href="http://www.canneslions.com/" target="_blank">Cannes Lions Festival</a> which is the largest advertising and PR conference of the year.</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="596" height="447" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://vimeo.com/moogaloop.swf?clip_id=5326255&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=B7C70F&amp;fullscreen=1" /><embed type="application/x-shockwave-flash" width="596" height="447" src="http://vimeo.com/moogaloop.swf?clip_id=5326255&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=B7C70F&amp;fullscreen=1" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<img src="http://feeds.feedburner.com/~r/PabloViquezBlog/~4/MzSVIFkxQlM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pabloviquez.com/2009/06/cannes-festival-touchwall/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pabloviquez.com/2009/06/cannes-festival-touchwall/</feedburner:origLink></item>
		<item>
		<title>Schematic Touchwall</title>
		<link>http://feedproxy.google.com/~r/PabloViquezBlog/~3/B89CbPonU7s/</link>
		<comments>http://www.pabloviquez.com/2009/06/schematic-touchwall/#comments</comments>
		<pubDate>Wed, 17 Jun 2009 18:10:09 +0000</pubDate>
		<dc:creator>Pablo Viquez</dc:creator>
				<category><![CDATA[schematic]]></category>
		<category><![CDATA[tech]]></category>

		<guid isPermaLink="false">http://www.pabloviquez.com/2009/06/schematic-touchwall/</guid>
		<description><![CDATA[I’m super happy for my colleagues on the success of the biggest touch wall ever!



]]></description>
			<content:encoded><![CDATA[<p>I’m super happy for my colleagues on the success of the biggest touch wall ever!</p>
<div class="wlWriterEditableSmartContent" id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:2e8e6556-cf48-4329-adb6-6840200b617a" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<div><object width="400" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=5192300&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=5192300&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="300"></embed></object></div>
</div>
<img src="http://feeds.feedburner.com/~r/PabloViquezBlog/~4/B89CbPonU7s" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pabloviquez.com/2009/06/schematic-touchwall/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.pabloviquez.com/2009/06/schematic-touchwall/</feedburner:origLink></item>
		<item>
		<title>Move foreign keys from one table to another in Oracle</title>
		<link>http://feedproxy.google.com/~r/PabloViquezBlog/~3/7xH8lAL88-8/</link>
		<comments>http://www.pabloviquez.com/2009/06/move-foreign-keys-from-one-table-to-another-in-oracle/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 15:58:54 +0000</pubDate>
		<dc:creator>Pablo Viquez</dc:creator>
				<category><![CDATA[tech]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[foreign keys]]></category>
		<category><![CDATA[oracle]]></category>

		<guid isPermaLink="false">http://www.pabloviquez.com/2009/06/move-foreign-keys-from-one-table-to-another-in-oracle/</guid>
		<description><![CDATA[I needed to switch all foreign keys from one table to another using PL/SQL in Oracle. This was the result:
Necesitaba un script para pasar los foreign keys de una tabla a otra en Oracle, al final este es el resultado:

/**
 * Modifies all references to entity_old and switch them to entity
 *
 * Process
 * [...]]]></description>
			<content:encoded><![CDATA[<p>I needed to switch all foreign keys from one table to another using PL/SQL in Oracle. This was the result:</p>
<p>Necesitaba un script para pasar los foreign keys de una tabla a otra en Oracle, al final este es el resultado:</p>
<pre class="brush: sql">
/**
 * Modifies all references to entity_old and switch them to entity
 *
 * Process
 *  1. Disable Foreign Keys
 *  2. Drop foreign key
 *  3. Create the foreign key, pointing to the new location
 */

var v_old_table varchar2(100);
var v_new_table varchar2(100);
var v_sql varchar2(500);
var v_sql_delete varchar2(500);

exec :v_old_table := &#039;OLD_TABLE_NAME_HERE&#039;;
exec :v_new_table := &#039;NEW_TABLE_NAME_HERE&#039;;

SET SERVEROUTPUT ON;
BEGIN
    FOR row_entity IN (SELECT ac.CONSTRAINT_NAME,
                              ac.CONSTRAINT_TYPE,
                              ac.TABLE_NAME,
                              ac.R_CONSTRAINT_NAME,
                              ac.STATUS,
                              ac.DELETE_RULE,
                              cc.COLUMN_NAME,
                              sr.COLUMN_NAME AS COLUMN_SOURCE
                         FROM ALL_CONSTRAINTS ac,
                              USER_CONS_COLUMNS cc,
                              USER_CONS_COLUMNS sr
                        WHERE ac.CONSTRAINT_NAME = cc.CONSTRAINT_NAME
                          AND ac.R_CONSTRAINT_NAME = sr.CONSTRAINT_NAME
                          AND ac.CONSTRAINT_TYPE = &#039;R&#039;
                        AND ac.R_CONSTRAINT_NAME IN (SELECT CONSTRAINT_NAME
                                                       FROM ALL_CONSTRAINTS
                                                      WHERE CONSTRAINT_TYPE IN (&#039;P&#039;,&#039;U&#039;)
                                                       AND TABLE_NAME = :v_old_table))
    LOOP
        BEGIN
            -- Disable the foreign key IF is enable
            IF row_entity.STATUS = &#039;ENABLED&#039; THEN
                :v_sql := &#039;ALTER TABLE &#039; || row_entity.TABLE_NAME ||
                  &#039; MODIFY CONSTRAINT &#039; || row_entity.CONSTRAINT_NAME ||
                  &#039; DISABLE&#039;;

                -- Print SQL Statement
                DBMS_OUTPUT.PUT_LINE(:v_sql || &#039;;&#039;);

                EXECUTE IMMEDIATE :v_sql;
            END IF;

            IF row_entity.DELETE_RULE = &#039;CASCADE&#039; THEN
                :v_sql_delete := &#039; ON DELETE CASCADE&#039;;
            ELSE
                :v_sql_delete := &#039;&#039;;
            END IF;

            -- Drop the table reference
            :v_sql := &#039;ALTER TABLE &#039;|| row_entity.TABLE_NAME ||
                    &#039; DROP CONSTRAINT &#039; || row_entity.CONSTRAINT_NAME;

            DBMS_OUTPUT.PUT_LINE(:v_sql || &#039;;&#039;);
            EXECUTE IMMEDIATE :v_sql;

            -- Re-create the table reference
            :v_sql := &#039;ALTER TABLE &#039;|| row_entity.TABLE_NAME ||
                    &#039; ADD CONSTRAINT &#039; || row_entity.CONSTRAINT_NAME ||
                    &#039; FOREIGN KEY (&#039; || row_entity.COLUMN_NAME || &#039;)&#039; ||
                    &#039; REFERENCES &#039; || :v_new_table || &#039; (&#039; || row_entity.COLUMN_SOURCE || &#039;)&#039; ||
                    :v_sql_delete;

            DBMS_OUTPUT.PUT_LINE(:v_sql || &#039;;&#039;);
            EXECUTE IMMEDIATE :v_sql;
        END;
    END LOOP;
END;

/

show errors;
</pre>
<img src="http://feeds.feedburner.com/~r/PabloViquezBlog/~4/7xH8lAL88-8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pabloviquez.com/2009/06/move-foreign-keys-from-one-table-to-another-in-oracle/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.pabloviquez.com/2009/06/move-foreign-keys-from-one-table-to-another-in-oracle/</feedburner:origLink></item>
		<item>
		<title>php set_include_path() function returns false</title>
		<link>http://feedproxy.google.com/~r/PabloViquezBlog/~3/Lcz6YrBm6F4/</link>
		<comments>http://www.pabloviquez.com/2009/06/php-set_include_path-function-returns-false/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 01:22:52 +0000</pubDate>
		<dc:creator>Pablo Viquez</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[errors]]></category>
		<category><![CDATA[set_include_path]]></category>
		<category><![CDATA[windows registry]]></category>

		<guid isPermaLink="false">http://www.pabloviquez.com/2009/06/php-set_include_path-function-returns-false/</guid>
		<description><![CDATA[After a while struggling with the php function set_include_path() on windows, became to my attention that using the windows registry to set php configuration values they are set using the php_admin_value which forbids overriding it&#160; on run time.
So for example, if you set the include_path on the windows registry and then you call the set_include_path [...]]]></description>
			<content:encoded><![CDATA[<p>After a while struggling with the php function set_include_path() on windows, became to my attention that using the windows registry to set php configuration values they are set using the <strong>php_admin_value</strong> which forbids overriding it&#160; on run time.</p>
<p>So for example, if you set the include_path on the windows registry and then you call the set_include_path function in your application, it will return false and won&#8217;t change the include_path.</p>
<p>The same applies if you use php_admin_value on your .htaccess file or virtual host file.</p>
<hr />
<p>Después de un tiempo luchando con la la función de PHP <strong>set_include_path()</strong> en windows, que me retornaba false cuando la llamaba, noté que cuando se usa el registro de windows (windows registry) para modificar la configuracion de PHP (<a href="http://www.pabloviquez.com/2009/06/zend-server-500-internal-error-server/">Ver: Registro de windows y la configuracion de PHP</a>), es como utilizar <strong>php_admin_value</strong> la cual no deja que se modifiquen en tiempo de ejecución.</p>
<p>Por ejemplo, si se usa el registro de windows con la configuración de PHP &quot;include_path” y luego se llama la función set_include_path en la aplicación, esta retorna false (false) y no cambiará la configuración.</p>
<p>Esto aplica también si utiliza php_admin_value en el archivo .htaccess o donde se defina un host virtual.</p>
<img src="http://feeds.feedburner.com/~r/PabloViquezBlog/~4/Lcz6YrBm6F4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pabloviquez.com/2009/06/php-set_include_path-function-returns-false/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pabloviquez.com/2009/06/php-set_include_path-function-returns-false/</feedburner:origLink></item>
	</channel>
</rss>
