<?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"
	>

<channel>
	<title>Focus on PHP</title>
	<atom:link href="http://www.mauriciocuenca.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mauriciocuenca.com/blog</link>
	<description>PHP insights, tips and tricks</description>
	<pubDate>Sat, 23 Apr 2011 15:44:14 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.1</generator>
	<language>en</language>
			<item>
		<title>Create your own Instagram app with PHP</title>
		<link>http://www.mauriciocuenca.com/blog/2011/04/create-your-own-instagram-app-with-php/</link>
		<comments>http://www.mauriciocuenca.com/blog/2011/04/create-your-own-instagram-app-with-php/#comments</comments>
		<pubDate>Sat, 23 Apr 2011 15:44:14 +0000</pubDate>
		<dc:creator>Mauricio Cuenca</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[open source]]></category>

		<category><![CDATA[instagram]]></category>

		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.mauriciocuenca.com/blog/?p=141</guid>
		<description><![CDATA[
Register your application Instagram to get your OAuth credentials.
Make sure to set your callback URL as a web address that is accessible anywhere from tje Internet, something like http://yourdoma.in/callback.php
Download the latest version of the code in zip or tar.gz format.
Unpack the code and modify the credentials stored in the $config variable of example.php to the [...]]]></description>
			<content:encoded><![CDATA[<ol>
<li><a href="http://instagr.am/developer/client/register/">Register</a> your application Instagram to get your OAuth credentials.</li>
<li>Make sure to set your callback URL as a web address that is accessible anywhere from tje Internet, something like http://yourdoma.in/callback.php</li>
<li>Download the latest version of the code in <a href="https://github.com/macuenca/Instagram-PHP-API/zipball/master">zip</a> or <a href="https://github.com/macuenca/Instagram-PHP-API/tarball/master">tar.gz</a> format.</li>
<li>Unpack the code and modify the credentials stored in the $config variable of example.php to the ones obtained in step 1</li>
<li>Point your browser to http://yourdomain/example.php. If the user is already authenticated, she must be presented with a recent popular photos screen. Otherwise, the authentication page will pop up.</li>
</ol>
<p>This is the only part of the code that you should modify in example.php:</p>
<pre class="syntax-highlight:php">
/**
* Configuration params, make sure to write exactly the ones
* instagram provide you at http://instagr.am/developer/
*/
$config = array(
    &#039;client_id&#039; =&gt; &#039;&lt;your_client_id&gt;&#039;,
    &#039;client_secret&#039; =&gt; &#039;&lt;your_client_secret&gt;&#039;,
    &#039;grant_type&#039; =&gt; &#039;authorization_code&#039;,
    &#039;redirect_uri&#039; =&gt; &#039;http://your.call/back/url.php&#039;,
);
</pre>
<p>If you have any question, don&#8217;t hesitate to post your comment and check back often, I read them frequently.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mauriciocuenca.com/blog/2011/04/create-your-own-instagram-app-with-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Instagram API implementation in PHP</title>
		<link>http://www.mauriciocuenca.com/blog/2011/02/instagram-api-implementation-in-php/</link>
		<comments>http://www.mauriciocuenca.com/blog/2011/02/instagram-api-implementation-in-php/#comments</comments>
		<pubDate>Sun, 27 Feb 2011 19:42:54 +0000</pubDate>
		<dc:creator>Mauricio Cuenca</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[english]]></category>

		<category><![CDATA[hacks]]></category>

		<category><![CDATA[open source]]></category>

		<category><![CDATA[instagram]]></category>

		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.mauriciocuenca.com/blog/?p=133</guid>
		<description><![CDATA[Instagram recently released an official API. Initially, they had implementations in Python and Ruby, so I decided to build mine in PHP with a little help from Zend Framework.
In order to use the official API, you have to sign up first for a client key at http://instagr.am/developer/. You will need to register a new client [...]]]></description>
			<content:encoded><![CDATA[<p>Instagram recently released an official API. Initially, they had implementations in Python and Ruby, so I decided to build mine in PHP with a little help from Zend Framework.</p>
<p>In order to use the official API, you have to sign up first for a client key at <a href="http://instagr.am/developer/">http://instagr.am/developer/</a>. You will need to register a new client or use the data from an existing one, just keep in mind these are the important data that you need before you can interact with the API:</p>
<p><strong>Client Id:</strong> let&#8217;s call it a public key. It is necessary so the API knows your application. This is public available information, for the purpose of the example provided with my implementation we are going to query Instagram&#8217;s service directly using the client key as part of the URL.</p>
<p><strong>Client secret:</strong> this is the private key that once paired with the client id is exchanged with Instagram&#8217;s service. The client secret needs to be private, but you have to make it available in some form inside your code so it can be sent and to get the authentication token back.</p>
<p><strong>Callback url:</strong> maybe on of the most important aspects in this example. Make sure the callback URL is exactly the same where you are going to put the script that acts as an entry point for the Instagram callback. For this particular example, this script is going to be called &#8220;instagram.php&#8221;, meaning that you&#8217;ll have to point Instagram to something like http://example.com/instagram.php.</p>
<p>So this is as easy as one, two, three.</p>
<p>1. Grab the code from GitHub in you preferred format: <a href="https://github.com/macuenca/Instagram-PHP-API/zipball/master">zip</a> or <a href="https://github.com/macuenca/Instagram-PHP-API/tarball/master">tar.gz</a> and Unpack it in the same folder you told Instagram your callback was going to live.</p>
<p>2. The example we create in this post, authenticates and displays the most popular photos according to the data sent back by the API. The implementation provides access to all public methods, so you can create you own stuff. Amongst others, you can search for media, perform &#8216;follow&#8217; actions or search media by location.</p>
<p>3. Just make sure to modify the code, so you can put your own client properties in the $config array at the beginning of the file:</p>
<pre class="syntax-highlight:php">

/**
* Configuration params, make sure to write exactly the ones
* instagram provide you at http://instagr.am/developer/
*/
$config = array(
        &#039;site_url&#039; =&gt; &#039;https://api.instagram.com/oauth/access_token&#039;,
        &#039;client_id&#039; =&gt; &#039;&#039;, // Your client id
        &#039;client_secret&#039; =&gt; &#039;&#039;, // Your client secret
        &#039;grant_type&#039; =&gt; &#039;authorization_code&#039;,
        &#039;redirect_uri&#039; =&gt; &#039;&#039;, // The redirect URI you provided when signed up for the service
     );
</pre>
<p>And now, the code of the instagram.php script:</p>
<pre class="syntax-highlight:php">
require_once &#039;Instagram.php&#039;;

/**
* Configuration params, make sure to write exactly the ones
* instagram provide you at http://instagr.am/developer/
*/
$config = array(
        &#039;site_url&#039; =&gt; &#039;https://api.instagram.com/oauth/access_token&#039;,
        &#039;client_id&#039; =&gt; &#039;&#039;, // Your client id
        &#039;client_secret&#039; =&gt; &#039;&#039;, // Your client secret
        &#039;grant_type&#039; =&gt; &#039;authorization_code&#039;,
        &#039;redirect_uri&#039; =&gt; &#039;&#039;, // The redirect URI you provided when signed up for the service
     );

// Instantiate the API handler object
$instagram = new Instagram($config);
$popular = $instagram-&gt;getPopularMedia();

// After getting the response, let&#039;s iterate the payload
echo &quot;&lt;ul&gt;\n&quot;;
$response = json_decode($popular, true);
foreach ($response[&#039;data&#039;] as $data) {
    $link = $data[&#039;link&#039;];
    $caption = $data[&#039;caption&#039;][&#039;text&#039;];
    $author = $data[&#039;caption&#039;][&#039;from&#039;][&#039;username&#039;];
    $thumbnail = $data[&#039;images&#039;][&#039;thumbnail&#039;][&#039;url&#039;];
?&gt;
&lt;li&gt;&lt;a href=&quot;&lt;?= $link ?&gt;&quot;&gt;&lt;img src=&quot;&lt;?= $thumbnail ?&gt;&quot; title=&quot;&lt;?= $caption ?&gt;&quot; width=&quot;150&quot; height=&quot;150&quot; border=&quot;0&quot; align=&quot;absmiddle&quot;&gt;&lt;/a&gt; by &lt;?= $author ?&gt;&lt;/li&gt;
&lt;?
}
echo &quot;&lt;/ul&gt;\n&quot;;
</pre>
<p>Finally, point you browser to the authorization URL and enjoy your coding!<br /> https://api.instagram.com/oauth/authorize/?client_id=CLIENT_ID&amp;redirect_uri=REDIRECT_URL.</p>
<p>You can get more details about manipulating the API at http://instagr.am/developer/</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mauriciocuenca.com/blog/2011/02/instagram-api-implementation-in-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Two (or more) Zend Framework projects on a shared host</title>
		<link>http://www.mauriciocuenca.com/blog/2009/03/two-or-more-zend-framework-projects-on-a-shared-host/</link>
		<comments>http://www.mauriciocuenca.com/blog/2009/03/two-or-more-zend-framework-projects-on-a-shared-host/#comments</comments>
		<pubDate>Tue, 10 Mar 2009 09:14:17 +0000</pubDate>
		<dc:creator>Mauricio Cuenca</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[php]]></category>

		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://www.mauriciocuenca.com/blog/?p=112</guid>
		<description><![CDATA[Shared hosting environments can be a nightmare when it comes to PHP Web Development, specially in testing stages. Yes, I know one should not be using and paying for a hosting plan if the code is still not production ready, but I have seen some cases.
I will try to show how to have the Zend [...]]]></description>
			<content:encoded><![CDATA[<p>Shared hosting environments can be a nightmare when it comes to PHP Web Development, specially in testing stages. Yes, I know one should not be using and paying for a hosting plan if the code is still not production ready, but I have seen some cases.</p>
<p>I will try to show how to have the Zend Framework installed with as many projects as you want (if your server quota allows you to) in the same web space and all these projects sharing the same ZF copy.</p>
<p>Suppose that your home directory is /home/mauricio/. From now on, I am going to refer to it as &lt;root&gt;. Create the following file structure under it:</p>
<pre class="syntax-highlight:bash">
library/
  Zend/
myfirstproject/
  application/
    controllers/
    views/
      scripts/
mysecondproject/
  application/
    controllers/
    views/
      scripts/
public_html/
  myfirstproject/
  mysecondproject/
</pre>
<p>Now <a href="http://framework.zend.com/download/latest">download</a>, extract and upload the &#8220;Zend&#8221; directory contained in the zip or gz file into the &#8220;&lt;root&gt;/library&#8221; directory of the structure that you have just created. This copy of the Zend Framework will be shared by all projects. If needed, you can upgrade to a future version of ZF just by changing its content.</p>
<p>Keep in mind that this example is based on the fact that the public folder on the hosting environment is &#8220;&lt;root&gt;/public_html&#8221;. Some providers call it &#8220;www&#8221;, so&#8230; in this example our public folder will be called &#8220;public_html&#8221;, make the appropriate changes to suit your needs.</p>
<p>The first folders: &#8220;myfirstproject&#8221; and &#8220;mysecondproject&#8221; will contain the application files that won&#8217;t be visible to the outside world. Notice that under public_html exist another two folders under the same names, these two folder will contain the bootstrap or the entry point for the application which must be of public access and all the images, style sheets and other media that your application requires.</p>
<p>Your .htaccess file under &lt;root&gt;/public_html/myfirstproject/ should look like this:</p>
<pre class="syntax-highlight:bash">
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
</pre>
<p>And the bootstrap file index.php under the same location, should look like this:</p>
<pre class="syntax-highlight:php">
&lt;?php
/**
* &lt;root&gt;/public_html/myfirstproject/index.php
*
*/

// The library folder contains Zend Framework files
define(&#039;LIBRARY_PATH&#039;,     realpath(dirname(__FILE__) . &#039;/../../library/&#039;));
define(&#039;APP_PATH&#039;,         realpath(dirname(__FILE__) . &#039;/../../myfirstproject/application/&#039;));
define(&#039;CONTROLLERS_PATH&#039;, APP_PATH . &#039;/controllers/&#039;);

// library is appended to the include_path
set_include_path(get_include_path() . PATH_SEPARATOR . LIBRARY_PATH);
include_once &#039;Zend/Loader.php&#039;;
Zend_Loader::registerAutoload();

/**
* The most important step is to set the controllers directory pointing to
* &lt;root&gt;/myfirstproject/application/controllers
*/
$front = Zend_Controller_Front::getInstance();
$front-&gt;setControllerDirectory(CONTROLLERS_PATH);
$front-&gt;dispatch();
</pre>
<p>That was the trick, let&#8217;s finish this creating our IndexController and its view. The first one should be placed on &lt;root&gt;/myfirsproject/application/controllers/IndexController.php:</p>
<pre class="syntax-highlight:php">
&lt;?php

/**
* &lt;root&gt;/myfirstproject/application/controllers/IndexController.php
*
*/
class IndexController extends Zend_Controller_Action
{
  public function indexAction()
  {
  }
}
</pre>
<p>The view should be anything you like, my bet is for:</p>
<pre class="syntax-highlight:html">
&lt;!-- &lt;root&gt;/myfirstproject/application/views/scripts/index.phtml --&gt;
&lt;html&gt;

&lt;head&gt;&lt;title&gt;It works!&lt;/title&gt;&lt;/head&gt;

&lt;body&gt;
&lt;h2&gt;It works!&lt;/h2&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>That&#8217;s all, you can start building more views, controllers and helpers. To get your second project working just follow the same steps that you did for &#8220;myfirstproject&#8221; folder. The same way, you can create as many projects as you want, keep in mind that they all share the same Zend Framework library.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mauriciocuenca.com/blog/2009/03/two-or-more-zend-framework-projects-on-a-shared-host/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Gmail outage wasn&#8217;t so bad at all!</title>
		<link>http://www.mauriciocuenca.com/blog/2009/02/gmail-outage-wasnt-so-bad-at-all/</link>
		<comments>http://www.mauriciocuenca.com/blog/2009/02/gmail-outage-wasnt-so-bad-at-all/#comments</comments>
		<pubDate>Fri, 27 Feb 2009 20:35:13 +0000</pubDate>
		<dc:creator>Mauricio Cuenca</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[opinions]]></category>

		<category><![CDATA[personal]]></category>

		<category><![CDATA[gmail]]></category>

		<category><![CDATA[google]]></category>

		<guid isPermaLink="false">http://www.mauriciocuenca.com/blog/?p=109</guid>
		<description><![CDATA[Bad news spread rapidly and everybody heard about the Gmail service disruption on February 24th. I was personally affected by the issue, fortunately I only manage my personal e-mail through Gmail, so my business communications wasn&#8217;t affected at all.
Besides the huge attention that this problem caught, I was really impressed by the open and detailed [...]]]></description>
			<content:encoded><![CDATA[<p>Bad news spread rapidly and everybody heard about the Gmail <a href="http://blogs.wsj.com/digits/2009/02/24/gmail-outage-disrupts-working-day/">service disruption on February 24th</a>. I was personally affected by the issue, fortunately I only manage my personal e-mail through Gmail, so my business communications wasn&#8217;t affected at all.</p>
<p>Besides the huge attention that this problem caught, I was really impressed by the open and detailed response that Google gave to all of its customers. One good thing about the Gfail issue was the creation of the new <a href="http://www.google.com/appsstatus#">Google apps status dashboard</a>, where &#8211;as its name says&#8211; people can see the status of the main Google services with very detailed information, like this <a href="http://www.google.com/appsstatus/ir/1nsexcr2jnrj1d6.pdf">PDF report</a> about the past Gmail issue.</p>
<p>How I wish that many companies follow this lead&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mauriciocuenca.com/blog/2009/02/gmail-outage-wasnt-so-bad-at-all/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Yahoo Briefcase is shut down</title>
		<link>http://www.mauriciocuenca.com/blog/2009/02/yahoo-briefcase-is-shut-down/</link>
		<comments>http://www.mauriciocuenca.com/blog/2009/02/yahoo-briefcase-is-shut-down/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 09:25:44 +0000</pubDate>
		<dc:creator>Mauricio Cuenca</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[opinions]]></category>

		<category><![CDATA[personal]]></category>

		<category><![CDATA[briefcase]]></category>

		<category><![CDATA[shutdown]]></category>

		<category><![CDATA[yahoo]]></category>

		<guid isPermaLink="false">http://www.mauriciocuenca.com/blog/?p=104</guid>
		<description><![CDATA[After almost ten years of enjoying my little briefcase, Yahoo! decided to pull the plug. I think I won&#8217;t miss it

Full details on this link!
]]></description>
			<content:encoded><![CDATA[<p>After almost ten years of enjoying my little briefcase, Yahoo! decided to pull the plug. I think I won&#8217;t miss it</p>
<p><a href="http://www.mauriciocuenca.com/blog/wp-content/uploads/2009/02/yahoobriefcasenotice.gif"><img class="aligncenter size-full wp-image-105" title="Yahoo! Briefcase shutdown notice" src="http://www.mauriciocuenca.com/blog/wp-content/uploads/2009/02/yahoobriefcasenotice.gif" alt="" width="500" height="156" /></a></p>
<p>Full details on <a href="http://help.yahoo.com/l/us/yahoo/briefcase/closing/index.html">this link</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mauriciocuenca.com/blog/2009/02/yahoo-briefcase-is-shut-down/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Barcelona international PHP conference wrap up</title>
		<link>http://www.mauriciocuenca.com/blog/2008/10/barcelona-international-php-conference-wrap-up/</link>
		<comments>http://www.mauriciocuenca.com/blog/2008/10/barcelona-international-php-conference-wrap-up/#comments</comments>
		<pubDate>Sun, 05 Oct 2008 17:08:13 +0000</pubDate>
		<dc:creator>Mauricio Cuenca</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[open source]]></category>

		<category><![CDATA[php]]></category>

		<category><![CDATA[barcelona]]></category>

		<category><![CDATA[conference]]></category>

		<category><![CDATA[phpbcnint08]]></category>

		<guid isPermaLink="false">http://www.mauriciocuenca.com/blog/?p=93</guid>
		<description><![CDATA[After attending Google Developer Day in Madrid, I knew it was going to be hard to impress me. But the guys from phpbcnint08 blowed me away! Not only because of the very high quality of the speakers, the comfortable and appropriate venue, the really good meal, the all you can drink or the Wii, the [...]]]></description>
			<content:encoded><![CDATA[<p>After attending <a href="http://www.theserverlabs.com/blog/2008/09/26/google-developer-day-madrid-2008/" target="_blank">Google Developer Day in Madrid</a>, I knew it was going to be hard to impress me. But the guys from <a href="http://www.flickr.com/photos/tags/phpbcnint08/">phpbcnint08</a> blowed me away! Not only because of the very high quality of the speakers, the comfortable and appropriate venue, the really good meal, the all you can drink or the Wii, the XBOX 360, the Acer Aspire One, the O&#8217;Reilly books and the flight tickets they gave away.</p>
<p><img class="aligncenter" title="A short and nice break" src="http://farm4.static.flickr.com/3263/2896056577_a93cdc5f1e.jpg" alt="" width="500" height="333" /></p>
<p>What really impressed me was the love and commitement that all of the organizers showed about PHP. Some people say that you get what you pay for&#8230; well, the event registration was only 20 euros and some of the best-known PHP community speakers were there.</p>
<p>There were simultaneous talks, so I couldn&#8217;t attend all of them:</p>
<p>Marcus Bointon started with e-mail in PHP, not only showed the benefits of <a href="http://phpmailer.codeworxtech.com/" target="_blank">PHP Mailer</a>, he also dug into the mass mailing topic, giving some interesting facts and recommendations about handling the delivery of  huge amounts of e-mails.</p>
<p>The next talk was as entertaining as interesting, Arno Schneider who does a really good job designing very appealing slides, explained his disagreement with <a href="http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html" target="_blank">Rasmus Lerdorf about PHP frameworks</a>, showed some real world examples and took many of us back to our early programming days when our code was a mess.</p>
<p>Scott MacVicar and Derick Rethans were the last ones, they talked about SQLite 3 and Xdebug respectively. A pair of interesting and mature projects, both of which I&#8217;ve had the time to test drive.</p>
<p>My trip to Barcelona was totally worth it. I want to give a huge thanks to the organizers and encourage them to keep up with their loyalty and hard work towards the community, creating this type of good quality events and hoping for nothing in return.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mauriciocuenca.com/blog/2008/10/barcelona-international-php-conference-wrap-up/feed/</wfw:commentRss>
		</item>
		<item>
		<title>No more blogger</title>
		<link>http://www.mauriciocuenca.com/blog/2008/09/no-more-blogger/</link>
		<comments>http://www.mauriciocuenca.com/blog/2008/09/no-more-blogger/#comments</comments>
		<pubDate>Sat, 20 Sep 2008 15:16:54 +0000</pubDate>
		<dc:creator>Mauricio Cuenca</dc:creator>
		
		<category><![CDATA[opinions]]></category>

		<category><![CDATA[blogger]]></category>

		<guid isPermaLink="false">http://mauriciocuenca.com/wp/?p=29</guid>
		<description><![CDATA[After exchanging several e-mails back and forth with WordPress.com technical support, neither they nor I were able to migrate my blog from Blogger to WordPress, I had to do it manually. It seems that Google is not putting so much attention to Blogger as it does with other services.
So I&#8217;m glad to have this new [...]]]></description>
			<content:encoded><![CDATA[<p>After exchanging several e-mails back and forth with WordPress.com technical support, neither they nor I were able to migrate my blog from Blogger to WordPress, I had to do it manually. It seems that Google is not putting so much attention to Blogger as it does with other services.</p>
<p>So I&#8217;m glad to have this new blog!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mauriciocuenca.com/blog/2008/09/no-more-blogger/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Validación encadenada de formularios usando Zend_Filter_Input</title>
		<link>http://www.mauriciocuenca.com/blog/2008/09/validacion-encadenada-de-formularios-usando-zend_filter_input/</link>
		<comments>http://www.mauriciocuenca.com/blog/2008/09/validacion-encadenada-de-formularios-usando-zend_filter_input/#comments</comments>
		<pubDate>Thu, 18 Sep 2008 11:28:39 +0000</pubDate>
		<dc:creator>Mauricio Cuenca</dc:creator>
		
		<category><![CDATA[español]]></category>

		<category><![CDATA[php]]></category>

		<category><![CDATA[zend framework]]></category>

		<category><![CDATA[formulario]]></category>

		<category><![CDATA[validación]]></category>

		<guid isPermaLink="false">http://www.mauriciocuenca.com/blog/?p=84</guid>
		<description><![CDATA[Zend_Validator junto con Zend_Filter se convierten en una herramienta bastante poderosa para la validación de datos y formularios.
Hay que tener en cuenta que gracias a la arquitectura de Libre Uso (Use At Will) de Zend Framework, este pedazo de código puede ser usado en cualquier proyecto sin importar si se implementa MVC o no.
Como ejemplos [...]]]></description>
			<content:encoded><![CDATA[<p>Zend_Validator junto con Zend_Filter se convierten en una herramienta bastante poderosa para la validación de datos y formularios.<br />
Hay que tener en cuenta que gracias a la arquitectura de Libre Uso (Use At Will) de Zend Framework, este pedazo de código puede ser usado en cualquier proyecto sin importar si se implementa MVC o no.</p>
<p>Como ejemplos anteriores, este es bastante sencillo:</p>
<p>El indexAction() muestra la vista con el formulario que debe ser validado, si no se usa MVC olvidémoslo.</p>
<p>validateAction() es donde todo sucede, primero se declara una clase con un validador personalizado (que explicaré luego). La validación encadenada es creada, cada una especifica la clase de validación que se utiliza con sus respectivos parámetros y los mensajes predeterminados a mostrar. </p>
<p>Los mensajes personalizados son una característica bastante útil, especialmente cuando se desarrollan aplicaciones multi-lenguaje.</p>
<p>Luego se crea un array con los filtros a aplicar, no todos los datos son filtrados. En este caso, solo la edad, la dirección y el número telefónico son &#8220;limpiados&#8221; para evitar que lleguen caracteres prohibidos.</p>
<p>Finalmente Zend_Filter_Input entra en el juego, recibiendo todos los datos del formulario y chequeando todos en un solo llamado al método isValid().</p>
<p>Adicionalmente, estoy usando FlashMessenger para almacenar los mensajes de éxito o error y mostrarlos en el próximo llamado HTTP. Recuerde que los mensajes del FlashMessenger no pueden ser mostrados en la misma acción que se instancian.</p>
<p>Cualquier duda o comentario en macuenca@[ElCorreodeGoogle].com</p>
<pre class="syntax-highlight:php">
class ValidatorController extends Zend_Controller_Action
{
    /**
     * Renders the form
     *
     */
    public function indexAction()
    {
        show_source(PATH_CONTROLLERS . &#039;ExampleController.php&#039;);
    }

    /**
     * Validates the input
     *
     */
    public function validateAction()
    {
        /**
         * The included class is an example of custom validators
         */
        require_once PATH_CLASSES . &#039;My_Validate_Url.php&#039;;
        $validurl = new My_Validate_Url();
        $validurl-&gt;setMessage(&#039;Invalid URL&#039;, My_Validate_URL::NOT_MATCH);
        $validurl-&gt;setMessage(&#039;Empty&#039;, My_Validate_URL::STRING_EMPTY);
        $validators = array(
             &#039;address&#039; =&gt; array(&#039;Alnum&#039;, new Zend_Validate_Alnum(true),
                                &#039;messages&#039; =&gt; array(
                                &#039;Address not valid&#039;, // Default error message
                                // Specific error messages
                                array(Zend_Validate_Alnum::NOT_ALNUM =&gt;
                                      &#039;Address contains invalid characters&#039;,
                                      Zend_Validate_Alnum::STRING_EMPTY =&gt;
                                      &#039;Address field is mandatory&#039;))),
             &#039;phone&#039;   =&gt; array(&#039;Digits&#039;, new Zend_Validate_Digits(),
                                &#039;messages&#039; =&gt; array(
                                &#039;Wrong phone number format&#039;,
                                array(Zend_Validate_Digits::NOT_DIGITS =&gt;
                                      &#039;Phone number can only have digits&#039;,
                                      Zend_Validate_Digits::STRING_EMPTY =&gt;
                                      &#039;Phone number can not be empty&#039;))),
             &#039;age&#039;     =&gt; array(&#039;Digits&#039;, new Zend_Validate_Between(16, 59),
                                &#039;messages&#039; =&gt; array(
                                &#039;You do not qualify because of your age&#039;,
                                array(Zend_Validate_Between::NOT_BETWEEN =&gt;
                                      &#039;Age is not between the allowed range&#039;))),
             &#039;id&#039;      =&gt; array(&#039;StringLength&#039;, new Zend_Validate_StringLength(8, 10),
                                &#039;messages&#039; =&gt; array(
                                &#039;ID not valid&#039;,
                                array(Zend_Validate_StringLength::TOO_LONG =&gt;
                                      &#039;ID is too long&#039;,
                                      Zend_Validate_StringLength::TOO_SHORT =&gt;
                                      &#039;ID is too short&#039;))),
             &#039;date&#039;    =&gt; array(&#039;Date&#039;, new Zend_Validate_Date(),
                                &#039;messages&#039; =&gt; array(
                                &#039;Wrong date&#039;,
                                array(Zend_Validate_Date::INVALID =&gt;
                                      &#039;Date not recognized as valid&#039;,
                                      Zend_Validate_Date::FALSEFORMAT =&gt;
                                      &#039;Date format is incorrect&#039;,
                                      Zend_Validate_Date::NOT_YYYY_MM_DD =&gt;
                                     &#039;Date format must be YYYY-MM-DD&#039;))),
              &#039;url&#039;      =&gt; $validurl
           );

        /**
         * Age, address and phone are also filtered
         * The true param in Zend_Filter_Alnum tells it to allows whitespaces
         */
        $filters = array(&#039;age&#039;      =&gt; &#039;Int&#039;,
                         &#039;address&#039;  =&gt; array(&#039;Alnum&#039;, new Zend_Filter_Alnum(true)),
                         &#039;phone&#039;    =&gt; &#039;Digits&#039;);

        // Now we chain the validators, the filters and pass the post params on
        $input = new Zend_Filter_Input($filters, $validators);
        $input-&gt;setData($this-&gt;getRequest()-&gt;getParams());

        // Check whether errors occur
        if ($input-&gt;isValid())
        {
            $this-&gt;_helper-&gt;FlashMessenger-&gt;addMessage(&#039;Success!&#039;);
            $this-&gt;_helper-&gt;redirector(&#039;index&#039;);
        } else {
            $messages = $input-&gt;getMessages();
            foreach ($messages as $key =&gt; $value)
            {
                // Store all messages in FlashMessenger
                foreach ($value as $msg)
                {
                    $this-&gt;_helper-&gt;FlashMessenger-&gt;addMessage($msg);
                }
            }
        }

        // There are errors, the index action will show them...
        $this-&gt;_helper-&gt;redirector(&#039;index&#039;);
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.mauriciocuenca.com/blog/2008/09/validacion-encadenada-de-formularios-usando-zend_filter_input/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Creating a custom form validator using Zend_Validate</title>
		<link>http://www.mauriciocuenca.com/blog/2008/09/creating-a-custom-forma-validator-using-zend_validate/</link>
		<comments>http://www.mauriciocuenca.com/blog/2008/09/creating-a-custom-forma-validator-using-zend_validate/#comments</comments>
		<pubDate>Thu, 18 Sep 2008 11:26:11 +0000</pubDate>
		<dc:creator>Mauricio Cuenca</dc:creator>
		
		<category><![CDATA[php]]></category>

		<category><![CDATA[zend framework]]></category>

		<category><![CDATA[form validation]]></category>

		<guid isPermaLink="false">http://www.mauriciocuenca.com/blog/?p=72</guid>
		<description><![CDATA[Zend_Validate_Interface allows to create any type of validator, though a Zend_Validate_Regex exists, I created my own URL validator using a regular expression just for the sake of this example.
You can see the custom validator in action in this post.
This is the code:

class My_Validate_Url extends Zend_Validate_Abstract
{
    /**
     * Validation [...]]]></description>
			<content:encoded><![CDATA[<p>Zend_Validate_Interface allows to create any type of validator, though a Zend_Validate_Regex exists, I created my own URL validator using a regular expression just for the sake of this example.</p>
<p>You can see the custom validator in action in this post.</p>
<p>This is the code:</p>
<pre class="syntax-highlight:php">
class My_Validate_Url extends Zend_Validate_Abstract
{
    /**
     * Validation failure message key for when the value is an empty string
     */
    const STRING_EMPTY = &#039;stringEmpty&#039;;
    const NOT_MATCH    = &#039;urlNotMatch&#039;;

    /**
     * @var array
     */
    protected $_messageTemplates = array(
        self::NOT_MATCH    =&gt; &quot;&#039;%value%&#039; does not match an url&quot;,
        self::STRING_EMPTY =&gt; &quot;&#039;%value% is an empty string&quot;
    );

    public function isValid($value)
    {
        $valueString = (string) $value;

        $this-&gt;_setValue($valueString);

        if (&#039;&#039; === $valueString) {
            $this-&gt;_error(self::STRING_EMPTY);
            return false;
        } elseif (!preg_match(&#039;#https?://([-\w\.])+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?#&#039;, $valueString)) {
            $this-&gt;_error(self::NOT_MATCH);
            return false;
        }

        return true;
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.mauriciocuenca.com/blog/2008/09/creating-a-custom-forma-validator-using-zend_validate/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Validator chains using Zend_Filter_Input</title>
		<link>http://www.mauriciocuenca.com/blog/2008/09/validator-chains-using-zend_filter_input/</link>
		<comments>http://www.mauriciocuenca.com/blog/2008/09/validator-chains-using-zend_filter_input/#comments</comments>
		<pubDate>Thu, 18 Sep 2008 11:23:29 +0000</pubDate>
		<dc:creator>Mauricio Cuenca</dc:creator>
		
		<category><![CDATA[english]]></category>

		<category><![CDATA[php]]></category>

		<category><![CDATA[zend framework]]></category>

		<category><![CDATA[form validation]]></category>

		<guid isPermaLink="false">http://www.mauriciocuenca.com/blog/?p=69</guid>
		<description><![CDATA[Zend_Validator paired with Zend_Filter become a powerfull tool for validating data and forms.
Keep in mind that thanks to the Use At Will architecture of the Zend Framework, you can use this sample code in any PHP5 based project, does not matter if your using MVC or not.
Like all my examples, this is pretty straightforward:
The indexAction() [...]]]></description>
			<content:encoded><![CDATA[<p>Zend_Validator paired with Zend_Filter become a powerfull tool for validating data and forms.<br />
Keep in mind that thanks to the Use At Will architecture of the Zend Framework, you can use this sample code in any PHP5 based project, does not matter if your using MVC or not.</p>
<p>Like all my examples, this is pretty straightforward:</p>
<p>The indexAction() only shows the view that contains the form to be validated, if you&#8217;re not using MVC you can leave it behind.<br />
validateAction() is where all the magic happens, first a class for a custom validator (explained in other post) is declared. Then the validator chain is created, each one specifying the validator class being used with its respective parameters and the custom messages to show. The custom messages is a real nice feature, specially when developing multi-language applications.<br />
Then the filters array is created, not all input is filtered. In this case, just the age, address and phone are &#8220;cleaned&#8221; to avoid forbidden characters.<br />
Finally Zend_Filter_Input comes into the game, receiving all the form&#8217;s data and checking everything at once with its isValid() method.</p>
<p>Additionally, I&#8217;m using FlashMessenger to store the messages and show them in the following page reload. Keep in mind that FlashMessenger&#8217;s message can not be displayed in the same action where they are instantiated.</p>
<p>Any questions feel free to write me to macuenca@Google&#8217;sEmailService.com</p>
<pre class="syntax-highlight:php">
class ValidatorController extends Zend_Controller_Action
{
    /**
     * Renders the form
     *
     */
    public function indexAction()
    {
        show_source(PATH_CONTROLLERS . &#039;ExampleController.php&#039;);
    }

    /**
     * Validates the input
     *
     */
    public function validateAction()
    {
        /**
         * The included class is an example of custom validators
         */
        require_once PATH_CLASSES . &#039;My_Validate_Url.php&#039;;
        $validurl = new My_Validate_Url();
        $validurl-&gt;setMessage(&#039;Invalid URL&#039;, My_Validate_URL::NOT_MATCH);
        $validurl-&gt;setMessage(&#039;Empty&#039;, My_Validate_URL::STRING_EMPTY);
        $validators = array(
             &#039;address&#039; =&gt; array(&#039;Alnum&#039;, new Zend_Validate_Alnum(true),
                                &#039;messages&#039; =&gt; array(
                                &#039;Address not valid&#039;, // Default error message
                                // Specific error messages
                                array(Zend_Validate_Alnum::NOT_ALNUM =&gt;
                                      &#039;Address contains invalid characters&#039;,
                                      Zend_Validate_Alnum::STRING_EMPTY =&gt;
                                      &#039;Address field is mandatory&#039;))),
             &#039;phone&#039;   =&gt; array(&#039;Digits&#039;, new Zend_Validate_Digits(),
                                &#039;messages&#039; =&gt; array(
                                &#039;Wrong phone number format&#039;,
                                array(Zend_Validate_Digits::NOT_DIGITS =&gt;
                                      &#039;Phone number can only have digits&#039;,
                                      Zend_Validate_Digits::STRING_EMPTY =&gt;
                                      &#039;Phone number can not be empty&#039;))),
             &#039;age&#039;     =&gt; array(&#039;Digits&#039;, new Zend_Validate_Between(16, 59),
                                &#039;messages&#039; =&gt; array(
                                &#039;You do not qualify because of your age&#039;,
                                array(Zend_Validate_Between::NOT_BETWEEN =&gt;
                                      &#039;Age is not between the allowed range&#039;))),
             &#039;id&#039;      =&gt; array(&#039;StringLength&#039;, new Zend_Validate_StringLength(8, 10),
                                &#039;messages&#039; =&gt; array(
                                &#039;ID not valid&#039;,
                                array(Zend_Validate_StringLength::TOO_LONG =&gt;
                                      &#039;ID is too long&#039;,
                                      Zend_Validate_StringLength::TOO_SHORT =&gt;
                                      &#039;ID is too short&#039;))),
             &#039;date&#039;    =&gt; array(&#039;Date&#039;, new Zend_Validate_Date(),
                                &#039;messages&#039; =&gt; array(
                                &#039;Wrong date&#039;,
                                array(Zend_Validate_Date::INVALID =&gt;
                                      &#039;Date not recognized as valid&#039;,
                                      Zend_Validate_Date::FALSEFORMAT =&gt;
                                      &#039;Date format is incorrect&#039;,
                                      Zend_Validate_Date::NOT_YYYY_MM_DD =&gt;
                                     &#039;Date format must be YYYY-MM-DD&#039;))),
              &#039;url&#039;      =&gt; $validurl
           );

        /**
         * Age, address and phone are also filtered
         * The true param in Zend_Filter_Alnum tells it to allows whitespaces
         */
        $filters = array(&#039;age&#039;      =&gt; &#039;Int&#039;,
                         &#039;address&#039;  =&gt; array(&#039;Alnum&#039;, new Zend_Filter_Alnum(true)),
                         &#039;phone&#039;    =&gt; &#039;Digits&#039;);

        // Now we chain the validators, the filters and pass the post params on
        $input = new Zend_Filter_Input($filters, $validators);
        $input-&gt;setData($this-&gt;getRequest()-&gt;getParams());

        // Check whether errors occur
        if ($input-&gt;isValid())
        {
            $this-&gt;_helper-&gt;FlashMessenger-&gt;addMessage(&#039;Success!&#039;);
            $this-&gt;_helper-&gt;redirector(&#039;index&#039;);
        } else {
            $messages = $input-&gt;getMessages();
            foreach ($messages as $key =&gt; $value)
            {
                // Store all messages in FlashMessenger
                foreach ($value as $msg)
                {
                    $this-&gt;_helper-&gt;FlashMessenger-&gt;addMessage($msg);
                }
            }
        }

        // There are errors, the index action will show them...
        $this-&gt;_helper-&gt;redirector(&#039;index&#039;);
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.mauriciocuenca.com/blog/2008/09/validator-chains-using-zend_filter_input/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

