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

<channel>
	<title>Tudor Barbu&#039;s professional blog &#187; zend framework</title>
	<atom:link href="http://blog.motane.lu/tag/zend-framework/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.motane.lu</link>
	<description>Ramblings about software development</description>
	<lastBuildDate>Thu, 02 Feb 2012 17:38:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Paginating randomly ordered SQL results with Zend_Paginate</title>
		<link>http://blog.motane.lu/2012/01/10/paginating-randomly-ordered-sql-results-with-zend_paginate/</link>
		<comments>http://blog.motane.lu/2012/01/10/paginating-randomly-ordered-sql-results-with-zend_paginate/#comments</comments>
		<pubDate>Tue, 10 Jan 2012 19:32:28 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[mysq]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1837</guid>
		<description><![CDATA[As some of you might already know, I&#8217;m working on my latest project, StoreBeez, which is a virtual mall where independent businesses and artisans can open an online store fast and easy, without having to pay any upfront costs. The products are also displayed on our frontpage. And since I don&#8217;t want to promote a [...]]]></description>
			<content:encoded><![CDATA[<p>As some of you might already know, I&#8217;m working on my latest project, <a href="http://www.storebeez.com" title="E-commerce platform helping independent businesses and artisans go online by providing them with a free online store and free marketing" class="outgoing">StoreBeez</a>, which is a virtual mall where independent businesses and artisans can open an online store fast and easy, without having to pay any upfront costs. </p>
<p>The products are also displayed on our frontpage. And since I don&#8217;t want to promote a given store &#8211; all out stores are equal &#8211; displaying the products in random order seemed like a good idea. Retrieving random results is simple, just use MySQL&#8217;s <a href="http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand" title="MySQL's manual entry for rand()" class="outgoing">rand()</a> function and make the queries look like:</p>
<pre class="brush: sql; title: ; notranslate">
SELECT * FROM `table` ORDER BY RAND();
</pre>
<p>Which works. Every time the user reloads the page, different results are shown. The problem arises when I&#8217;m trying to paginate. Every request means a new random order and sometimes rows get displayed multiple times &#8211; on different pages &#8211; or simply get &#8220;lost&#8221;.</p>
<p>The solution is to keep the same order between two consecutive requests. To do this, just pass a seed to the random number generator:</p>
<pre class="brush: sql; title: ; notranslate">
SELECT * FROM `table` ORDER BY RAND({seed});
</pre>
<p>&#8230;where {seed} is a number kept in session. This way, the order is kept between requests. Given that I use Zend Framework as my &#8220;weapon of choice&#8221;, I will post a ZF solution below:</p>
<p>In the controller:</p>
<pre class="brush: php; title: ; notranslate">
$page = intval($this-&gt;_getParam('page'));
$page = $page ?: 1;

if ($page == 1) {
    $namespace = new Zend_Session_Namespace('random_key');
    $namespace-&gt;key = time();
}

$productsTable = new My_Table_Products();
$products = $productsTable-&gt;fetchPaginator();
$products-&gt;setItemCountPerPage(10)
         -&gt;setCurrentPageNumber($page);
</pre>
<p>And in the table:</p>
<pre class="brush: php; title: ; notranslate">
class My_Table_Products
{
    // ...

    public function fetchPaginator()
    {
        $namespace = new Zend_Session_Namespace('random_key');
        $select = $this-&gt;select()
                       -&gt;order('RAND(' . $namespace-&gt;random_key . ')');

        $paginator = Zend_Paginator::factory($select);

        return $paginator;
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2012/01/10/paginating-randomly-ordered-sql-results-with-zend_paginate/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Zend Framework 2.0</title>
		<link>http://blog.motane.lu/2011/11/10/zend-framework-2-0/</link>
		<comments>http://blog.motane.lu/2011/11/10/zend-framework-2-0/#comments</comments>
		<pubDate>Thu, 10 Nov 2011 15:46:40 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1623</guid>
		<description><![CDATA[Looks promising]]></description>
			<content:encoded><![CDATA[<p>Looks promising</p>
<p><iframe width="420" height="315" src="http://www.youtube.com/embed/T0LMaODppcc" frameborder="0" allowfullscreen></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2011/11/10/zend-framework-2-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Uploadify on Zend Framework and the 302 error</title>
		<link>http://blog.motane.lu/2011/10/20/uploadify-on-zend-framework-and-the-302-error/</link>
		<comments>http://blog.motane.lu/2011/10/20/uploadify-on-zend-framework-and-the-302-error/#comments</comments>
		<pubDate>Wed, 19 Oct 2011 23:46:30 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1602</guid>
		<description><![CDATA[Uploadify is an awesome script and it works like a charm. But &#8211; there&#8217;s always a but &#8211; sometimes it throws a mysterious 302 error. This happened to me all day long and it drove me crazy. Well, not really, I was already crazy So, what to do when the HTTP 302 error pops? A [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.uploadify.com/" title="Uploadify" class="outgoing">Uploadify</a> is an awesome script and it works like a charm. But &#8211; there&#8217;s always a but &#8211; sometimes it throws a mysterious 302 error. This happened to me all day long and it drove me crazy. Well, not really, I was already crazy <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  So, what to do when the HTTP 302 error pops? A quick look over HTTP statuses should point the me in the right direction:</p>
<blockquote><p>
The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.</p>
<p>The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).</p>
<p>If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.
</p></blockquote>
<p>from <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3" title="RFC 2626" class="outgoing">here</a>. In simple English, that means a redirect. So what happens!? For security reasons, I turned on the <a href="http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-httponly" title="PHP Settings - Cookie HttpOnly" class="outgoing">cookie-httponly</a> setting and the client-side script was unable to access the cookies and pass the session id back to the server-side script, which in term would see this connection as coming from an non-authenticated user and issue a redirect to the login page. Thus the mysterious 302 status.</p>
<p>The problem can be solved really easy, by turning the cookie-httponly setting off for the entire application. If that&#8217;s not desirable, there&#8217;s a more complicated solution. First, Uploadify must send the session id to the server together with the file:</p>
<pre class="brush: jscript; title: ; notranslate">
$('#fileUpload').uploadify({
    'uploader'   : '/uploadify/uploadify.swf',
    'script'     : '/images/upload/',
    'cancelImg'  : '/uploadify/cancel.png',
    'auto'       : true,
    'fileExt'    : '*.jpg;*.gif;*.png',
    'fileDesc'   : 'Image Files',
    'sizeLimit'  : 2097152,
    'scriptData' : {'sid' : '&lt;?=Zend_Session::getId();?&gt;'},
    onComplete   : function(event, id, fileObj, response, data) {
        // bla bla bla
    }
}
</pre>
<p>&#8230;then, turn off the auto-start in the application.ini file:</p>
<pre class="brush: plain; title: ; notranslate">
phpSettings.session.strict	= &quot;On&quot;
</pre>
<p>&#8230;and in the Bootstrap.php file:</p>
<pre class="brush: php; title: ; notranslate">
protected function _initSession()
{
	if (isset($_POST['sid'])) {
		Zend_Session::setId($_POST['sid']);
	}

	Zend_Session::start();
}
</pre>
<p>Of course, there are some security issues with both approaches, but nothing serious. Took me about 2 hours to figure it out <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2011/10/20/uploadify-on-zend-framework-and-the-302-error/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Single error message for Zend_Validate_EmailAddress</title>
		<link>http://blog.motane.lu/2011/01/07/single-error-message-for-zend_validate_emailaddress/</link>
		<comments>http://blog.motane.lu/2011/01/07/single-error-message-for-zend_validate_emailaddress/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 16:51:25 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1488</guid>
		<description><![CDATA[One of the strong assets of Zend Framework is its rich built in package of validators. It has validators for just about anything, from simple email addresses and digits to credit card numbers and database rows. Yet, sometimes things go wrong and they need to be hacked back on track. Today&#8217;s problem was with the [...]]]></description>
			<content:encoded><![CDATA[<p>One of the strong assets of Zend Framework is its rich built in package of validators. It has validators for just about anything, from simple email addresses and digits to credit card numbers and database rows. Yet, sometimes things go wrong and they need to be hacked back on track. Today&#8217;s problem was with the email address validator that sometimes generates some very user-unfriendly error messages. Like such:</p>
<blockquote><p>
&#8216;bad.email&#8217; is no valid hostname for email address &#8216;testing@bad.email&#8217;<br />
&#8216;bad.email&#8217; does not match the expected structure for a DNS hostname<br />
&#8216;bad.email&#8217; appears to be a local network name but local network names are not allowed
</p></blockquote>
<p>For the average user, these messages can be very confusing and sometimes is much better to just show an easy to understand &#8220;<em>Please enter a correct email</em>&#8221; message. How hard can that be with Zend Framework!?! Well&#8230;let&#8217;s say it&#8217;s not as simple as it looks.</p>
<p>The obvious thing to do is to add custom error messages (basically adding the same message over and over again). Like such: </p>
<pre class="brush: php; title: ; notranslate">
$email-&gt;setOptions(
    array(
        'label'      =&gt; 'Email',
        'required'   =&gt; true,
        'filters'    =&gt; array(
            'StringTrim',
            'StripTags',
        ),
        'validators' =&gt; array(
            array(
                'EmailAddress',
                true,
                array(
                    'allow' =&gt; Zend_Validate_Hostname::ALLOW_DNS,
                    'domain' =&gt; true,
                    'mx' =&gt; true,
                    'deep' =&gt; true,
                    'messages' =&gt; array(
                        Zend_Validate_EmailAddress::INVALID =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::INVALID_FORMAT =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::INVALID_HOSTNAME =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::INVALID_MX_RECORD =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::INVALID_SEGMENT =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::DOT_ATOM =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::QUOTED_STRING =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::INVALID_LOCAL_PART =&gt; 'Please enter a correct email'
                    ),
                ),
            ),
        ),
    )
);
</pre>
<p>But it won&#8217;t work. That&#8217;s because <em>Zend_Validate_EmailAddress</em> calls <em>Zend_Validate_Hostname</em> internally, so custom error messages should be added also for the <em>Zend_Validate_Hostname</em> validator.</p>
<pre class="brush: php; title: ; notranslate">
$email-&gt;setOptions(
    array(
        'label'      =&gt; 'Email',
        'required'   =&gt; true,
        'filters'    =&gt; array(
            'StringTrim',
            'StripTags',
        ),
        'validators' =&gt; array(
            array(
                'EmailAddress',
                true,
                array(
                    'allow' =&gt; Zend_Validate_Hostname::ALLOW_DNS,
                    'domain' =&gt; true,
                    'mx' =&gt; true,
                    'deep' =&gt; true,
                    'messages' =&gt; array(
                        Zend_Validate_EmailAddress::INVALID =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::INVALID_FORMAT =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::INVALID_HOSTNAME =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::INVALID_MX_RECORD =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::INVALID_SEGMENT =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::DOT_ATOM =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::QUOTED_STRING =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::INVALID_LOCAL_PART =&gt; 'Please enter a correct email',
                        Zend_Validate_EmailAddress::LENGTH_EXCEEDED =&gt; 'Please enter a correct email',
                        Zend_Validate_Hostname::CANNOT_DECODE_PUNYCODE =&gt; 'Please enter a correct email',
                        Zend_Validate_Hostname::INVALID =&gt; 'Please enter a correct email',
                        Zend_Validate_Hostname::INVALID_DASH =&gt; 'Please enter a correct email',
                        Zend_Validate_Hostname::INVALID_HOSTNAME =&gt; 'Please enter a correct email',
                        Zend_Validate_Hostname::INVALID_HOSTNAME_SCHEMA =&gt; 'Please enter a correct email',
                        Zend_Validate_Hostname::INVALID_LOCAL_NAME =&gt; 'Please enter a correct email',
                        Zend_Validate_Hostname::INVALID_URI =&gt; 'Please enter a correct email',
                        Zend_Validate_Hostname::IP_ADDRESS_NOT_ALLOWED =&gt; 'Please enter a correct email',
                        Zend_Validate_Hostname::LOCAL_NAME_NOT_ALLOWED =&gt; 'Please enter a correct email',
                        Zend_Validate_Hostname::UNDECIPHERABLE_TLD =&gt; 'Please enter a correct email',
                        Zend_Validate_Hostname::UNKNOWN_TLD =&gt; 'Please enter a correct email',
                    ),
                ),
            ),
        ),
    )
);
</pre>
<p>Pretty long. Yet still not working. But it is somewhat better &#8211; as no creepy error messages are being displayed &#8211; instead the same message appears multiple times. This is not a validator chain, so the programmer can&#8217;t force the breaking of the chain after the first failed test <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<p>In the end, after few hours of digging through the code and the docs, I came up with my own solution, which still harnesses the power of the original <a href="http://framework.zend.com/apidoc/core/Zend_Validate/Zend_Validate_EmailAddress.html" class="outgoing" title="Zend_Validate_EmailAddress in ZF API" >Zend_Validate_EmailAddress</a> validator while providing a way to add a simple &#8220;<em>Please enter a correct email</em>&#8221; message. One time <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . It uses the <a href="http://framework.zend.com/apidoc/core/Zend_Validate/Zend_Validate_Callback.html" class="outgoing" title="Zend_Validate_Callback in ZF API">Zend_Validate_Callback</a> class and PHP 5.3 anonymus functions:</p>
<pre class="brush: php; title: ; notranslate">
$email-&gt;setOptions(
    array(
        'label' =&gt; 'Email',
        'required' =&gt; TRUE,
        'filters' =&gt; array(
            'StringTrim',
            'StripTags',
        ),
        'validators' =&gt; array(
            array(
                'Callback',
                true,
                array(
                    'callback' =&gt; function($value) {
                        $validator = new Zend_Validate_EmailAddress(
                            array(
                                'allow' =&gt; Zend_Validate_Hostname::ALLOW_DNS,
                                'domain' =&gt; true,
                                'mx' =&gt; true,
                                'deep' =&gt; true,
                            )
                        );

                        return $validator-&gt;isValid($value);
                    },
                    'messages' =&gt; array(
                        Zend_Validate_Callback::INVALID_VALUE =&gt; 'Please enter a correct email',
                    ),
                ),
            ),
        ),
    )
);
</pre>
<p>It might seem a little far fetched, but it works <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2011/01/07/single-error-message-for-zend_validate_emailaddress/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Zend Framework Certified Engineer</title>
		<link>http://blog.motane.lu/2010/12/16/zend-framework-certified-engineer/</link>
		<comments>http://blog.motane.lu/2010/12/16/zend-framework-certified-engineer/#comments</comments>
		<pubDate>Thu, 16 Dec 2010 12:07:46 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[certifications]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1429</guid>
		<description><![CDATA[This is a post I&#8217;ve been wanting to write for a while but I didn&#8217;t quite get the time to do it. It&#8217;s about me finally taking the ZF certification exam. I wanted to take this certification for over an year and a half, but first I postponed it because I was learning python and [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://blog.motane.lu/wp-content/uploads/2009/05/zend_framework_logo.png" alt="" title="Zend Framework" width="259" height="136" class="alignleft size-full wp-image-689" />This is a post I&#8217;ve been wanting to write for a while but I didn&#8217;t quite get the time to do it. It&#8217;s about me finally taking the ZF certification exam. I wanted to take this certification for over an year and a half, but first I postponed it because I was learning python and working with Django and I didn&#8217;t have the time to actually look over Zend Framework&#8217;s manual and read it. Then I moved to Spain, got caught up with other problems and so on, and so on&#8230;</p>
<p>Thing is that I bought a voucher for this exam about an year ago, and, as most Zend issued vouchers, it only lasts one year. So, few weeks ago I found myself with an already paid non-refundable voucher bound to expire. Since I had nothing to lose, I decided to take my chances and take the exam. And I did <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  <a href="http://www.zend.com/en/store/education/certification/yellow-pages.php#show-ClientCandidateID=ZEND009807" title="View my Zend profile" class="outgoing">Hooray for me</a>!</p>
<h2><span>About the exam</span></h2>
<p>The Zend Framework is much more &#8220;to the point&#8221; than the PHP 5 and it&#8217;s a piece of cake for the seasoned Zend Framework developer. No more &#8220;which comes first: the needle or the haystack?&#8221; questions. Everything is focused on asserting the fact that the candidate has the knowledge required to be productive using ZF. The topics cover a large part of the ZF manual, with focus on commonly used features. This doesn&#8217;t mean that you shouldn&#8217;t pay attention to more &#8220;exotic&#8221; topics like Zend_Memory, Zend_TimeSync or Zend_Wildfire.  Although the test refers to version 1.5 of Zend Framework &#8211; the current version is 1.11 &#8211; there&#8217;s nothing specific to that version and the questions refer to those features that are common throughout all the versions (MVC, coding standards, plugins, validator chains, etc).</p>
<p>PS: don&#8217;t email me asking for the questions to the test! Go study&#8230; </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2010/12/16/zend-framework-certified-engineer/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Constants for table names</title>
		<link>http://blog.motane.lu/2010/06/01/constants-for-table-names/</link>
		<comments>http://blog.motane.lu/2010/06/01/constants-for-table-names/#comments</comments>
		<pubDate>Tue, 01 Jun 2010 20:19:44 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1367</guid>
		<description><![CDATA[While working on a PHP project, I had the following idea: wouldn&#8217;t be better to use constants for table names? I mean, having a file, let&#8217;s say /application/config/tables.php, which would look something like: And afterwards, use this value throughout the application: &#8230;in the associated Zend_Db_Table_Abstract &#8230;in joins: &#8230;in the forms: This makes much more sense [...]]]></description>
			<content:encoded><![CDATA[<p>While working on a PHP project, I had the following idea: wouldn&#8217;t be better to use constants for table names? I mean, having a file, let&#8217;s say <em>/application/config/tables.php</em>, which would look something like:</p>
<pre class="brush: php; title: ; notranslate">
define('TABLE_USERS', 'users');
</pre>
<p>And afterwards, use this value throughout the application:</p>
<p>&#8230;in the associated Zend_Db_Table_Abstract</p>
<pre class="brush: php; title: ; notranslate">
class Users extends Zend_Db_Table_Abstract
{
    protected $_name = TABLE_USERS;
}
</pre>
<p>&#8230;in joins:</p>
<pre class="brush: php; title: ; notranslate">
$this-&gt;select(Zend_Db_Table::SELECT_WITH_FROM_PART)
 -&gt;setIntegrityCheck(false)
 -&gt;join(TABLE_USERS, sprintf('%s.id = %s.user_id', TABLE_USERS, $this-&gt;_name));
</pre>
<p>&#8230;in the forms:</p>
<pre class="brush: php; title: ; notranslate">
$validator = new Zend_Validate_Db_NoRecordExists(
    array(
        'table' =&gt; TABLE_USERS,
        'field' =&gt; 'email',
    )
);
</pre>
<p>This makes much more sense to me, since writing a simple &#8216;users&#8217; string can be interpreted as a &#8220;<a href="http://en.wikipedia.org/wiki/Magic_number_(programming)" title="Magic number article in Wikipedia" class="outgoing">magic number</a>&#8220;&#8230;well&#8230;string and it&#8217;s very hard to maintain, should one want to, let&#8217;s say, prefix some of the tables in the database with their module&#8217;s name. </p>
<p>For example, if there&#8217;s already an &#8220;users&#8221; table in system and, in a new module, there&#8217;s the need for another &#8220;users&#8221; table, it would be less confusing to prefix the old table it&#8217;s called &#8220;old_module_table&#8221; and the call the new one &#8220;new_module_table&#8221;. Encapsulating the table&#8217;s name into a constant makes this really easy. I think I&#8217;ll use this in my next project.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2010/06/01/constants-for-table-names/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Zend Framework and web hosting services</title>
		<link>http://blog.motane.lu/2009/11/24/zend-framework-and-web-hosting-services/</link>
		<comments>http://blog.motane.lu/2009/11/24/zend-framework-and-web-hosting-services/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 19:47:29 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[hosting]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1106</guid>
		<description><![CDATA[Let&#8217;s face it. We can&#8217;t all buy or rent our own servers. It&#8217;s not cost effective. So we turn to hosting companies &#8211; always the popular choice. But when you&#8217;re using an shared hosting service, you can&#8217;t make changes in the server&#8217;s configuration file. You usually get a writeable directory in a location like &#8230;and [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s face it. We can&#8217;t all buy or rent our own servers. It&#8217;s not cost effective. So we turn to hosting companies &#8211; always the popular choice. But when you&#8217;re using an shared hosting service, you can&#8217;t make changes in the server&#8217;s configuration file. You usually get a writeable directory in a location like</p>
<pre class="brush: plain; title: ; notranslate">
/home/{your-username}/public_html/
</pre>
<p>&#8230;and a <a href="http://www.cpanel.net/" title="Cpanel Inc. homepage" class="outgoing">Cpanel account</a> to manage your share of the server, emails, databases and so on. And&#8230;that&#8217;s about it. You can&#8217;t point your webroot to the public directory as taught in Zend Framework&#8217;s manual, all your library files will be exposed to the public and so on. What to do then? The answer is simple: <strong><em>.htaccess</em></strong> and <strong>mod_rewrite</strong>. Usually, hosting companies install <strong><em>mod_rewrite</em></strong> and set <strong><em>AllowOverride</em></strong> to true, so this solution will work in the vast majority of cases.</p>
<p>Upload via FTP or SSH your content into your <strong><em>public_html</em></strong>, <strong><em>wwwroot</em></strong> or <strong><em>www</em></strong> directory (the webroot directory, whatever its name may be). Then add 4 htaccess files, one directly in the web root, one in the public directory and one in all other folders. It should look something like this (without the numbers, of course).</p>
<blockquote>
<pre>
public_html/
     /public
       .htaccess (2)
     /application
        .htaccess (3)
     /library
        .htaccess (3)
    .htaccess (1)
</pre>
</blockquote>
<p>Now, the first htaccess file &#8211; #1 &#8211; should contain the following:</p>
<pre class="brush: plain; title: ; notranslate">
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</pre>
<p>&#8230;this will redirect the traffic from this folder to the public/ sub-folder. The second .htaccess &#8211; the one in the public folder &#8211; should be the .htaccess file shipped with Zend Framework. It usually looks like this:</p>
<pre class="brush: plain; title: ; notranslate">
SetEnv APPLICATION_ENV production 

Options +FollowSymLinks
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 .htaccess files located in all other directories &#8211; #3 &#8211; should simply forbid access to their respective folders, like such:</p>
<pre class="brush: plain; title: ; notranslate">
deny from all
</pre>
<p>Worked for me <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2009/11/24/zend-framework-and-web-hosting-services/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Debugging PHP with FirePHP on Zend Framework</title>
		<link>http://blog.motane.lu/2009/10/01/debugging-php-with-firephp-on-zend-framework/</link>
		<comments>http://blog.motane.lu/2009/10/01/debugging-php-with-firephp-on-zend-framework/#comments</comments>
		<pubDate>Thu, 01 Oct 2009 05:09:15 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1108</guid>
		<description><![CDATA[You know the saying: if debugging means taking the bugs out, then programming means putting them in. Yes. We all have bugs in our code. And since not all of them can be marketed as &#8220;undocumented features&#8221;, from time to time we have to debug our applications. The best debugger for PHP I&#8217;ve used so [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://blog.motane.lu/wp-content/uploads/2009/10/firephp_large.png" alt="firephp" title="Fire PHP" width="158" height="154" class="alignleft size-full wp-image-1118" />You know the saying: if debugging means taking the bugs out, then programming means putting them in. Yes. We all have bugs in our code. And since not all of them can be marketed as &#8220;undocumented features&#8221;, from time to time we have to debug our applications.</p>
<p>The best debugger for PHP I&#8217;ve used so far is Zend&#8217;s. Zend Platform together with Zend Studio constitutes a very good development environment and a great debugging environment. Due to the fact that Zend Studio is a little pricey, I don&#8217;t use it any more, instead I&#8217;m using a highly customised vim. This makes a great development environment, but unfortunately isn&#8217;t not that great when debugging. I know you can use <a href="http://www.apaddedcell.com/easy-php-debugging-ubuntu-using-xdebug-and-vim" title="Easy PHP debugging using Xdebug and vim" class="outgoing">vim with Xdebug</a>, but it&#8217;s quite a chore, and I don&#8217;t like it. Since old school debugging with <strong><em>var_dump()</em></strong> or <strong><em>print_r()</em></strong> is out of the question, I was looking for another way to debug my applications. And I&#8217;ve found just the thing: <a href="http://www.firephp.org/" title="FirePHP - Firebug extension for AJAX development" class="outgoing">FirePHP</a>. It&#8217;s a Firefox extension, just like FireBug &#8211; that can receive debug information from the server. </p>
<p>Since I do most of my <del>bugging</del> programming on Zend Framework, I also need debugging for this platform. I use the OOP based bootstraping method, where you extend your Bootstrap class from Zend_Application_Bootstrap_Bootstrap. And in the .htaccess file of the /public/ directory, I have an envelope with the current state of application (usually on of development/staging/production):</p>
<pre class="brush: plain; title: ; notranslate">
SetEnv APPLICATION_ENV development
</pre>
<p>Normally, I need the debug information only when the application is in the &#8220;development&#8221; state, so I&#8217;m using this method in the Bootstrap class. </p>
<pre class="brush: php; title: ; notranslate">
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
    // Bootstrap other components

    /**
     * inits FirePHP for debugging
     *
     * @return void
     */
    protected function _initFirebugDebugger() {
        if(APPLICATION_ENV == 'development') {
            // don't debug while not in &quot;development&quot;
            $logger = new Zend_Log();
            $writer = new Zend_Log_Writer_Firebug();
            $logger-&gt;addWriter($writer);

            Zend_Registry::set('logger',$logger);
        }
    }
}
</pre>
<p>I also like to have some syntactic sugar when developing, so I&#8217;ve define this function in the Bootstrap.php file. Yes, I know that this might be perceived as a blasphemy by some of the OOP purists out there, but I really don&#8217;t care. If you don&#8217;t want non-OOP &#8220;stains&#8221; on your code, simply create a <strong><em>YourApplication_Utility_Firebug</em></strong> class or whatever with a static <strong><em>debug()</em></strong> method and paste the code in it. </p>
<pre class="brush: php; title: ; notranslate">
/**
 * syntactic sugar for logging errors
 * and debug messages to FireBug
 *
 * @param string $message
 * @param int $label
 * @return void
 */
function fb($message, $label = null) {
    if($label != null) {
    	$message = array($label, $message);
    }

    if(Zend_Registry::isRegistered('logger')) {
    	Zend_Registry::get('logger')-&gt;log($message);
    }
}
</pre>
<p>And now, any time you need to debug something, simply type:</p>
<pre class="brush: php; title: ; notranslate">
fb($variable);
fb($_POST); // and so on
</pre>
<p>And all these variables will be sent to Firefox&#8217;s FirePHP toolbar and you can inspect them from there. For even better results, you can also send debug information from your ErrorController to FirePHP (comes in handy when using Ajax). </p>
<p>PS: I&#8217;ll have a look into <a href="http://firelogger4php.binaryage.com/" title="FireLogger for PHP" class="outgoing">FireLogger for PHP</a>. It also look pretty interesting, although it&#8217;s only in Beta.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2009/10/01/debugging-php-with-firephp-on-zend-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Zend Framework SameAs validator</title>
		<link>http://blog.motane.lu/2009/09/29/zend-framework-sameas-validator/</link>
		<comments>http://blog.motane.lu/2009/09/29/zend-framework-sameas-validator/#comments</comments>
		<pubDate>Tue, 29 Sep 2009 13:13:45 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[validators]]></category>
		<category><![CDATA[zend framework]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=955</guid>
		<description><![CDATA[While working on a Zend Framework project, I&#8217;ve found myself in need of a &#8220;same as&#8221; validator. If you&#8217;re familiar with Zend Framework&#8217;s form system, then you know what a validator is, if not, enhance your knowledge on the topic by reading this page from ZF&#8217;s manual. My validator was supposed to check if the [...]]]></description>
			<content:encoded><![CDATA[<p>While working on a Zend Framework project, I&#8217;ve found myself in need of a &#8220;same as&#8221; validator. If you&#8217;re familiar with Zend Framework&#8217;s form system, then you know what a validator is, if not, enhance your knowledge on the topic by reading <a href="http://framework.zend.com/manual/en/zend.validate.html" title="Zend Framework documentation - Zend Validate" class="outgoing">this page</a> from ZF&#8217;s manual. </p>
<p>My validator was supposed to check if the same value was entered into two password fields, to avoid the user&#8217;s typos in passwords. You know, those annoying &#8220;please re-type your password&#8221; fields. At the time, I couldn&#8217;t find a good validator for this purpose, so I&#8217;ve decided to write my own. The source code is available here: </p>
<pre class="brush: php; title: ; notranslate">
/**
 * Checks if a field has the same value as another,
 * very useful in validating passwords
 *
 * @package Generic Validate
 * @author Tudor Barbu &lt;miau@motane.lu&gt;
 * @copyright MIT
 */

class Generic_Validate_SameAs extends Zend_Validate_Abstract {
    /**
     * Validation failure message key for when the values are not
     * the same
     */
    const NOT_THE_SAME = 'not_the_same';

    /**
     * the external element that we check the value against
     *
     * @var Zend_Form_Element
     */
    protected $_element;

    /**
     * Validation failure message template definitions
     *
     * @var array
     */
    protected $_messageTemplates = array(
        self::NOT_THE_SAME =&gt; 'The two values are not identical',
    );

    /**
     * Can receive a Zend_Form_Element parameter that will be used
     * into the validation process
     *
     * @param Zend_Form_Element
     */
    public function __construct(Zend_Form_Element $element = null) {
        if(null !== $element) {
            $this-&gt;setElement($element);
        }
    }

    /**
     * Set the element
     *
     * @param Zend_Form_Element $element
     * @return void
     */
    public function setElement(Zend_Form_Element $element) {
        $this-&gt;_element = $element;
    }

    /**
     * gets the element
     *
     * @return Zend_Form_Element
     */
    public function getElement() {
        return $this-&gt;_element;
    }

    /**
     * overrides isValid from Zend_Validate_Interface
     *
     * @param string $value
     * @return bool
     */
    public function isValid($value) {
        if(null === $this-&gt;_element) {
            require_once 'Zend/Exception.php';
            throw new Zend_Exception('You must add a Zend_Form_Element to the SameAs validator prior to calling the isValid() method');
        }

        if($value != $this-&gt;_element-&gt;getValue()) {
            $this-&gt;_error(self::NOT_THE_SAME);
            return false;
        }

        return true;
    }
}

// EOF
</pre>
<p>PS: The formatting plugin I&#8217;m using might not display everything correctly <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  Aside from that, It&#8217;s quite easy to use:</p>
<pre class="brush: php; title: ; notranslate">
// create some filters
$stringTrimFilter = new Zend_Filter_StringTrim();
$stripTagsFilter = new Zend_Filter_StripTags();

// other validators
$notEmptyValidator = new Zend_Validate_NotEmpty();
$notEmptyValidator-&gt;setMessage('This field is required');

// create the SameAs validator
$sameAsValidator = new Generic_Validate_SameAs();
$sameAsValidator-&gt;setMessage('The 2 fields do not coincide', Generic_Validate_SameAs::NOT_THE_SAME);

// create the main password field
$password = new Zend_Form_Element_Password('password');
$password-&gt;setOptions(
    array(
        'label'       =&gt; 'Password',
        'required'   =&gt; true,
        'filters'      =&gt; array($stringTrimFilter, $stripTagsFilter),
        'validators' =&gt; array($notEmptyValidator),
    )
);    

// add this field to the SameAs validator
$sameAsValidator-&gt;setElement($password);

// create the new
$validateNewPassword = new Zend_Form_Element_Password('validateNewPassword');
$validateNewPassword-&gt;setOptions(
    array(
        'label'        =&gt; 'Re-type the password',
        'required'   =&gt; true,
        'filters'      =&gt; array($stringTrimFilter, $stripTagsFilter),
        'validators' =&gt; array($notEmptyValidator, $sameAsValidator), // add it as a validator to the second field
    )
);
</pre>
<p>If the value entered in the second field isn&#8217;t the same as the value entered in the first field, the validator will signal an error. Simple as that.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2009/09/29/zend-framework-sameas-validator/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Zend_Db quoteInto() with multiple arguments</title>
		<link>http://blog.motane.lu/2009/05/21/zend_db-quoteinto-with-multiple-arguments/</link>
		<comments>http://blog.motane.lu/2009/05/21/zend_db-quoteinto-with-multiple-arguments/#comments</comments>
		<pubDate>Thu, 21 May 2009 08:19:19 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[zend framework]]></category>
		<category><![CDATA[Zend_Db]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=702</guid>
		<description><![CDATA[Zend Framework has some weird &#8220;features&#8221; so to say, which pop out from time to time and get the programmers really annoyed. The latest thing quoteInto() method of Zend_Db_Adapter_Abstract class. This is supposed to quote input variables prior to entering them into a SQL command to avoid SQL injection attacks. Sounds cool, doesn&#8217;t it? Well&#8230;not [...]]]></description>
			<content:encoded><![CDATA[<p>Zend Framework has some weird &#8220;features&#8221; so to say, which pop out from time to time and get the programmers really annoyed. The latest thing <a href="http://funzro.wordpress.com/2009/05/20/%E2%80%9Ci-take-it-you-haven%E2%80%99t-had-sex-for-a-while%E2%80%9D/" title="quoteInto()" class="outgoing">quoteInto()</a> method of Zend_Db_Adapter_Abstract class. This is supposed to quote input variables prior to entering them into a SQL command to avoid SQL injection attacks. Sounds cool, doesn&#8217;t it? Well&#8230;not quite. Because, because it can only quote one argument. </p>
<p>You can&#8217;t write:</p>
<pre class="brush: php; title: ; notranslate">
// note: I usually extend my models from the Zend_Db_Table_Abstract class
// this code should be executed in a model of a such model
$select = new Zend_Db_Select($this-&gt;_db);
$select-&gt;from($this-&gt;_name);
$select-&gt;where($this-&gt;_db-&gt;quoteInto('(a = ? AND b = ?) OR (c != ?)', $a, $b, $c);
</pre>
<p>&#8230;as this won&#8217;t work. Of course, there&#8217;s a really lame approach, to concatenate the output from multiple quoteInto() calls. Like such:</p>
<pre class="brush: php; title: ; notranslate">
$select-&gt;where(
    $this-&gt;_db-&gt;quoteInto('(a =? AND ', $a) .
    $this-&gt;_db-&gt;quoteInfo('b = &gt;)', $b) .
    $this-&gt;_db-&gt;quoteInfo(' OR ( c != ?)', $c)
);
</pre>
<p>As I said, extremely lame. What&#8217;s to do then. Well, when I&#8217;ve hit this roadblock, I&#8217;ve opted for prepared statements. Of course, they brake the OOP encapsulation of SQL queries but if you don&#8217;t need to alter the query later it&#8217;s okay. So:</p>
<pre class="brush: php; title: ; notranslate">
$stmt = $this-&gt;_db-&gt;prepare( 'SELECT * FROM ' . $this-&gt;_name . ' WHERE (a = ? AND b = ?) OR (c != ?)');
$stmt-&gt;execute(array($a, $b, $c));
</pre>
<p>This also works when you need to write custom sql queries:</p>
<pre class="brush: php; title: ; notranslate">
$stmt = $this-&gt;_db-&gt;prepare('INSERT INTO ' . $this-&gt;_name . ' (first, second) VALUES (?, ?) ON DUPLICATE KEY UPDATE first = first + 1');
$stmt-&gt;execute(array($first, $second));
</pre>
<p>A decent workaround to the quoteInto() problem&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2009/05/21/zend_db-quoteinto-with-multiple-arguments/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

