<?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>PHP Magazine &#187; PHP5</title>
	<atom:link href="http://www.phpmag.ru/category/programming/php5/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.phpmag.ru</link>
	<description>Suum cuique</description>
	<lastBuildDate>Tue, 01 Jun 2010 14:42:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Subversion Gems: Sparse Directories</title>
		<link>http://www.phpmag.ru/2010/06/01/subversion-sparse-directories/</link>
		<comments>http://www.phpmag.ru/2010/06/01/subversion-sparse-directories/#comments</comments>
		<pubDate>Tue, 01 Jun 2010 14:41:20 +0000</pubDate>
		<dc:creator>Victor Farazdagi</dc:creator>
				<category><![CDATA[PHP5]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[svn]]></category>

		<guid isPermaLink="false">http://www.phpmag.ru/?p=1041</guid>
		<description><![CDATA[Recently, I become involved in Zend Framework even more &#8211; this time not only developing using it (which I am doing for some 3 years now), but actually contributing back whenever I can. And I plan to dedicate even more hrs/week to work on this undoubtedly nice, yet complex piece of software. So, lyrics aside [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I become involved in Zend Framework even more &#8211; this time not only developing <em>using</em> it (which I am doing for some 3 years now), but actually <em>contributing</em> back whenever I can. And I plan to dedicate even more hrs/week to work on this undoubtedly nice, yet complex piece of software. </p>
<p>So, lyrics aside &#8211; today I had to learn new Subversion trick (the hard way), so I am writing it down here, in hope that it saves some other hacker time to play PacMan.</p>
<p><strong>Problem</strong>:<br />
I needed to checkout into single working copy all relevant (to me) parts of ZF repository. Not doing separate checkouts for the trunk, then branches, then incubator, but having single checkout of repo which I can keep up to date by simple</p>
<pre name="code" class="bash">
svn up</pre>
<p>directly from the root of working copy.</p>
<p>Now the problematic part: you never ever want to checkout whole ZF repository &#8211; need I mention that it is HUGE? So, what I actually wanted is to checkout the whole repo <em>excluding</em> some paths &#8211; such as lots of previous releases in tags/branches folders.<br />
<span id="more-1041"></span><br />
<strong>Solution</strong>:<br />
That&#8217;s where <a href="http://svnbook.red-bean.com/en/1.5/svn.advanced.sparsedirs.html">Sparse Directories chapter</a> from svn book comes handy.</p>
<p>I will not repeat what&#8217;s written there, as I doubt I can explain it better. Yet I would add couple of notes, that might be a time savers I was talking about:</p>
<p>First, as of Subversion 1.6 you can actually exclude directories <em>explicitly</em> (go on and actually read that chapter, to find out that 1.5 supports what they call implicit exclusion).</p>
<p>And second, if you are tempted to run</p>
<pre name="code" class="bash">
$ svn co http://framework.zend.com/svn/framework/standard zf-standard --depth immediates
</pre>
<p>it is  <strong>probably</strong> a bad idea. </p>
<p>In theory it should work like a charm, in practice on my Ubuntu box it takes for ever to bring those 4 immediate directories located in &#8220;standard&#8221; repo. I checked those directories with <strong>svn info</strong> and they have Depth attribute set (quite correctly) to &#8220;empty&#8221; &#8211; yet it takes a lot of network traffic and time to checkout them (once that&#8217;s done &#8211; <strong>svn up</strong> takes no time at all though). It takes so much time, as to make all this sparse directory magic not worth using. </p>
<p>Fortunately, there&#8217;s a work around: proceed one directory at a time, using &#8220;empty&#8221; as depth:</p>
<pre name="code" class="bash">
$ svn co http://framework.zend.com/svn/framework/standard zf-standard --depth empty
$ cd zf-standard
$ svn co http://framework.zend.com/svn/framework/standard/branches --depth empty
$ svn co http://framework.zend.com/svn/framework/standard/tags --depth empty
$ svn co http://framework.zend.com/svn/framework/standard/trunk --depth infinity
</pre>
<p>As you see, I made sure that <strong>trunk</strong> directory is fetched recursively. That&#8217;s because I work on trunk and need it in full.</p>
<p>Now let&#8217;s fetch some branch that we are interested in, while ignoring (and as such implicitly excluding) those that are too outdated to waste time and traffic on them. </p>
<p>Descend to <strong>zf-standard/branches</strong> directory of your newly created working copy and issue following command:</p>
<pre name="code" class="bash">
$ svn up release-1.10
</pre>
<p>As you don&#8217;t provide any depth specifiers &#8220;infinity&#8221; is assumed, and whole branch is fetched. Once that done, you can use your regular svn up/ci workflow &#8211; directory depth parameter is sticky, so you don&#8217;t have to worry about any directory that you didn&#8217;t fetch. Everything works as in normal checkouts, you just don&#8217;t have some of files (and in our case number of files tends to be 6-7 digit number) from your central repo.</p>
<p>Although I tend to <a href="http://github.com/farazdagi">git</a> more and more lately, subversion can still amaze me (after all these years!) <img src='http://www.phpmag.ru/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmag.ru/2010/06/01/subversion-sparse-directories/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Zend_Uri and spaces/unwise chars in URLs</title>
		<link>http://www.phpmag.ru/2010/01/13/zend_uri-and-unwise-chars-in-urls/</link>
		<comments>http://www.phpmag.ru/2010/01/13/zend_uri-and-unwise-chars-in-urls/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 09:15:06 +0000</pubDate>
		<dc:creator>Victor Farazdagi</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[Zend_Uri]]></category>

		<guid isPermaLink="false">http://www.phpmag.ru/?p=928</guid>
		<description><![CDATA[Usage of Zend_Http_Client is pretty straight-forward: $client = new Zend_Http_Client($uri); $client->request(Zend_Http_Client::HEAD); // HTTP HEAD request However, today, on my Ubuntu box I had real problems as HTTP client constantly ended in segmentation fault (SIGTERM in apache logs). When debugging, I noticed that it does so only if $uri contains so called &#8220;unwise&#8221; characters, such as [...]]]></description>
			<content:encoded><![CDATA[<p>Usage of Zend_Http_Client is pretty straight-forward:</p>
<pre name="code" class="php">
$client = new Zend_Http_Client($uri);
$client->request(Zend_Http_Client::HEAD); // HTTP HEAD request
</pre>
<p>However, today, on my Ubuntu box I had real problems as HTTP client constantly ended in segmentation fault (SIGTERM in apache logs). When debugging, I noticed that it does so only if $uri contains so called &#8220;unwise&#8221; characters, such as spaces, &#8220;{&#8220;, &#8220;}&#8221;, &#8220;^&#8221; etc.</p>
<p>Going deeper, I reviewed the source code of Zend_Http_Client::setUri($uri) method, only to discover that it relies on Zend_Uri::factory($uri), to initialize the URLs. From there it was pretty simple. Zend_Uri is aware of &#8220;unwise&#8221; chars problem and disallows them by default (why exception thrown by Zend_Uri ended in SIGTERM is yet to discover, however). In order to allow such a characters:</p>
<pre name="code" class="php">
Zend_Uri::setConfig(array('allow_unwise' => true));
$client = new Zend_Http_Client($uri); // $uri may contain unwise chars now
</pre>
<p>After issuing above instruction Zend_Uri accepts those unwisely formed URIs. Plus, you have to URL-encode white-spaces (i.e. make sure that white-spaces in query string, or actually in URI part after the host name are replaced with &#8220;%20&#8243; char) to make them acceptable.</p>
<p>Further info available in <a href="http://framework.zend.com/manual/en/zend.uri.html#zend.uri.validation.allowunwise">offical documentation</a>.</p>
<p>Please note, that I still think that having unreliable chars in URI is really bad practice. If you work with some system that already gone far on this path, it&#8217;s nice to have a method to actually consume such a wildly formed URIs. Kudos to Zend_Uri maintainers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmag.ru/2010/01/13/zend_uri-and-unwise-chars-in-urls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Zend Framework via svn:externals</title>
		<link>http://www.phpmag.ru/2009/12/30/zend-framework-via-svnexternals/</link>
		<comments>http://www.phpmag.ru/2009/12/30/zend-framework-via-svnexternals/#comments</comments>
		<pubDate>Tue, 29 Dec 2009 21:41:52 +0000</pubDate>
		<dc:creator>Victor Farazdagi</dc:creator>
				<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[subversion]]></category>

		<guid isPermaLink="false">http://www.phpmag.ru/?p=921</guid>
		<description><![CDATA[I have used ZF in several projects, and think is is quite safe to use svn:externals to attach Zend and ZendX as external dependency. It might not be the good idea for other projects, but when it comes to ZF &#8211; what is in trunk is pretty stable. So, go into folder which stores ZF, [...]]]></description>
			<content:encoded><![CDATA[<p>I have used ZF in several projects, and think is is quite safe to use svn:externals to attach Zend and ZendX as external dependency. It might not be the good idea for other projects, but when it comes to ZF &#8211; what is in trunk is pretty stable.</p>
<p>So, go into folder which stores ZF, and safely remove the library. Then just add ZF as external dependency (which would be updated every time you update the working copy):</p>
<pre name="code" class="bash">
svn pe svn:externals .
</pre>
<p>in and editor opened, enter the dependencies:</p>
<pre name="code" class="bash">
Zend http://framework.zend.com/svn/framework/standard/trunk/library/Zend
ZendX http://framework.zend.com/svn/framework/extras/trunk/library/ZendX
</pre>
<p>finally commit everything and obtain.</p>
<pre name="code" class="bash">
svn ci -m 'ZF set as external dep'
svn up
</pre>
<p>The beauty of this approach &#8211; you always have up to date version of ZF.<br />
The danger of this approach &#8211; you always have up to date version of ZF!</p>
<p>Word of caution:<br />
Sometimes this may break things (when backward-compatibility is broken in ZF trunk), but actually if you have unit tests which check your build before deploying, you are pretty safe &#8211; you spot the problem, you resolve it.</p>
<p>NB: This approach supposes that you tag your releases, so that when new release is coming out, you create a tag, export everything into newly created tag (thus freezing the code), and checkout from tag on production server.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmag.ru/2009/12/30/zend-framework-via-svnexternals/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Zend Framework: Authorize.net CIM proposal</title>
		<link>http://www.phpmag.ru/2009/08/07/zend-framework-authorize-net-cim-proposal/</link>
		<comments>http://www.phpmag.ru/2009/08/07/zend-framework-authorize-net-cim-proposal/#comments</comments>
		<pubDate>Fri, 07 Aug 2009 10:06:28 +0000</pubDate>
		<dc:creator>Victor Farazdagi</dc:creator>
				<category><![CDATA[PHP5]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Zend Framework]]></category>
		<category><![CDATA[ANet CIM]]></category>

		<guid isPermaLink="false">http://www.phpmag.ru/?p=853</guid>
		<description><![CDATA[I have finally completed proposal for Authorize.net CIM API. Hopefully, this API gets included into ZF (in one form or another), as ANet is one of the best services to work with user payment profiles, let alone CC processing. On proposal page you can review use cases, and if you are interested in internals feel [...]]]></description>
			<content:encoded><![CDATA[<p>I have finally completed <a href="http://zendframework.com/wiki/display/ZFPROP/Zend_Service_AuthorizeNet_Cim+-+Victor+Farazdagi">proposal</a> for <a href="http://www.authorize.net/solutions/merchantsolutions/merchantservices/cim/">Authorize.net CIM</a> API. Hopefully, this API gets included into ZF (in one form or another), as ANet is one of the best services to work with user payment profiles, let alone CC processing. On proposal page you can review use cases, and if you are interested in internals feel free to download fully-working component&#8217;s <a href="http://www.phpmag.ru/AuthorizeNet.tar.gz">prototype</a> (it is still a prototype as most probably it would be updated in accordance with peer review on ZF wiki).</p>
<p>Let me know your suggestions on how the component can be improved.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmag.ru/2009/08/07/zend-framework-authorize-net-cim-proposal/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>__toString() must not throw an exception</title>
		<link>http://www.phpmag.ru/2009/08/07/__tostring-must-not-throw-an-exception/</link>
		<comments>http://www.phpmag.ru/2009/08/07/__tostring-must-not-throw-an-exception/#comments</comments>
		<pubDate>Fri, 07 Aug 2009 00:57:47 +0000</pubDate>
		<dc:creator>Victor Farazdagi</dc:creator>
				<category><![CDATA[PHP5]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Magic Methods]]></category>

		<guid isPermaLink="false">http://www.phpmag.ru/?p=846</guid>
		<description><![CDATA[This seems kind of limitation to me, indeed, if you use __toString() magic method for anything other than simple object variables concatenation, your code should be able to throw exceptions. Consider you have an object that generates XML as output, and you decide to provide even nicer interface, so that anyone using it in string [...]]]></description>
			<content:encoded><![CDATA[<p>This seems kind of limitation to me, indeed, if you use __toString() magic method for anything other than simple object variables concatenation, your code should be able to throw exceptions. Consider you have an object that generates XML as output, and you decide to provide even nicer interface, so that anyone using it in string context to get access to that XML. XML generation might not go well, and the obvious way to let the client know about this is to throw an exception. However, this is not possible (most probably due to some internal architecture limitations &#8211; as I honestly see no reason why this ideologically wrong).</p>
<p>One (not quite pretty) way to still provide some feedback from __toString() is using trigger_error:</p>
<pre name="code" class="php">
public function  __toString()
{
    try {
        $output = $this->generateXml();
        return $output;
    } catch(Exception $e) {
        trigger_error($e->getMessage(), E_USER_ERROR);
        return '';
    }
}
</pre>
<p>If you know of a better option, let me know!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmag.ru/2009/08/07/__tostring-must-not-throw-an-exception/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Exploring SPL: Interfaces</title>
		<link>http://www.phpmag.ru/2009/08/05/exploring-spl-interfaces/</link>
		<comments>http://www.phpmag.ru/2009/08/05/exploring-spl-interfaces/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 02:22:30 +0000</pubDate>
		<dc:creator>Victor Farazdagi</dc:creator>
				<category><![CDATA[PHP5]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Interfaces]]></category>
		<category><![CDATA[SPL]]></category>

		<guid isPermaLink="false">http://www.phpmag.ru/?p=752</guid>
		<description><![CDATA[Starting with PHP5 almost any PHP installation contained SPL (Standard PHP Library) extension &#8211; with few exceptions, when hosters intentionally disabled it. With PHP 5.3 out, this extension is considered to be within PHP core, and as such it&#8217;s not possible to disable it anymore. This in fact is a good thing, as SPL really [...]]]></description>
			<content:encoded><![CDATA[<p>Starting with PHP5 almost any PHP installation contained SPL (Standard PHP Library) extension &#8211; with few exceptions, when hosters intentionally disabled it. With PHP 5.3 out, this extension is considered to be within PHP core, and as such it&#8217;s not possible to disable it anymore. This in fact is a good thing, as SPL really deserves to be the core component.</p>
<p>In an attempt to shed some light on and to draw attention to SPL, I plan to post several articles discussing various parts of this extension. I will start with SPL Interfaces so that you can grasp immediately the usefulness of the SPL. </p>
<p>Comprehending SPL interfaces presupposes that you know standard interfaces that come build-in with PHP5. So, I wrote <a href="http://www.phpmag.ru/2009/08/02/php5-predefined-interfaces/">preliminary article</a> discussing them &#8211; I consider it to be a prerequisite for good understanding of the current material.</p>
<p>Covered in this article:</p>
<ul>
<li><a href="#countable">The Countable Interface</a></li>
<li><a href="#outer.iterator">The OuterIterator Interface</a></li>
<li><a href="#seekable">The SeekableIterator Interface</a></li>
<li><a href="#recursive.iterator">The RecursiveIterator Interface</a></li>
<li><a href="#spl.observer.subject">The SplObserver and SplSubject Interfaces</a></li>
</ul>
<p><span id="more-752"></span></p>
<p><a name="countable">&nbsp;</a><br />
<strong>The Countable Interface</strong></p>
<p><a href="http://ru.php.net/manual/en/class.countable.php">Countable</a> interface is quite simple: classes implementing it can be used with the <a href="http://php.net/manual/en/function.count.php">count()</a> function. </p>
<pre name="code" class="php">
Countable   {
    /* Methods */
    abstract public int count ( void )
}
</pre>
<p>As you see, all it takes to comply to interface&#8217;s contract is implementation of single method, namely <i>count()</i>:</p>
<pre name="code" class="php">
/**
 * Dummy "contained" class
 */
class Item {}

/**
 * Dummy "container" class implementing Countable
 */
class Items implements Countable
{
    protected $items = array();

    public function add(Item $item)
    {
        $this->items[] = $item;
        return $this;
    }

    public function count()
    {
        return count($this->items);
    }
}

$items = new Items();
$items->add(new Item())
      ->add(new Item())
      ->add(new Item());
echo count($items);     // outputs 3
// you can use sizeof() as well - since it's an alias for count()
echo sizeof($items);
</pre>
<p><a name="outer.iterator">&nbsp;</a><br />
<strong>The OuterIterator Interface</strong></p>
<p><del datetime="2010-05-29T12:00:16+00:00">I am not sure why php manual&#8217;s <a href="http://php.net/manual/en/spl.interfaces.php">respective section</a> doesn&#8217;t contain explanation of this interface, my wild guess &#8211; doc.team hasn&#8217;t time to fill it (hopefully, yet)</del>. Anyway, here is what OuterIterator is all about: OuterIterator serves as wrapper for another inner iterator (which is generally passed into constructor of implementing class). It is similar to IteratorAggregate, but while the former is extending Traversable, OuterIterator extends Iterator &#8211; so implementing class not only contains accessor method for contained iterator, but could be iterated itself as well <img src='http://www.phpmag.ru/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  I know, how it sounds, no need to panic though &#8211; everything would be clear in a moment. Let&#8217;s first look into synopsis:</p>
<pre name="code" class="php">
OuterIterator extends Iterator {
    /* Methods */
    abstract public Iterator getInnerIterator();

    /* Inherited methods */
    abstract public mixed current( void  )
    abstract public scalar key( void )
    abstract public void next( void )
    abstract public void rewind( void )
    abstract public boolean valid( void )
}
</pre>
<p>So, implementing object must be traversable and contain reference to some inner iterator. There&#8217;s great pre-build <a href="http://ru.php.net/manual/en/class.filteriterator.php">FilterIterator</a>, which is an abstract class, allowing to create filter iterators (iterators that filter out some unwanted values). FilterIterator implements OuterIterator &#8211; you pass the iterator to be filtered, and then you can traverse the FilterIterator for filtered values. Let&#8217;s build our own version of FilterIterator:</p>
<pre name="code" class="php">
class OddsFilter implements OuterIterator
{
    protected $innerIterator;

    public function __construct($it)
    {
        $this->innerIterator = $it;
    }

    /**
     * whether the current element of the iterator is acceptable
     */
    public function accept()
    {
        return (bool)($this->current() % 2); // false on evens, true on odds
    }

    /**
     * OuterIterator Methods
     */
    public function getInnerIterator()
    {
        return $this->innerIterator;
    }

    /**
     * Inherited Methods
     */
    public function current()
    {
        return $this->innerIterator->current();
    }

    public function key()
    {
        return $this->innerIterator->key();
    }

    public function next()
    {
        $this->innerIterator->next();
        $this->fetch();
    }

    public function rewind()
    {
        $this->innerIterator->rewind();
        $this->fetch();
    }

    public function valid()
    {
        return $this->innerIterator->valid();
    }

    /**
     * Move forward until the condition defined in accept() is met
     */
    protected function fetch()
    {
        while($this->innerIterator->valid()) {
            if($this->accept()) {
                return;
            }
            $this->innerIterator->next();
        }
    }
}

$iterator = new ArrayIterator(array(1, 2, 3, 4, 5));
$filteredIterator = new OddsFilter($iterator);
print_r(iterator_to_array($filteredIterator));
</pre>
<p>Time to take a closer look at code. OddsFilter is an iterator that filters out even numbers and returns odd numbers only. It accepts instance of Iterator in its constructor, here we used ArrayIterator (very simple iterator, allowing us to traverse arrays and objects). So, on line 70, we created <b>$iterator</b> variable from sample array, and passed this iterator into OddsFilter. OddsFilter mainly delegates calls to contained/inner iterator with a prominent exception of next() and rewind() methods, they call additional method fetch():</p>
<pre name="code" class="php">
protected function fetch()
{
    while($this->innerIterator->valid()) {
        if($this->accept()) {
            return;
        }
        $this->innerIterator->next();
    }
}
</pre>
<p>Here, again, we eventually call inner iterator&#8217;s next() method, but we might call it several times, untill acceptable value is found.</p>
<p>You might wonder what iterator_to_array() function does, simple &#8211; it copies iterator into array, so that resultant output of our code would be:</p>
<pre name="code" class="php">
Array
(
    [0] => 1
    [2] => 3
    [4] => 5
)
</pre>
<p>Of course, instead of using iterator_to_array(), I could have also traversed <b>$filteredIterator</b> with foreach loop &#8211; after all OddsFilter is an iterator itself.</p>
<p>To sum up, OuterIterator is helpful when we have some input iterator (which serves as inner iterator), that should be somehow manipulated (filtered in our case), and results should also be traversable (which is true, as OuterIterator implements Iterator interface itself). </p>
<p>Please note that extending <a href="http://php.net/manual/en/class.filteriterator.php">FilterIterator</a> class is far superior way of building filters &#8211; all you need is to implement abstract accept() method to get very same results (all traversal logic is done within FilterIterator itself).</p>
<p>Note: Thanks to <a href="http://www.phpmag.ru/2009/08/05/exploring-spl-interfaces/#comment-825">P18X</a> for spotting the bug in original code &#8211; fixed now.</p>
<p><a name="seekable">&nbsp;</a><br />
<strong>The SeekableIterator Interface</strong></p>
<p>This interface is build on <a href="http://www.phpmag.ru/2009/08/02/php5-predefined-interfaces/#iterator">Iterator</a> and adds support for quick navigating (seeking) of a certain positions. Everything is done via seek() method added with this interface:</p>
<pre name="code" class="php">
SeekableIterator extends Iterator {
    /* Methods */
    abstract public void seek( int $position )
    /* Inherited methods */
    abstract public mixed Iterator::current( void )
    abstract public scalar Iterator::key( void )
    abstract public void Iterator::next( void )
    abstract public void Iterator::rewind( void )
    abstract public boolean Iterator::valid( void )
}
</pre>
<p>Within seek() method internal iterator position should be set to requested value, if position not found or applicable <a href="http://www.php.net/manual/en/class.outofboundsexception.php">OutOfBoundsException</a> should be thrown.</p>
<p>Here is sample iterator implementing the SeekableIterator:</p>
<pre name="code" class="php">
class Item
{
    protected $title = null;

    public function __construct($title)
    {
        $this->title = $title;
    }

    public function __toString()
    {
        return $this->title;
    }
}

class Items implements SeekableIterator
{
    /**
     * List of contained items
     * @var array
     */
    protected $items = array();

    /**
     * Current iterator position
     * @var int
     */
    protected $pos = 0;

    public function add(Item $item)
    {
        $this->items[] = $item;
        return $this;
    }

    /**
     * SeekableIterator methods
     */
    public function seek($pos)
    {
        $this->pos = $pos;
        if(!$this->valid()) { // position is not seekable!
            throw new OutOfBoundsException('Item at position ' . $pos . ' not found..');
        }
    }

    /**
     * Iterator methods
     */
    public function current()
    {
        return $this->items[$this->pos];
    }

    public function key()
    {
        return $this->pos;
    }

    public function next()
    {
        $this->pos++;
    }

    public function rewind()
    {
        $this->pos = 0;
    }

    public function valid()
    {
        return isset($this->items[$this->pos]);
    }
}

$items = new Items();
$items->add(new Item('milk'))
      ->add(new Item('butter'))
      ->add(new Item('bread'));

try {
    $items->seek(2);
    printf('%d - %s ', $items->key(), $items->current()); // 2 - bread

    $items->seek(3); // OutOfBoundsException should be thrown
                     // Item at position 3 not found..
} catch (OutOfBoundsException $e) {
    die($e->getMessage());
}
</pre>
<p>As you can see, I based this example on <a href="http://www.phpmag.ru/2009/08/02/php5-predefined-interfaces/#iterator">Iterator&#8217;s example</a> from preliminary article. Indeed, in order to make our iterator more flexible (next() method is cool but locating items in any order other than sequential is impossible), all we have to do is to add seek() method that does the job.</p>
<p><a name="recursive.iterator">&nbsp;</a><br />
<strong>The RecursiveIterator Interface</strong></p>
<p>Before we get into details, let&#8217;s give somewhat formal definition of interface.</p>
<p>RecursiveIterator extends <a href="http://www.phpmag.ru/2009/08/02/php5-predefined-interfaces/#iterator">Iterator</a> interface, so it is an iterator itself. What is special about this iterator is the fact that items it contains can be also traversed i.e. we can create iterators for them. Consider multi-dimensional array: </p>
<pre name="code" class="php">
$numbers = array(
    array(1, 2),
    array(3, 4, 5, array(6, 7)),
    8, 9
);
</pre>
<p>This array has 4 elements in total. Whilst first two are arrays, last two (8, 9) are scalars. Imagine that we wanted to print all numbers in that <b>$numbers</b> array &#8211; obviously the recursive function is the most elegant solution (which allows us to have as much depth as necessary). Here, we can traverse first two elements of the array, as they are arrays themselves, even more &#8211; the second element has not only scalars in it but yet another array to be traversed:</p>
<pre name="code" class="php">
    array(3, 4, 5, array(6, 7))
</pre>
<p>RecursiveIterator interface was designed to solve exactly this kinds of problems. If you have a complex structure with multiple levels of data, this interface helps you to recursively traverse all contained elements. Thus in PHP manual definition of this interface goes as following: </p>
<blockquote><p>Classes implementing RecursiveIterator can be used to iterate over iterators.</p></blockquote>
<p>Indeed, if any contained entry can be traversed (i.e. we can attach iterator to it), RecursiveIterator provides an interface to do so.</p>
<p>Here is the synopsis:</p>
<pre name="code" class="php">
RecursiveIterator extends Iterator {
    // Returns an iterator for the current entry
    public RecursiveIterator getChildren( void )

    // whether an iterator could be created for the current entry
    public bool hasChildren( void ) 

    /* Inherited methods */
    abstract public mixed Iterator::current ( void )
    abstract public scalar Iterator::key ( void )
    abstract public void Iterator::next ( void )
    abstract public void Iterator::rewind ( void )
    abstract public boolean Iterator::valid ( void )
}
</pre>
<p>As you see two new methods has been added. </p>
<p>Please note, these methods apply to the current entry, not the base iterator itself. So, hasChildren() should check whether current entry is an array or object, and as such is traversable, thus allowing to create iterator for it. By the same token, getChildren() returns iterator for the current entry&#8217;s contained items. Somewhat obvious, but when I first read the documentation, it took me some time to figure this out.</p>
<p>In order to iterate over children items, we have to be sure that entry is traversable &#8211; hasChildren() method is exactly for this. Once we know, that current entry is traversable, we should be able to obtain iterator to do so &#8211; getChildren() returns such an iterator (its type must be RecursiveIterator &#8211; what we are dealing with, on all levels of recursion, is always one type of interface).</p>
<p>It&#8217;s time to show you some code! First of all NumberIterator I have written to &#8220;flatten&#8221; arrays, so that despite the dimensions, I can have a list of all elements:</p>
<pre name="code" class="php">
class NumbersIterator implements RecursiveIterator
{
    /**
     * List of numbers. Array may be multi-dimensional.
     * @var array
     */
    public $numbers = array();

    /**
     * Current iterator's position
     * @var int
     */
    protected $pos = 0;

    /**
     * Initiates iterator
     * @param array $numbers
     */
    public function __construct($numbers = array())
    {
        $this->numbers = $numbers;
    }

    /**
     * RecursiveIterator methods
     */

    /**
     * Returns current entry's iterator
     * @return NumbersIterator
     */
    public function getChildren()
    {
        return new NumbersIterator($this->current());
    }

    /**
     * Returns true if iterator could be obtained for the current entry.
     * @return boolean
     */
    public function hasChildren()
    {
        return is_array($this->current());
    }

    /**
     * Iterator methods
     */
    public function current()
    {
        return $this->numbers[$this->pos];
    }

    public function key()
    {
        return $this->pos;
    }

    public function next()
    {
        $this->pos++;
    }

    public function rewind()
    {
        $this->pos = 0;
    }

    public function valid()
    {
        return isset($this->numbers[$this->pos]);
    }
}
</pre>
<p>Now we need a recursive function, which would help us traversing:</p>
<pre name="code" class="php">
function displayNumbers(NumbersIterator $iterator) {
    while($iterator->valid()) {
        if($iterator->hasChildren()) {
            displayNumbers($iterator->getChildren());
        } else {
            echo $iterator->current() . '';
        }
        $iterator->next();
    }
}
</pre>
<p>Finally, let&#8217;s traverse the array I have shown you at the beginning of this section:</p>
<pre name="code" class="php">
$numbers = array(
    array(1, 2),
    array(3, 4, 5, array(6, 7)),
    8, 9
);

$iterator = new NumbersIterator($numbers);
displayNumbers($iterator);
</pre>
<p>Everything should be pretty self-explanatory &#8211; scalars get printed &#8220;as is&#8221;, if current iteratable entry is an array (i.e. hasChildren() returns true), I traverse all its children, by recursively calling displayNumbers().</p>
<p>This section was one of the hardest to explain, so sorry for lengthy code and explanations. If you still feel lost, please, let me know via comments &#8211; I would try to clarify and improve current section.</p>
<p><a name="spl.observer.subject">&nbsp;</a><br />
<strong>The SplObserver and SplSubject Interfaces</strong></p>
<p>I would discuss both interfaces in a single section, as they describe well known <a href="http://en.wikipedia.org/wiki/Observer_pattern">Observer design pattern</a>.</p>
<p><del datetime="2010-05-29T12:00:16+00:00">Again, I am not sure why PHP Manual&#8217;s <a href="http://www.php.net/manual/en/spl.interfaces.php">respective section</a> does not provide any info regarding this interfaces, I believe they are quite important,</del> so here is what they all about:</p>
<p>I would not go into any details regarding observer pattern &#8211; as there better places (<a href="http://www.ibm.com/developerworks/library/os-php-designptrns/">here</a> for eg) that provide explanation and PHP implementations of the pattern. In a nutshell, the pattern allows you to define one-to-many relationship between so called Subject and Observer(s), and once the state of the Subject changes, all bind Observer(s) get notified. If you know Java (read-only is enough), Head First Design Patterns is really mind-friendly intro (I don&#8217;t suggest GoF&#8217;s book, because if you are able to get through it, there&#8217;s 0 possibility you haven&#8217;t tried it yet <img src='http://www.phpmag.ru/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  )</p>
<p>Now, back to interfaces.</p>
<p>SplSubject</p>
<pre name="code" class="php">
SplSubject {
    public void attach(SplObserver $observer);
    public void detach(SplObserver $observer);
    public void notify();
}
</pre>
<p>Interface is pretty simple: you should be able to attach observing objects, detach them, and, once state of the subject is changed, notify observers. Here is sample implementation:</p>
<pre name="code" class="php">
class Subject implements SplSubject
{
    /**
     * List of attached observers
     * @var array
     */
    protected $observers = array();

    protected $title = null;

    /**
     * Update subject's title - observers notified!
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
        $this->notify(); // all observers get notified of change
    }

    public function getTitle()
    {
        return $this->title;
    }

    /**
     * SplSubject methods
     */

    public function attach(SplObserver $observer)
    {
        $this->observers[] = $observer;
    }

    public function detach(SplObserver $observer)
    {
        // I cannot use array_search output in IF block directly,
        // as 0 might be returned (if what I am detaching is the first observer)
        // so I must make sure that $key is not false (taking type into account)
        $key = array_search($observer, $this->observers, true);
        if( !($key === false) ) {
            unset($this->observers[$key]);
        }
    }

    public function notify()
    {
        foreach($this->observers as $observer) {
            $observer->update($this);
        }
    }
}
</pre>
<p>SplObserver is even more simple, all you have to do is to provide update() method:</p>
<pre name="code" class="php">
SplObserver {
    public void update(SplSubject $subject);
}
</pre>
<p>Implementation of simple observer class:</p>
<pre name="code" class="php">
class Observer implements SplObserver
{
    public function update(SplSubject $subject)
    {
        echo 'Subject updated! New title: ' . $subject->getTitle();
    }
}
</pre>
<p>Now, let&#8217;s use our Subject and Observer together:</p>
<pre name="code" class="php">
$subject = new Subject();       // create subject
$observer = new Observer();     // create observer
$subject->attach($observer);    // attach observer
$subject->setTitle('Hi, there!'); // Subject updated! New title: Hi, there!
</pre>
<p>Well, SPL implementation of the observer pattern is not the best I&#8217;ve seen &#8211; since it tightly couples the subject and observer (for example, our observer is aware that subject has getTitle() method). However, for most needs it is good enough.</p>
<p><strong>Conclusion</strong></p>
<p>I hope you enjoyed at least some parts of this article, and hopefully it gives you better understanding of the SPL&#8217;s interfaces. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmag.ru/2009/08/05/exploring-spl-interfaces/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>PHP5: Predefined Interfaces</title>
		<link>http://www.phpmag.ru/2009/08/02/php5-predefined-interfaces/</link>
		<comments>http://www.phpmag.ru/2009/08/02/php5-predefined-interfaces/#comments</comments>
		<pubDate>Sun, 02 Aug 2009 00:38:50 +0000</pubDate>
		<dc:creator>Victor Farazdagi</dc:creator>
				<category><![CDATA[PHP5]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[SPL]]></category>

		<guid isPermaLink="false">http://www.phpmag.ru/?p=794</guid>
		<description><![CDATA[Note: This article serves as preliminary for SPL Interfaces article to be published later on. I wanted to provide good overview of (highly under-used) Standard PHP Library (SPL) starting with interfaces. However, without firstly discussing predefined interfaces, which come bundled with each and every PHP distribution, discussion of SPL-provided ones seemed to be incomplete. To [...]]]></description>
			<content:encoded><![CDATA[<p>Note: This article serves as preliminary for <a href="http://www.phpmag.ru/2009/08/05/exploring-spl-interfaces/">SPL Interfaces article</a> to be published later on. </p>
<p>I wanted to provide good overview of (highly under-used) Standard PHP Library (SPL) starting with interfaces. However, without firstly discussing predefined interfaces, which come bundled with each and every PHP distribution, discussion of SPL-provided ones seemed to be incomplete. </p>
<p>To be covered in this article:</p>
<ul>
<li><a href="#traversable">The Traversable Interface</a></li>
<li><a href="#iterator">The Iterator Interface</a></li>
<li><a href="#iterator.aggregate">The IteratorAggregate Interface</a></li>
<li><a href="#array.access">The ArrayAccess Interface</a></li>
<li><a href="#serializable">The Serializable Interface</a></li>
</ul>
<p><span id="more-794"></span></p>
<p><a name="traversable">&nbsp;</a><br />
<strong>The Traversable Interface</strong></p>
<p>Basically this interface is used to mark that object of the class can be used in <a href="http://ru.php.net/manual/en/control-structures.foreach.php">foreach</a> i.e. it could be traversed. This interface is internal in a sense that you cannot use it directly in your scripts, instead you have to implement either <a href="#iterator">Iterator</a> or <a href="#iterator.aggregate">IteratorAggregate</a> interfaces (which extend the Traversable). Since the interface is not implementable within your PHP classes, it&#8217;s synopsis does not enforce any methods:</p>
<pre name="code" class="php">
Traversable
{}
</pre>
<p><a name="iterator">&nbsp;</a><br />
<strong>The Iterator Interface</strong></p>
<p>Extends the <a href="#traversable">Traversable</a>, this interface can be used to produce objects that can iterate themselves. As a rule of thumb: if your object holds number of some items, and you need to access them individually in foreach, <a href="#iterator">Iterator</a> (or <a href="#iterator.aggregate">IteratorAggregate</a> for that matter) is the good bid. Here is the synopsis:</p>
<pre name="code" class="php">
Iterator extends Traversable {
    /* Methods */
    abstract public mixed current ( void )  // return current element's value
    abstract public scalar key ( void )     // return current element's key
    abstract public void next ( void )      // move internal pointer forward
    abstract public void rewind ( void )    // move to the beginning
    abstract public boolean valid ( void )  // check if current position is valid
}
</pre>
<p>To illustrate, here is sample Iterator implementation and usage:</p>
<pre name="code" class="php">
class Item
{
    protected $title = null;

    public function __construct($title)
    {
        $this->title = $title;
    }

    public function __toString()
    {
        return $this->title;
    }
}

class Items implements Iterator
{
    /**
     * List of contained items
     * @var array
     */
    protected $items = array();

    /**
     * Current iterator position
     * @var int
     */
    protected $pos = 0;

    public function add(Item $item)
    {
        $this->items[] = $item;
        return $this;
    }

    /**
     * Iterator methods
     */
    public function current()
    {
        return $this->items[$this->pos];
    }

    public function key()
    {
        return $this->pos;
    }

    public function next()
    {
        $this->pos++;
    }

    public function rewind()
    {
        $this->pos = 0;
    }

    public function valid()
    {
        return isset($this->items[$this->pos]);
    }
}

$items = new Items();
$items->add(new Item('milk'))
      ->add(new Item('butter'))
      ->add(new Item('bread'));

foreach($items as $key => $item) {
    printf('%d - %s ', $key, $item);
}
// Output:
// 0 - milk
// 1 - butter
// 2 - bread
</pre>
<p>Pretty simple, isn&#8217;t it? Granted, it takes time to get used to, but once you do, you would never look back.</p>
<p><a name="iterator.aggregate">&nbsp;</a><br />
<strong>The IteratorAggregate Interface</strong></p>
<p>PHP5 comes with a lot of predefined iterators (and SPL adds to the list), so you rarely need to write your own. For situations when there&#8217;s already suitable iterator for your object (either pre-build or written by you), there&#8217;s little sense to implement Iterator interface, instead it&#8217;s just enough to implement the IteratorAggregate, which allows you to use external iterators. Here is interface synopsis:</p>
<pre name="code" class="php">
IteratorAggregate extends Traversable {
    /* Methods */
    abstract public Traversable getIterator( void )
}
</pre>
<p>As you see, all you have to do is to provide <i>getIterator()</i> method, which would return suitable instance of iterator to be used for traversal:</p>
<pre name="code" class="php">
class Numbers implements IteratorAggregate
{
    protected $numbers = array(1, 2, 3);

    public function getIterator()
    {
        return new ArrayIterator($this->numbers);
    }
}

$nums = new Numbers();
foreach($nums as $k=>$v) {
    printf('%d - %d ', $k, $v);
}

// Output:
//0 - 1
//1 - 2
//2 - 3
</pre>
<p>I used predefined <a href="http://ru.php.net/manual/en/class.arrayiterator.php">ArrayIterator</a> iterator, which allows to traverse arrays and objects. You can use your own iterator as well (the only requirement is that it implements on <a href="#traversable">Traversable</a>).</p>
<p><a name="array.access">&nbsp;</a><br />
<strong>The ArrayAccess Interface</strong></p>
<p>One of the coolest interfaces that come with PHP5, ArrayAccess allows you to interact with your objects as if they were arrays. If you are familiar with C++, it&#8217;s like overloading [] operator (well, almost). Anyway, here is interface synopsis:</p>
<pre name="code" class="php">
ArrayAccess {
    // whether an offset exists
    abstract public boolean offsetExists( mixed $offset )
    // returns the value at specified offset
    abstract public mixed offsetGet( mixed $offset )
    // assigns a value to the specified offset
    abstract public void offsetSet( mixed $offset , mixed $value )
    // unsets an offset
    abstract public void offsetUnset( mixed $offset )
}
</pre>
<p>Don&#8217;t worry if interface doesn&#8217;t seem simple at first, everything would clear up once you review the example:</p>
<pre name="code" class="php">
class Config implements ArrayAccess
{
    protected $options = array(
        'username' => 'torio',
        'uri'      => 'http://www.phpmag.ru/'
    );

    /**
     * ArrayAccess implementation
     */
    public function offsetExists($offset)
    {
        return isset($this->options[$offset]);
    }

    public function offsetGet($offset )
    {
        return $this->options[$offset];
    }

    public function offsetSet($offset, $value )
    {
        $this->options[$offset] = $value;
    }

    public function offsetUnset($offset )
    {
        unset($this->options[$offset]);
    }
}

$config = new Config();
if(isset($config['uri'])) { // offsetExists() is called internally
    printf('URI: %s ', $config['uri']);   // offsetGet()
}
$config['username'] = 'vic';                    // offsetSet()
printf('Username: %s', $config['username']);

unset($config['uri']);                          // offsetUnset()
if(!isset($config['uri'])) {
    echo 'Offset deleted..';
}

// Output:
// URI: http://www.phpmag.ru/
// Username: vic
// Offset deleted..
</pre>
<p>Note: As of PHP 5.3 it is possible to return the value at a given offset by reference.</p>
<p><a name="serializable">&nbsp;</a><br />
<strong>The Serializable Interface</strong></p>
<p>This is the last of predefined interfaces, and is actually quite a simple one (if you are familiar with data serialization). If you want your object to control its serialization/unserialization process you can either use magic methods <a href="http://ru.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.sleep">__sleep()</a>/<a href="http://ru.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.sleep">__wakeup()</a> or, more explicitly, just to implement the <a href="http://ru.php.net/manual/en/class.serializable.php">Serializable</a> interface:</p>
<pre name="code" class="php">
Serializable {
    /* Methods */
    abstract public string serialize( void )
    abstract public mixed unserialize( string $serialized )
}
</pre>
<p>Here is trivial example:</p>
<pre name="code" class="php">
class Item implements Serializable
{
    protected $title = null;

    public function __construct($title)
    {
        $this->title = $title;
    }

    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Serializable implementation
     */
    public function serialize()
    {
        return serialize(array($this->title));
    }

    public function unserialize($serialized )
    {
        list($title) = unserialize($serialized);
        // this method is invoked as constructor, if you need to use
        // default constructor, invoke it manually:
        $this->__construct($title);
    }

}

$serialized = serialize(new Item('milk'));
$obj = unserialize($serialized);
printf('Title: %s ', $obj->getTitle()); // Title: milk
</pre>
<p>That&#8217;s about it! If you liked the article, consider <a href="http://feeds2.feedburner.com/php-addicted">subscribing to RSS</a>, so that you can follow up the incoming SPL tutorials.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmag.ru/2009/08/02/php5-predefined-interfaces/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Zend Framework: dynamically change view script</title>
		<link>http://www.phpmag.ru/2009/07/31/zend-framework-dynamically-change-view-script/</link>
		<comments>http://www.phpmag.ru/2009/07/31/zend-framework-dynamically-change-view-script/#comments</comments>
		<pubDate>Fri, 31 Jul 2009 13:55:47 +0000</pubDate>
		<dc:creator>Victor Farazdagi</dc:creator>
				<category><![CDATA[Zend Framework]]></category>

		<guid isPermaLink="false">http://www.phpmag.ru/?p=731</guid>
		<description><![CDATA[Rendering view script for particular controller action is really easy. Indeed, thanks to (enabled by default) ViewRenderer helper, scripts are auto-loaded: renderer searches script directory(ies) for a view script called CONTROLLER_NAME/ACTION_NAME.SCRIPT_EXTENSION once found, view is auto-rendered. However, sometimes it&#8217;s not what you want, instead you need to render some other view depending on some internal [...]]]></description>
			<content:encoded><![CDATA[<p>Rendering view script for particular controller action is really easy. Indeed, thanks to (enabled by default) ViewRenderer helper, scripts are auto-loaded: renderer searches script directory(ies) for a view script called <code>CONTROLLER_NAME/ACTION_NAME.SCRIPT_EXTENSION</code> once found, view is auto-rendered. </p>
<p>However, sometimes it&#8217;s not what you want, instead you need to render some other view depending on some internal criteria. For example, you may want to render some custom error displaying view. So, if we are positive on what we want, let me show you how to do it:</p>
<pre name="code" class="php">
class TestController extends Zend_Controller_Action
{
    /**
     * test/index.phtml would be rendered by default
     * @return void
     */
    public function indexAction()
    {
        // render test/foo.phtml
        $this->_helper->viewRenderer('foo');

        // render bar/foo.phtml to the default response segment, without using a
        // controller view script subdirectory ("test" in this case):
        // so you may use scripts from other controllers
        $this->_helper->viewRenderer('bar/foo', null, true);

        // now render the script, as previous calls do not render anything,
        // they are just used so that default script is swapped and not rendered:
        $this->render('foo');
        // OR
        $this->render('bar/foo', null, true);
    }
}
</pre>
<p>Please, note that you do not need to provide view extension (foo but not foo.phtml or any extension you happen to use for your views) &#8211; what renderer expects is action name, and we simply swapping the current action. Internally, direct() method is called when you update view renderer, which in turn is proxy for setRender():</p>
<pre name="code" class="php">
// allows you to set any of scriptAction, responseSegment,
// and noController in one pass.
setRender($action = null, $name = null, $noController = false)
</pre>
<p>So, you may use </p>
<pre name="code" class="php">
$this->_helper->viewRenderer->setRender('foo');
</pre>
<p>to change current view, but this form is less common, as it requires more typing <img src='http://www.phpmag.ru/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
NB: If you need more info on ViewRenderer there&#8217;s no better place but <a href="http://framework.zend.com/manual/en/zend.controller.actionhelpers.html">ZF Manual</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmag.ru/2009/07/31/zend-framework-dynamically-change-view-script/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NetBeans + PHP: type hinting</title>
		<link>http://www.phpmag.ru/2009/07/15/netbeans-php-type-hinting/</link>
		<comments>http://www.phpmag.ru/2009/07/15/netbeans-php-type-hinting/#comments</comments>
		<pubDate>Wed, 15 Jul 2009 20:42:21 +0000</pubDate>
		<dc:creator>Victor Farazdagi</dc:creator>
				<category><![CDATA[PHP5]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[NetBeans]]></category>

		<guid isPermaLink="false">http://www.phpmag.ru/?p=676</guid>
		<description><![CDATA[Sometimes, especially when dealing with variations of factory pattern, single method (namely factory()) can return objects of different types, so NetBeans is unable to guess the exact type of returned instance and as such cannot auto-complete. Indeed, you can setup return type using phpDoc syntax: /** * @return Some_Base_Abstract_Class_Name */ public function factory($adapter) but that [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes, especially when dealing with variations of factory pattern, single method (namely <em>factory()</em>) can return objects of different types, so NetBeans is unable to guess the exact type of returned instance and as such cannot auto-complete. Indeed, you can setup return type using phpDoc syntax:</p>
<pre name="code" class="php">
/**
 * @return Some_Base_Abstract_Class_Name
 */
public function factory($adapter)
</pre>
<p>but that doesn&#8217;t work if returned objects are specifications of more general abstract class (exactly the case with factory).</p>
<p>As it turned out, you can easily resolve this issue &#8211; just document your variable with @var, before calling factory() method:</p>
<pre name="code" class="php">
/**
 * @var Some_Specific_Class $foo
 */
$foo = Magic::factory('adapterName');
$foo-> // and NetBeans opens pop-up list with available attributes and methods
</pre>
<p>The good news, you can use this method in any scope &#8211; it just works <img src='http://www.phpmag.ru/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  I love NetBeans!!</p>
<p><strong>UPD:</strong> Well, actually NetBeans seems to be picky of scope &#8211; as reported by others (and confirmed by myself).</p>
<p><strong>UPD1:</strong> Actually NetBeans handles this quite well, just use vdoc (review <a href="http://blogs.sun.com/netbeansphp/entry/defining_a_variable_type_in">this</a> and <a href="http://blogs.sun.com/netbeansphp/entry/defining_variable_type_in_a">this</a> for details)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmag.ru/2009/07/15/netbeans-php-type-hinting/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>WordPress plugin dev + jQuery</title>
		<link>http://www.phpmag.ru/2009/06/21/wordpress-plugin-dev-jquery/</link>
		<comments>http://www.phpmag.ru/2009/06/21/wordpress-plugin-dev-jquery/#comments</comments>
		<pubDate>Sun, 21 Jun 2009 03:35:50 +0000</pubDate>
		<dc:creator>Victor Farazdagi</dc:creator>
				<category><![CDATA[UMapper DevTimes]]></category>
		<category><![CDATA[WP-plugins]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[notes]]></category>

		<guid isPermaLink="false">http://www.phpmag.ru/?p=628</guid>
		<description><![CDATA[Today, when working on UMapper plugin, I tried to use jQuery &#8211; and failed. Although jQuery is now in WP core, $ shortcut wasn&#8217;t working. As it turned out, WP team (quite rightly!) used JQuery.noConflict &#8211; which helps avoiding naming conflict with similar libraries, such as prototype. So, we cannot use $ shortcut function, which [...]]]></description>
			<content:encoded><![CDATA[<p>Today, when working on <a href="http://wordpress.org/extend/plugins/umapper/">UMapper plugin</a>, I tried to use jQuery &#8211; and failed. Although jQuery is now in WP core, <em><strong>$</strong></em> shortcut wasn&#8217;t working. As it turned out, WP team (quite rightly!) used <a title="More information about this function" href="http://docs.jquery.com/Core/jQuery.noConflict">JQuery.noConflict</a> &#8211; which helps avoiding naming conflict with similar libraries, such as prototype. So, we cannot use $ shortcut function, which is quite annoying. In order to overcome this limitation the following construct can be used:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">jQuery<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>$<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// inside this block you can use $ shortcut !!</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Just a small note to myself <img src='http://www.phpmag.ru/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.phpmag.ru/2009/06/21/wordpress-plugin-dev-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
