<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0">
  <channel>
    <title><![CDATA[ZFSnippets]]></title>
    <link>http://feeds2.feedburner.com/Zfsnippets</link>
    <description><![CDATA[Zend Framework Code Snippets]]></description>
    <pubDate>Wed, 11 Nov 2009 06:43:28 +0000</pubDate>
    <managingEditor>admin@zfsnippets.com (zfsnippets)</managingEditor>
    <generator>Zend Framework Zend_Feed</generator>
    <language>en</language>
    <docs>http://blogs.law.harvard.edu/tech/rss</docs>
    <ttl>180</ttl>
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/Zfsnippets" type="application/rss+xml" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
      <title><![CDATA[Twitter log writer]]></title>
      <link>http://zfsnippets.com/snippets/view/id/71</link>
      <guid>http://zfsnippets.com/snippets/view/id/71</guid>
      <description><![CDATA[<p>This log writer allows you to push the messages to a Twitter user. This user updates his timeline with the message.<br />
<br />
Support for Zend_Log_Formatter_Simple is available. It is recommended to log only some types (filter them with Zend_Log_Filter) because connecting to Twitter for every simple (stupid) message is a waste of resources.<br />
<br />
More information at my Google code project: http://code.google.com/p/sozfo</p><pre><code>&lt;?php
class Sozfo_Log_Writer_Twitter extends Zend_Log_Writer_Abstract
{
    protected $_username;
    protected $_password;
    protected $_twitter;

    public function __construct ($username, $password)
    {
        $this-&gt;_username = $username;
        $this-&gt;_password = $password;

        $this-&gt;_formatter = new Zend_Log_Formatter_Simple();
    }

    protected function _getTwitter ()
    {
        if (null === $this-&gt;_twitter) {
            $this-&gt;_twitter = new Zend_Service_Twitter($this-&gt;_username, $this-&gt;_password);
            $response = $this-&gt;_twitter-&gt;account-&gt;verifyCredentials();
            if ($response-&gt;isError()) {
                throw new Zend_Log_Exception('Provided credentials for Twitter log writer are wrong');
            }
        }
        return $this-&gt;_twitter;
    }

    public function _write ($event)
    {
        $line = $this-&gt;_formatter-&gt;format($event);
        $this-&gt;_getTwitter()-&gt;status-&gt;update($line);
    }
}</code></pre>]]></description>
      <pubDate>Sun, 25 Oct 2009 19:32:41 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Zend_Db_Table_Row datatype conversion support]]></title>
      <link>http://zfsnippets.com/snippets/view/id/70</link>
      <guid>http://zfsnippets.com/snippets/view/id/70</guid>
      <description><![CDATA[<p>As we know, all DB adapters return all data as strings, so this small extension gets datatype from table description and converts necessary fields to php datatypes like int, bool or float. Enjoy!</p><pre><code>&lt;?php
class Model_Row_Abstract extends Zend_Db_Table_Row {
	
	protected $_dataTypes = array(
		'bit' =&gt; 'int',
		'tinyint' =&gt; 'int',
		'bool' =&gt; 'bool',
		'boolean' =&gt; 'bool',
		'smallint' =&gt; 'int',
		'mediumint' =&gt; 'int',
		'int' =&gt; 'int',
		'integer' =&gt; 'int',
		'bigint' =&gt; 'float',
		'serial' =&gt; 'int',
		'float' =&gt; 'float',
		'real' =&gt; 'float',
		'numeric' =&gt; 'float',
		'money' =&gt; 'float',
		'double' =&gt; 'float',
		'double precision' =&gt; 'float',
		'decimal' =&gt; 'float',
		'dec' =&gt; 'float',
		'fixed' =&gt; 'float',
		'year' =&gt; 'int'
	);
	
	/**
	 * Initialize object
	 *
	 * Called from {@link __construct()} as final step of object instantiation.
	 *
	 * @return void
	 */
	public function init() {
		$table = $this-&gt;getTable();
		if ($table) {
			$cols = $table-&gt;info(Zend_Db_Table_Abstract::METADATA);
			foreach ($cols as $name =&gt; $col) {
				$dataType = strtolower($col['DATA_TYPE']);
				if (array_key_exists($dataType, $this-&gt;_dataTypes)) {
					settype($this-&gt;_data[$name], $this-&gt;_dataTypes[$dataType]);
				}
			}
		}
	}
}
?&gt;</code></pre>]]></description>
      <pubDate>Tue, 20 Oct 2009 13:04:12 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Advanced Zend_Application_Resource_Frontcontroller]]></title>
      <link>http://zfsnippets.com/snippets/view/id/69</link>
      <guid>http://zfsnippets.com/snippets/view/id/69</guid>
      <description><![CDATA[<p>With this is FrontController Resource you can set order of plugin loading, and can call FrontController plugins with additional params.</p><pre><code>&lt;?php
/**
 * Front Controller Application Resources
 *
 * You can use this is resource in your application.ini
 * &lt;code&gt;
 * ; set classname (0 is order for loader)
 * resources.frontController.plugins.0.classname = &quot;Core_Controller_Plugin_Acl&quot;
 * ; set some options
 * resources.frontController.plugins.0.options.denied.controller = error
 * resources.frontController.plugins.0.options.denied.action = denied
 * resources.frontController.plugins.0.options.role = guest
 * &lt;/code&gt;
 *
 * @category   Core
 * @package    Core_Application
 * @subpackage Resource
 * 
 * @version  $Id: Frontcontroller.php 1560 2009-10-16 13:22:35Z dark $
 */
class Core_Application_Resource_Frontcontroller 
    extends Zend_Application_Resource_ResourceAbstract
{
    /**
     * @var Zend_Controller_Front
     */
    protected $_front;

    /**
     * Initialize Front Controller
     * 
     * @return Zend_Controller_Front
     */
    public function init()
    {
        $front = $this-&gt;getFrontController();
        
        foreach ($this-&gt;getOptions() as $key =&gt; $value) {
            switch (strtolower($key)) {
                case 'controllerdirectory':
                    if (is_string($value)) {
                        $front-&gt;setControllerDirectory($value);
                    } elseif (is_array($value)) {
                        foreach ($value as $module =&gt; $directory) {
                            $front-&gt;addControllerDirectory($directory, 
                                                           $module);
                        }
                    }
                    break;
                    
                case 'modulecontrollerdirectoryname':
                    $front-&gt;setModuleControllerDirectoryName($value);
                    break;
                    
                case 'moduledirectory':
                    $front-&gt;addModuleDirectory($value);
                    break;
                    
                case 'defaultcontrollername':
                    $front-&gt;setDefaultControllerName($value);
                    break;
                    
                case 'defaultaction':
                    $front-&gt;setDefaultAction($value);
                    break;
                    
                case 'defaultmodule':
                    $front-&gt;setDefaultModule($value);
                    break;
                    
                case 'baseurl':
                    $front-&gt;setBaseUrl($value);
                    break;
                    
                case 'params':
                    $front-&gt;setParams($value);
                    break;
                    
                case 'plugins':
                    ksort($value);
                    foreach ((array) $value as $index =&gt; $pluginClass) {
                        if (is_array($pluginClass)) {
                            if (!isset($pluginClass['options'])) {
                                $pluginClass['options'] = array();
                            }
                            $plugin = new $pluginClass['classname']($pluginClass['options']);
                        } else {
                            $plugin = new $pluginClass();
                        }
                        $front-&gt;registerPlugin($plugin, $index);
                    }
                    break;

                case 'throwexceptions':
                    $front-&gt;throwExceptions((bool) $value);
                    break;

                case 'actionhelperpaths':
                    if (is_array($value)) {
                        foreach ($value as $helperPrefix =&gt; $helperPath) {
                            Zend_Controller_Action_HelperBroker::addPath($helperPath, $helperPrefix);
                        }
                    }
                    break;

                default:
                    $front-&gt;setParam($key, $value);
                    break;
            }
        }

        if (null !== ($bootstrap = $this-&gt;getBootstrap())) {
            $this-&gt;getBootstrap()-&gt;frontController = $front;
        }

        return $front;
    }

    /**
     * Retrieve front controller instance
     * 
     * @return Zend_Controller_Front
     */
    public function getFrontController()
    {
        if (null === $this-&gt;_front) {
            $this-&gt;_front = Zend_Controller_Front::getInstance();
        }
        return $this-&gt;_front;
    }
}
</code></pre>]]></description>
      <pubDate>Fri, 16 Oct 2009 14:53:25 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Generate MySQL DB Backup using config object]]></title>
      <link>http://zfsnippets.com/snippets/view/id/68</link>
      <guid>http://zfsnippets.com/snippets/view/id/68</guid>
      <description><![CDATA[<p>You have the database name, username and password in the config file, don't you? <br />
<br />
Use the information to generate a MySQL dump file. </p><pre><code>$config = Zend_Registry::get('config');
        $dbUsername = $config-&gt;database-&gt;params-&gt;username;
        $dbPassword = $config-&gt;database-&gt;params-&gt;password;
        $dbName = $config-&gt;database-&gt;params-&gt;dbname;
        $file = APPLICATION_PATH . '/data/backup/' . time() . '.sql';
        $command = sprintf(&quot;
            mysqldump -u %s --password=%s -d %s --skip-no-data &gt; %s&quot;,
            escapeshellcmd($dbUsername),
            escapeshellcmd($dbPassword),
            escapeshellcmd($dbName),
            escapeshellcmd($file)
        );
        exec($command);
</code></pre>]]></description>
      <pubDate>Tue, 29 Sep 2009 19:11:59 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[NotModified Cache Controller Plugin]]></title>
      <link>http://zfsnippets.com/snippets/view/id/67</link>
      <guid>http://zfsnippets.com/snippets/view/id/67</guid>
      <description><![CDATA[<p>NotModified Cache Controller Plugin for better clients browser and server bandwidth usage.</p><pre><code>&lt;?php
/**
 * NotModifiedCache.php
 *
 * @category   BaseZF_Framework
 * @package    BaseZF
 * @copyright  Copyright (c) 2008 BaseZF
 * @author     Harold Thetiot (hthetiot)
 */

class BaseZF_Framework_Controller_Plugin_NotModifiedCache extends Zend_Controller_Plugin_Abstract
{
    /**
     * Defined by Zend_Controller_Plugin_Abstract
     */
    public function dispatchLoopShutdown()
    {
        $response = $this-&gt;getResponse();

        // no cache if error found or if response
        // is not a Zend_Controller_Response_Http instance
        if (!($response instanceOf Zend_Controller_Response_Http) || $response-&gt;isException()) {
            return;
        }

        // Generate unique Hash-ID by using MD5
        $hashID = md5($response-&gt;getBody());

        // Specify the time when the page has
        // been changed. For example this date
        // can come from the database or any
        // file. Here we define a fixed date value:
        $lastChangeTime = 1144055759;

        // Define the proxy or cache expire time
        $expireTime = 3600; // seconds (= one hour)

        // Get request headers:
        $headers = apache_request_headers();
        // you could also use getallheaders() or $_SERVER
        // or HTTP_SERVER_VARS

        // Set cache/proxy informations:
        $response-&gt;setHeader('Cache-Control', 'max-age=' . $expireTime); // must-revalidate
        $response-&gt;setHeader('Expires', gmdate('D, d M Y H:i:s', time() + $expireTime) . ' GMT');

        // Set last modified (this helps search engines
        // and other web tools to determine if a page has
        // been updated)
        $response-&gt;setHeader('Last-Modified', gmdate('D, d M Y H:i:s', $lastChangeTime) . ' GMT');

        // Send a &quot;ETag&quot; which represents the content
        // (this helps browsers to determine if the page
        // has been changed or if it can be loaded from
        // the cache - this will speed up the page loading)
        $response-&gt;setHeader('ETag', $hashID);

        // The browser &quot;asks&quot; us if the requested page has
        // been changed and sends the last modified date he
        // has in it's internal cache. So now we can check
        // if the submitted time equals our internal time value.
        // If yes then the page did not get updated
        $PageWasUpdated = !(isset($headers['If-Modified-Since']) &amp;&amp; strtotime($headers['If-Modified-Since']) == $lastChangeTime);

        // The second possibility is that the browser sends us
        // the last Hash-ID he has. If he does we can determine
        // if he has the latest version by comparing both IDs.
        // Warning: If-None-Match header can have a value like &quot;hash0, hash1&quot;
        $DoIDsMatch = (isset($headers['If-None-Match']) &amp;&amp; strpos($headers['If-None-Match'], $hashID) !== false);

        // Does one of the two ways apply?
        if (!$PageWasUpdated or $DoIDsMatch){

            // Okay, the browser already has the
            // latest version of our page in his
            // cache. So just tell him that
            // the page was not modified and DON'T
            // send the content -&gt; this saves bandwith and
            // speeds up the loading for the visitor
            $response-&gt;setHttpResponseCode(304);

            // That's all, now close the connection:
            $response-&gt;setHeader('Connection', 'close');

            // The magical part:
            // No content here ;-)
            $front = Zend_Controller_Front::getInstance();
            $front-&gt;returnResponse(false);

            // Just the headers
            $response-&gt;sendHeaders();

        } else {

            // Okay, the browser does not have the
            // latest version or does not have any
            // version cached. So we have to send him
            // the full page.
            $response-&gt;setHttpResponseCode(200);

            // Tell the browser which size the content
            $response-&gt;setHeader('Content-Length', mb_strlen($response));
        }
    }
}
</code></pre>]]></description>
      <pubDate>Wed, 26 Aug 2009 10:30:38 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Paginator_Adapter_DoctrineQuery]]></title>
      <link>http://zfsnippets.com/snippets/view/id/66</link>
      <guid>http://zfsnippets.com/snippets/view/id/66</guid>
      <description><![CDATA[<p>Usage:<br />
<br />
$q = Doctrine_Query::create()<br />
            -&gt;from('Movie m');<br />
<br />
$paginator = new Zend_Paginator(new Smapp_Paginator_Adapter_DoctrineQuery($q));<br />
<br />
And use it as usual Zend paginator:<br />
<br />
$dataset = $paginator-&gt;setItemCountPerPage(48)<br />
                    -&gt;setCurrentPageNumber($this-&gt;_getParam('page', 1));<br />
<br />
$this-&gt;view-&gt;paginator = $paginator;</p><pre><code>&lt;?php
/**
 * SM's code library
 * 
 * 
 * @category    Smapp     
 * @package     Smapp_Paginator
 * @copyright   Copyright (c) 2009 Pavel V Egorov
 * @author      Pavel V Egorov
 * @link        http://epavel.ru/
 * @since       14.08.2009
 */


/**
 * @see Zend_Paginator_Adapter_Interface
 */
require_once 'Zend/Paginator/Adapter/Interface.php';

/**
 * @category    Smapp     
 * @package     Smapp_Paginator
 * @copyright   Copyright (c) 2009 Pavel V Egorov
 * @author      Pavel V Egorov
 * @link        http://epavel.ru/
 * @since       14.08.2009
 */
class Smapp_Paginator_Adapter_DoctrineQuery implements Zend_Paginator_Adapter_Interface
{
    /**
     * Database query
     *
     * @var Doctrine_Query
     */
    protected $_query = null;

    /**
     * Total item count
     *
     * @var integer
     */
    protected $_rowCount = null;

    /**
     * Constructor.
     *
     * @param Doctrine_Query $q The select query
     */
    public function __construct(Doctrine_Query $q)
    {
        $this-&gt;_query = $q;
    }

    /**
     * Sets the total row count
     *
     * @param  Doctrine_Query|integer $totalRowCount Total row count integer
     *                                               or query
     * @return Zend_Paginator_Adapter_DbSelect $this
     * @throws Zend_Paginator_Exception
     */
    public function setRowCount($rowCount)
    {
        if ($rowCount instanceof Doctrine_Query) {
            $this-&gt;_rowCount = $rowCount-&gt;count();
        } else if (is_integer($rowCount)) {
            $this-&gt;_rowCount = $rowCount;
        } else {
            /**
             * @see Zend_Paginator_Exception
             */
            require_once 'Zend/Paginator/Exception.php';

            throw new Zend_Paginator_Exception('Invalid row count');
        }

        return $this;
    }

    /**
     * Returns an array of items for a page.
     *
     * @param  integer $offset Page offset
     * @param  integer $itemCountPerPage Number of items per page
     * @return array
     */
    public function getItems($offset, $itemCountPerPage)
    {
        return $this-&gt;_query-&gt;limit($itemCountPerPage)
                            -&gt;offset($offset)
                            -&gt;execute();
    }

    /**
     * Returns the total number of rows in the result set.
     *
     * @return integer
     */
    public function count()
    {
        if ($this-&gt;_rowCount === null) {
            $this-&gt;setRowCount(
                $this-&gt;_query-&gt;count()
            );
        }
        return $this-&gt;_rowCount;
    }
}
</code></pre>]]></description>
      <pubDate>Fri, 14 Aug 2009 03:51:43 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[simple cache ]]></title>
      <link>http://zfsnippets.com/snippets/view/id/65</link>
      <guid>http://zfsnippets.com/snippets/view/id/65</guid>
      <description><![CDATA[<p>simple exapmle of &quot;non smart&quot; cashing.<br />
work perfectly in not to big sites</p><h3></h3><pre><code>&lt;?php


//bootstrap.php
require 'CacheAll.php';
....
</code></pre><h3></h3><pre><code>&lt;?php
 require 'Zend/Cache.php';
    $frontendOptions = array(
               'lifetime' =&gt; 108000,
               'debug_header' =&gt; false, // for debugging set &quot;true&quot;
               'default_options' =&gt; array(
                            'cache' =&gt; true,
                            'cache_with_get_variables' =&gt; true,
                            'make_id_with_get_variables' =&gt; true,
                            'cache_with_cookie_variables' =&gt; true,
                            'make_id_with_cookie_variables' =&gt; true
              ),
           );
          $backendOptions = array(
                 'cache_dir' =&gt; '/path/to/dir',
                 'hashed_directory_level' =&gt; 1,
                 'file_name_prefix' =&gt; 'npc',
           );
           $c = Zend_Cache::factory('Page', 'File', $frontendOptions, $backendOptions);
           $c -&gt; start();
</code></pre>]]></description>
      <pubDate>Tue, 04 Aug 2009 12:52:29 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Zend_Mail inline picture attachments]]></title>
      <link>http://zfsnippets.com/snippets/view/id/64</link>
      <guid>http://zfsnippets.com/snippets/view/id/64</guid>
      <description><![CDATA[<p>This simple code will load pictures from HTML email and create special attachment, which will force to display pictures in email clients even if they block pictures</p><pre><code>&lt;?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Mail
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */


/**
 * @see Zend_Mail
 */
require_once 'Zend/Mail.php';

/**
 * Class for sending an email.
 *
 * @category   Zend
 * @package    Zend_Mail
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Techi_Mail extends Zend_Mail
{

	/**
     * Sets the HTML body for the message
     *
     * @param  string    $html
     * @param  string    $charset
     * @param  string    $encoding
     * @return Zend_Mail Provides fluent interface
     */
	public function setBodyHtml($html, $charset = null, $encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE, $preload_images = true)
	{
		if ($preload_images)
		{
			$this-&gt;setType(Zend_Mime::MULTIPART_RELATED);

			$dom = new DOMDocument(null, $this-&gt;getCharset());
			@$dom-&gt;loadHTML($html);

			$images = $dom-&gt;getElementsByTagName('img');

			for ($i = 0; $i &lt; $images-&gt;length; $i++)
			{
				$img = $images-&gt;item($i);
				$url = $img-&gt;getAttribute('src');

				$image_http = new Zend_Http_Client($url);
				$response = $image_http-&gt;request();

				if ($response-&gt;getStatus() == 200)
				{
					$image_content = $response-&gt;getBody();

					$pathinfo = pathinfo($url);
					$mime_type = $response-&gt;getHeader('Content-Type');

					$mime = new Zend_Mime_Part($image_content);
					$mime-&gt;id          = $url;
					$mime-&gt;location    = $url;
					$mime-&gt;type        = $mime_type;
					$mime-&gt;disposition = Zend_Mime::DISPOSITION_INLINE;
					$mime-&gt;encoding    = Zend_Mime::ENCODING_BASE64;
					$mime-&gt;filename    = $pathinfo['basename'];

					$this-&gt;addAttachment($mime);
				}
			}
		}

		return parent::setBodyHtml($html, $charset, $encoding);
	}
}
</code></pre>]]></description>
      <pubDate>Sun, 19 Jul 2009 22:35:12 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Zend_Navigation_Page_Mvc  isActive()]]></title>
      <link>http://zfsnippets.com/snippets/view/id/63</link>
      <guid>http://zfsnippets.com/snippets/view/id/63</guid>
      <description><![CDATA[<p>Use this method to let the isActive() method automatically detect if it is active or not.<br />
<br />
Instead of getting the default module / controller / action the vars are coming from a request object.<br />
<br />
This script is calling $router-&gt;route($front-&gt;getRequest()) to get a correct request object. If you don't use the actionStack helper, just call $front-&gt;getRequest();</p><pre><code>&lt;?
class Mhwk_Navigation_Page_Mvc extends Zend_Navigation_Page_Mvc
{
    public function isActive($recursive = false)
    {
        if (!$this-&gt;_active) {
            $front = Zend_Controller_Front::getInstance();
			$router = $front-&gt;getRouter();
			
			$request = $router-&gt;route($front-&gt;getRequest());
            $reqParams = $request-&gt;getParams();

            if (!array_key_exists('module', $reqParams)) {
                $reqParams['module'] = $front-&gt;getDefaultModule();
            }

            $myParams = $this-&gt;_params;
			
			$route = $router-&gt;getRoute($this-&gt;_route);
            $routeDefaults = $route-&gt;getDefaults();

            if (null !== $this-&gt;_module) {
                $myParams['module'] = $this-&gt;_module;
            } else {
                $myParams['module'] = $routeDefaults['module'];
            }

            if (null !== $this-&gt;_controller) {
                $myParams['controller'] = $this-&gt;_controller;
            } else {
                $myParams['controller'] = $routeDefaults['controller'];
            }

            if (null !== $this-&gt;_action) {
                $myParams['action'] = $this-&gt;_action;
            } else {
                $myParams['action'] = $routeDefaults['action'];
            }

            if (count(array_intersect_assoc($reqParams, $myParams)) ==
                count($myParams)) {
                $this-&gt;_active = true;
                return true;
            }
        }

        return parent::isActive($recursive);
    }
}</code></pre>]]></description>
      <pubDate>Tue, 14 Jul 2009 10:27:21 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[AnyMarkup Decorator]]></title>
      <link>http://zfsnippets.com/snippets/view/id/62</link>
      <guid>http://zfsnippets.com/snippets/view/id/62</guid>
      <description><![CDATA[<p>With the AnyMarkup decorator you can place arbitrary markup before or after other output.<br />
<br />
Just put the key 'markup' in the decorator options somewhere and assign it some (valid) markup.<br />
<br />
Use multiple instances of the decorator to wrap your content withy any markup. See http://devzone.zend.com/article/3450-Decorators-with-Zend_Form for a reference on using multiple instances of a decorator.</p><pre><code>&lt;?php
class My_Decorator_AnyMarkup extends Zend_Form_Decorator_Abstract {

    public function render($content) {
        $placement = $this-&gt;getPlacement();
        $separator = $this-&gt;getSeparator();
        switch ($placement) {
            case self::PREPEND:
                return $this-&gt;_options['markup'] . $separator . $content;
            case self::APPEND:
            default:
                return $content . $separator . $this-&gt;_options['markup'];
        }
    }

}
?&gt;</code></pre>]]></description>
      <pubDate>Sun, 28 Jun 2009 20:05:07 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Mailto Obfuscator]]></title>
      <link>http://zfsnippets.com/snippets/view/id/61</link>
      <guid>http://zfsnippets.com/snippets/view/id/61</guid>
      <description><![CDATA[<p>Output filter to obfuscate mailto: links<br />
<br />
Obfuscation method is 'kindly borrowed' from smarty template engine.<br />
Uses javascript as obfuscation method, but has no fallback when javascript is disabled.</p><pre><code>&lt;?php

class Vendor_View_Filter_ObfuscateMailto implements Zend_Filter_Interface
{
	/**
	 * Regex to find mailto links
	 * Note that it only finds the links,
	 * it does not care about the validity of the email-address
	 *
	 * @var string
	 */
	protected $_pattern = '/&lt;a(.*)href=&quot;mailto:([^&quot;]*)&quot;(.*)&gt;(.*)&lt;\/a&gt;/iu';
	
	/**
	 * Defined in Zend_Filter_Interface
	 *
	 * @param	mixed	$value	Value to filter
	 * @return	mixed			Filtered value
	 */
	public function filter($value)
	{
		return preg_replace_callback($this-&gt;_pattern, array($this, '_obfuscate'), $value);
	}
	
	/**
	 * Obfuscates found mailto links to encoded javascript
	 *
	 * @param	array	$matches	Matches from regex
	 * @return	string				Obfuscated mailto link
	 */
	protected function _obfuscate(array $matches)
	{
		// javascript to be executed
		$javascript = &quot;document.write('&quot;. $matches[0] .&quot;')&quot;;
		
		// empty string that will hold encoded version of javascript 
		$encodedJavascript = '';
		
		// encode each character from $javascript to hex and append it to $encodedJavascript
		for($i = 0; $i &lt; strlen($javascript); $i++) {
			$encodedJavascript .= '%' . bin2hex($javascript[$i]);
		}
		
		// return as html script-tag
		return '&lt;script type=&quot;text/javascript&quot;&gt;eval(unescape(\''. $encodedJavascript .'\'))&lt;/script&gt;';
	}
}

</code></pre><h3></h3><pre><code>$view-&gt;addFilterPath('Vendor/View/Filter', 'Vendor_View_Filter');
$view-&gt;addFilter('ObfuscateMailto');</code></pre>]]></description>
      <pubDate>Tue, 16 Jun 2009 09:28:46 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Zend_Queue simple example for offline processing]]></title>
      <link>http://zfsnippets.com/snippets/view/id/60</link>
      <guid>http://zfsnippets.com/snippets/view/id/60</guid>
      <description><![CDATA[<p>This is a little hacky, but a nice way to demonstrate Zend_Queue.<br />
<br />
An application we are developing sometimes had to send a lot of emails on request from the user, sending them was taking too long 'online', so we refactored the class to add the calls to a queue, allowing a scheduled task to send the emails 'offline'.<br />
<br />
This was tested against the latest trunk of Zend Framework and the incubator.</p><h3>Adapted class</h3><pre><code>&lt;?php
/**
 * Zend_Queue offline processing hack example
 *
 * @author      Dave Marshall 
 * @version     $Rev: $
 * @since       $Date: $
 * @link        $URL: $
 */
class EmailSender {

    private static $queue = null;

    /**
     * Set Queue
     *
     * @param Zend_Queue $queue
     */
    public static function setQueue($queue)
    {
        self::$queue = $queue;
    }

    /**
     * Takes an array of addresses and sends an email to each one.
     *
     * @see reallySendEmail
     * @see sendQueuedEmails
     * @param array $address
     */
    public static function sendEmail($address)
    {
        if (self::$queue === null) {
            // just send them now if we don't have a queue instance
            return self::reallySendEmail($address);
        }

        self::$queue-&gt;send(serialize(func_get_args()));
    }

    /**
     * Takes an array of addresses and sends an email to each one.
     *
     * @see sendEmail
     * @param array $address
     */
    private static function reallySendEmail($address)
    {
        /**
         * Code in here
         */
        echo 'Sending email to ' . implode(', ', $address) . PHP_EOL;
    }

    /**
     * Reads emails from the queue and sends them
     *
     * @param int $count - The number of queued items to process
     */
    public static function sendQueuedEmails($count)
    {
        /**
         * Should really check the queue is good here
         */

        $messages = self::$queue-&gt;receive(intval($count));
        foreach($messages as $msg) {
            $args = unserialize($msg-&gt;body);
            call_user_func_array(array(__CLASS__, 'reallySendEmail'), $args);
            self::$queue-&gt;deleteMessage($msg);
        }
    }
}

</code></pre><h3>Usage in application code</h3><pre><code>&lt;?php

set_include_path(
    'path/to/zend/framework' . PATH_SEPARATOR
    . 'path/to/zend/framework/incubator' . PATH_SEPARATOR
    . get_include_path()
);

require_once &quot;Zend/Loader.php&quot;;
Zend_Loader::registerAutoload();

define('DB_SERVER', 'localhost');
define('DB_PORT', 3306);
define('DB_USER', 'root');
define('DB_PASS', 'password');
define('DB_NAME', 'emailsender');
 
$config = array(
    'name' =&gt; 'transmittal',
    'driverOptions' =&gt; array(
        'host'     =&gt; DB_SERVER,
        'port'     =&gt; DB_PORT,
        'username' =&gt; DB_USER,
        'password' =&gt; DB_PASS,
        'dbname'   =&gt; DB_NAME,
        'type'     =&gt; 'pdo_mysql'
    )
);

// Create a database queue
$queue = new Zend_Queue('Db', $config);
$queue-&gt;createQueue('myqueue'); // called for good measure

EmailSender::setQueue($queue);
EmailSender::sendEmail(array('yourname@gmail.com'));

</code></pre><h3>Usage for crontab script</h3><pre><code>&lt;?php

set_include_path(
    'path/to/zend/framework' . PATH_SEPARATOR
    . 'path/to/zend/framework/incubator' . PATH_SEPARATOR
    . get_include_path()
);

require_once &quot;Zend/Loader.php&quot;;
Zend_Loader::registerAutoload();

define('DB_SERVER', 'localhost');
define('DB_PORT', 3306);
define('DB_USER', 'root');
define('DB_PASS', 'password');
define('DB_NAME', 'emailsender');

$config = array(
    'name' =&gt; 'transmittal',
    'driverOptions' =&gt; array(
        'host'     =&gt; DB_SERVER,
        'port'     =&gt; DB_PORT,
        'username' =&gt; DB_USER,
        'password' =&gt; DB_PASS,
        'dbname'   =&gt; DB_NAME,
        'type'     =&gt; 'pdo_mysql'
    )
);

// Create a database queue
$queue = new Zend_Queue('Db', $config);
$queue-&gt;createQueue('myqueue'); // called for good measure

EmailSender::setQueue($queue);
EmailSender::sendQueuedEmails(5);


</code></pre>]]></description>
      <pubDate>Mon, 01 Jun 2009 09:58:00 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[CDN View Helper]]></title>
      <link>http://zfsnippets.com/snippets/view/id/59</link>
      <guid>http://zfsnippets.com/snippets/view/id/59</guid>
      <description><![CDATA[<p>Setup:<br />
<br />
$types = array(<br />
	'images'  =&gt; 'http://me.cachefly.net/images',<br />
	'styles'  =&gt; 'http://static.me.com/st',<br />
	'scripts' =&gt; 'http://s3.amazonaws.com/mescripts',<br />
);<br />
Galahad_View_Helper_Cdn::setTypes($types);<br />
$view-&gt;addHelperPath('Galahad/View/Helper', 'Galahad_View_Helper');<br />
<br />
In View/Layout File:<br />
<br />
&lt;img src=&quot;&lt;?=$this-&gt;cdn('images')?&gt;/myimg.png&quot; /&gt;</p><pre><code>class Galahad_View_Helper_Cdn extends Zend_View_Helper_Abstract 
{
	static $_types = array(
		'default' =&gt; '',
		'images'  =&gt; '/images',
		'styles'  =&gt; '/styles',
		'scripts' =&gt; '/scripts',
	);
	
	static function setTypes($types)
	{
		self::$_types = $types;
	}
	
	public function cdn($type = 'default')
	{
		if (!isset(self::$_types[$type])) {
			throw new Exception('No CDN set for resource type ' . $type);
		}
		
		return self::$_types[$type];
	}
}</code></pre>]]></description>
      <pubDate>Mon, 04 May 2009 00:40:50 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Application_Resource_Paginator]]></title>
      <link>http://zfsnippets.com/snippets/view/id/58</link>
      <guid>http://zfsnippets.com/snippets/view/id/58</guid>
      <description><![CDATA[<p>Allows you to configure the Paginator globally. This is helpful if you use a standard view partial for all pagination.</p><pre><code>class Core_Application_Resource_Paginator extends Zend_Application_Resource_ResourceAbstract
{
    /**
     * Set the default scrolling style for the Paginator
     *
     * @param  string $scrollingStyle
     * @return Core_Application_Resource_Paginator
     */
    public function setDefaultScrollingStyle($scrollingStyle)
    {
        Zend_Paginator::setDefaultScrollingStyle($scrollingStyle);
        return $this;
    }

    /**
     * Set the default view partial for the Paginator
     *
     * @param  string|array $viewPartial
     * @return Core_Application_Resource_Paginator
     */
    public function setDefaultViewPartial($viewPartial)
    {
        Zend_View_Helper_PaginationControl::setDefaultViewPartial($viewPartial);
        return $this;
    }

    /**
     * Defined by Zend_Application_Resource_Resource
     *
     * @return void
     */
    public function init()
    {
    }
}

</code></pre><h3></h3><pre><code>
// Pass to Zend_Application like so:
resources.paginator.defaultScrollingStyle = &quot;Sliding&quot;
resources.paginator.defaultViewPartial = &quot;paging.phtml&quot;
</code></pre>]]></description>
      <pubDate>Wed, 29 Apr 2009 13:54:36 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Plugger - A Plugin Manager]]></title>
      <link>http://zfsnippets.com/snippets/view/id/57</link>
      <guid>http://zfsnippets.com/snippets/view/id/57</guid>
      <description><![CDATA[<p>The plugin manager - plugger - is implemented as a ZF plugin, but its not needed to register it as a plugin, only instantiate it and configure it by setters.<br />
<br />
Why a plugin manager? If you have many plugins in your ZF application they are all loaded on each request. Even if they are not needed in current request.<br />
<br />
The plugger is a layer before dispatch process is started and plugins are registered only if they are really needed in current request.<br />
<br />
<br />
<br />
advantages<br />
<br />
All plugins will be managed by one manager class, the plugin manager. The plugger has to be initiliazed in the bootstrap and after that, plugger registers all plugins automatically and only when they really needed.<br />
<br />
It's possible to load plugins on each request or only if they really needed (known by the URL). This decreases ZF parse time and serves much more flexibility in using plugins.<br />
<br />
The plugger detects the area from URL automatically in 3 optional steps by default. Alternativly a developer could set area by himself. This serves a lot of comfort to organize plugins.<br />
<br />
<br />
<br />
disadvantage<br />
<br />
If a baseUrl is used/needed, then it must be set manually in bootstrap, because plugger works completely in constructor and must be instantiated in bootstrap before running the dispatch process.</p><pre><code>TUTORIAL
Usage in bootstrap with setters:

// Include PHP file...
// Plugin Manager.
$plugger = new Bolzz_Zend_PluggerPlugin();

// This instance is used by plugger to load
// a plugin on demand.
$oLoaderPlugins = new Zend_Loader_PluginLoader();

// Add all prefix-path-mappings. That's all what plugger needs.
$oLoaderPlugins-&gt;addPrefixPath('Tools_Plugin', '../application/modules/tools/plugins/'); // EXAMPLE!

// Now, add the PluginLoader instance to the plugger.
$plugger-&gt;setLoader($oLoaderPlugins);

// Set &quot;default plugins&quot;. These plugins will be loaded on each request.
// That's the ZF standard.
$plugger-&gt;addDefaults('ToolBar');

// Add some arguments for plugin's constructor, if needed.
// Plugger will pass these 3 args in the same order and data type:
// Tools_Plugin_ToolBar - a boolean, an integer and a num array.
$plugger-&gt;addArgs('ToolBar', true, 1, array('val1', 'val2'));

// Above, last two calls can be done by one:
// $plugger-&gt;addDefaults('ToolBar', true, 1, array('val1', 'val2'));

// Now, first example why it's good to use plugger.
// Tools_Plugin_UserToolBar is only needed if a user wants to edit his options.
// Therefor, a user calls the URL http://www.mydomain.com/settings/someUsername.
// Now, plugger detects &quot;settings&quot; in the URL and loads all plugins,
// which were registered to this request.
$plugger-&gt;addSpecials('settings', 'UserToolBar', true, 1, array('val1', 'val2'));
// Tools_Plugin_AdminToolBar is only needed/loaded in an admin panel.
$plugger-&gt;addSpecials('admin', 'AdminToolBar');

// plugger handles each request by 3 steps to get known which AREA (settings, admins, etc.)
// should be loaded. This process can be customized.

// Option 1: Searches in URL for a module name and sets it as AREA.
// $plugger-&gt;setMode('module');
// Option 2: If the regex matches the URL &quot;settings&quot; is been set as AREA.
$plugger-&gt;setRegex('settings', '^settings/[a-z]*');
// Option 3: Searches in URL request string for &quot;settings&quot; and on success &quot;settings&quot; is being set as AREA.
// $plugger-&gt;setNeedle('settings', 'settings');

// Now, plugger is working.
$plugger-&gt;run();


// Note: plugger could throw an exception Bolzz_Exception_Plugger.
</code></pre><h3></h3><pre><code>&lt;?php
/**
 * Bolzz Library
 * http://www.bolzz.com - BOLZZ | IT Entwicklung
 *
 * LICENSE
 * 100% Freeware and Open Source
 *
 * @package Bolzz
 * @subpackage Zend
 * @category Plugins
 * @filesource
 */

require_once '../libs/Bolzz_Library/Bolzz/Exception/Plugger.php';

/**
 * Plugger (Plugin Manager)
 * Manages all plugins and loads them only if they are really needed.
 * On each request the Plugger registers plugins, if they are linked
 * to that request and only then.
 *
 * @example Quickstart_PluggerPlugin.php
 * @tutorial http://www.zfforum.de/showpost.php?p=29802&amp;postcount=21
 * @version Version 1.4.2
 */
final class Bolzz_Zend_PluggerPlugin extends Zend_Controller_Plugin_Abstract
{
// data elements #############################################################
// MUST ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	
	/**
	 * Count of members which has to be initialized to use/run Plugger.
	 */
	const MEMBERS_TO_INIT = 2;
	
	/**
	 * Counter flag.
	 *
	 * @var int Default: count of members to initialize.
	 */
	private $_initialized = self::MEMBERS_TO_INIT;
	
	/**
	 * List of initialized members. Setter method as element.
	 *
	 * @var array Num Array.
	 */
	private $_initList = array();
	
	/**
	 * Mode
	 *
	 * @var bool
	 */
	private $_run = false;
	
	/**
	 * Base URL set by front controller.
	 * @var string On init() $baseUrl is set on $this-&gt;front-&gt;getBaseUrl().
	 */
	private $_baseUrl = '';
	
	/**
	 * Parameters in URL.
	 * If $baseUrl is set, it will be filtered from $urlParams automatically by the _loadAreaBy*()-methods.
	 * @var string On init() $urlParams is set on $_SERVER['REQUEST_URI'].
	 */
	private $_urlParams = '';
	
	/**
	 * Name of Module, Controller, Action or whatever you like. If empty tried to set by loadArea().
	 * This variable represents current website area to register plugins for.
	 * Plugins from $pluginsAreas will be loaded by the Manager, if their associative key is equal with $area.
	 * &lt;code&gt;
	 * &lt;?php
	 * // Define plugins to load in specified areas.
	 * $pluginsAreas = array(
	 * 'areaFoo' =&gt; array('Plugin_Class1', 'Plugin_Class2'), // Area 1 ------- * Plugin 
	 * 'areaBar' =&gt; 'Plugin_Class3', // Area 1 ------- 1 Plugin
	 * 'areaFooBar' =&gt; array('Plugin_Class4')); // Area 1 ------- 1 Plugin
	 * 
	 * // if $area === 'areaFoo'
	 * //    Plugin_Class1 and Plugin_Class2 will be registered.
	 * //    Plugin_Class3 and Plugin_Class4 will NOT be registered.
	 * &lt;/code&gt;
	 * @var string
	 */
	private $_area = '';

	/**
	 * If you set $areaMode your project has to use a conventional modular directory struture, like Zend does recommend.
	 * If $areaRegex or $areaNeedle are set, they will be checked first.
 	 * @link http://framework.zend.com/manual/en/zend.controller.modular.html 7.11. Using a Conventional Modular Directory Structure
	 * @var string 'module' | 'controller' | 'action' | ''. By Default: 'module'.
	 */
	private $_areaMode = 'module';
	
	/**
	 * If $areaRegex is set, then Regex will be checked against the URL before $areaMode but after $areaNeedle.
	 * Haystack is URL string.
	 * &lt;code&gt;
	 * &lt;?php
	 * array('area name' =&gt; 'REGEX');
	 * &lt;/code&gt;	 
	 * @var array Associative Array.
	 */
	private $_areaRegex = array();

	/**
	 * If $areaNeedle is set, then your Regex will be checked against the URL before $areaMode and $areaRegex.
	 * Haystack is URL string.
	 * &lt;code&gt;
	 * &lt;?php
	 * array('area name' =&gt; 'needle');
	 * &lt;/code&gt;
	 * @var array Associative Array.
	 */
	private $_areaNeedle = array();
	
	/**
	 * Management for prefixes and paths of plugin classes.
	 * @var object Zend_Loader_PluginLoader_Interface
	 */
	private $_loader = null;
	
	/**
	 * Default plugins to load.
	 * &lt;code&gt;
	 * &lt;?php
	 * $pluginsDefaults = array('Plugin_Class1', 'Plugin_Class2', 'Plugin_Class3');
	 * &lt;/code&gt;
	 * @var array Numeric Array
	 */
	private $_pluginsDefaults = array();

	/**
	 * Plugins to load in specified areas.
	 * &lt;code&gt;
	 * &lt;?php
	 * // Exammple 1: In each area only one plugin will be loaded.
	 * $pluginsAreas = array(
	 * 'areaFoo' =&gt; 'Plugin_Class1', 
	 * 'areaBar' =&gt; 'Plugin_Class2', 
	 * 'areaFooBar' =&gt; 'Plugin_Class3');
	 * 
	 * // Example 2: In area 'areaFoo' will be more than one plugin loaded.
	 * $pluginsAreas = array(
	 * 'areaFoo' =&gt; array('Plugin_Class1', 'Plugin_Class2'), // Area 1 ------- * Plugin 
	 * 'areaBar' =&gt; 'Plugin_Class3', // Area 1 ------- 1 Plugin
	 * 'areaFooBar' =&gt; array('Plugin_Class4')); // Area 1 ------- 1 Plugin
	 * &lt;/code&gt;
	 * @var array Associative Array
	 */
	private $_pluginsAreas = array();
	
	/**
	 * Arguments for constructors of plugins.
	 * &lt;code&gt;
	 * &lt;?php
	 * // Example 1: One argument needed - Given as an string
	 * $arguments = array('classname' =&gt; 'param1');
	 * // Example 2: One argument needed - Given as an array
	 * $arguments = array('classname' =&gt; array('param1'));
	 * // Example 3: Two or more arguments needed
	 * $arguments = array('classname' =&gt; array('param1', 'param2'));
	 * &lt;/code&gt;
	 *
	 * @var array Assoziative [multiple] array.
	 */
	private $_arguments = array();
	
	/**
	 * The Singleton Front Controller
	 * Will be set each time when create an object. Flag $_run does not care.
	 * @var object Zend_Controller_Front
	 */
	public $front = null;

// element functions ##########################################################
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Constructor Bolzz_Zend_PluggerPlugin
	 * 
	 * Initialize members and register plugins.
	 * 
	 * @throws Bolzz_Exception_Plugger Only when $_run is true.
	 * @uses run()
	 * @uses Zend_Controller_Front::getInstance()
	 * @param object $_loader Zend_Loader_PluginLoader_Interface. By Default: null.
	 * @param array $_pluginsDefaults Load these plugins by default - array('Plugin_Name1', 'Plugin_Name2')
	 * @param array $_pluginsAreas Load these plugins in specific areas - array('area' =&gt; 'Plugin_Name')
	 * @param array $_arguments Arguments for constructors of plugins.
	 * @param string $_area Current name of Module, Controller or Action. If empty (default), Plugger will set it.
	 * @param string $_areaMode Values: 'module' | 'controller' | 'action' | ''. By Default: 'module'.
	 * @param array $_areaRegex Associative Array. Key is area which will be set if value (regex) matches in URL. Note: Regex must be set in brackets (REGEX).
	 * @param array $_areaNeedle Associative Array. Key is area, which will be set if value (needle) found in URL.
	 * @param bool $_run If true, constructor will try to run Plugger. Default: false.
	 */
	public function __construct($_loader = null, $_pluginsDefaults = array(), $_pluginsAreas = array(),
								$_arguments = array(), $_area = '',
								$_areaMode = 'module', $_areaRegex = array(), $_areaNeedle = array(),
								$_run = false)
	{
		$this-&gt;front = Zend_Controller_Front::getInstance();

		$this-&gt;_run = $_run;
		
		$this-&gt;_init($_loader, $_pluginsDefaults, $_pluginsAreas, $_arguments, $_area, $_areaMode, $_areaRegex, $_areaNeedle);

		if (true === $this-&gt;_run) {
			$this-&gt;run();
		}
	}

// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Initialize members.
	 * 
	 * Uses $_SERVER['REQUEST_URI'] to get all GET parameters to $_urlParams.
	 * 
	 * @usedby __construct()
	 * @param object $_loader Zend_Loader_PluginLoader_Interface
	 * @param array $_pluginsDefaults
	 * @param array $_pluginsAreas
	 * @param array $_arguments
	 * @param string $_area
	 * @param string $_areaMode
	 * @param array $_areaRegex
	 * @param array $_areaNeedle
	 * @return void
	 */
	private function _init($_loader, $_pluginsDefaults, $_pluginsAreas, $_arguments, $_area,
							$_areaMode,	$_areaRegex, $_areaNeedle)
	{
		if ($_loader instanceof Zend_Loader_PluginLoader_Interface) {
			$this-&gt;setLoader($_loader);
		}

		$this-&gt;setBaseUrl($this-&gt;front-&gt;getBaseUrl());
		$this-&gt;setUrlParams($_SERVER['REQUEST_URI']);
		$this-&gt;setDefaults($_pluginsDefaults);
		$this-&gt;setSpecials($_pluginsAreas);
		$this-&gt;setArgs($_arguments);
		$this-&gt;setMode($_areaMode);
		$this-&gt;setRegex($_areaRegex);
		$this-&gt;setNeedle($_areaNeedle);

		if (!empty($_area)) {
			$this-&gt;setArea($_area);
		}
	}

// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Register plugins for specific areas.
	 * 
	 * @todo exception handling
	 * @usedby __construct()
	 * @uses _runFactory()
	 * @uses $_pluginsAreas
	 * @uses $_area
	 * @return void
	 */
	private function _registerSpecials()
	{
		// identify equal areas
		switch ($this-&gt;_area) {
			case 'default':
			case 'index':
				$areaTmp = array('default', 'index');
				break;
			default:
				$areaTmp[0] = $this-&gt;_area;
				break;
		}

		if (is_array($areaTmp)) {
			$counts = count($areaTmp);
		} else {
			$counts = 0;
		}

		while ($counts &gt; 0) {
			$countsIndex = --$counts;

			if (isset($areaTmp[$countsIndex])) {
				if (isset($this-&gt;_pluginsAreas[$areaTmp[$countsIndex]])) {
					$areaClasses = $this-&gt;_pluginsAreas[$areaTmp[$countsIndex]];

					if (!empty($areaClasses)) {
						if (is_array($areaClasses)) {
							foreach ($areaClasses as $key =&gt; $name) {
								$this-&gt;_runFactory($name);
							}
						} else {
							$this-&gt;_runFactory($areaClasses);
						}
					}
				}
			}
		}
	}	

// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Register plugins for all areas of application.
	 * 
	 * @todo exception handling
	 * @usedby __construct()
	 * @uses _runFactory()
	 * @uses $_pluginsDefaults
	 * @return void
	 */
	private function _registerDefaults()
	{
		if (!empty($this-&gt;_pluginsDefaults)) {
			foreach ($this-&gt;_pluginsDefaults as $key =&gt; $name) {
				$this-&gt;_runFactory($name);
			}
		}
	}	

// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Factory Method for Plugins. Create an object.
	 * 
	 * @todo throw Exception if could not instantiate class, because of missing arguments, etc.
	 * @uses ReflectionClass
	 * @param string $_sName Filename or Class name
	 * @param string $_sClassName Is definetly a class name
	 * @return bool|object false or instance of $_sClassName
	 */
	private function _factory($_sName, $_sClassName)
	{
		if (isset($_sName) &amp;&amp; array_key_exists($_sName, $this-&gt;_arguments)) {
			$index = $_sName;
		} elseif (isset($_sClassName) &amp;&amp; array_key_exists($_sClassName, $this-&gt;_arguments)) {
			$index = $_sClassName;
		} else {
			$index = false;
		}
		
		if ($index !== false
		&amp;&amp; isset($_sClassName)
		&amp;&amp; !empty($_sClassName)
		&amp;&amp; is_string($_sClassName)) {
			if (is_array($this-&gt;_arguments[$index])) {
				// array - support constructors with more than one arguments.			

				$refl = new ReflectionClass($_sClassName);

				$obj = $refl-&gt;newInstanceArgs($this-&gt;_arguments[$index]);
			} else { 
				// string - only one argument given to constructor.

				$obj = new $_sClassName($this-&gt;_arguments[$index]);	
			}
		} else {
			if (isset($_sClassName)
			&amp;&amp; !empty($_sClassName)
			&amp;&amp; is_string($_sClassName))
				$obj = new $_sClassName();
			else
				$obj = null;
		}

		return (!is_null($obj) &amp;&amp; is_object($obj)) ? $obj : false;
	}

// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++	

	/**
	 * Run Factory Method for Plugins.
	 * 
	 * @throws Zend_Loader_PluginLoader_Exception
	 * @throws Bolzz_Exception_Plugger
	 * @uses _factory()
	 * @uses $front
	 * @uses $_loader
	 * @param string $_sName Filename or Class name
	 * @return void
	 */
	private function _runFactory($_sName)
	{
		if (!is_object($this-&gt;_loader)
		|| !($this-&gt;_loader instanceof Zend_Loader_PluginLoader_Interface)) {
			include_once 'Zend/Loader/PluginLoader/Exception.php';
			
			throw new Zend_Loader_PluginLoader_Exception(__CLASS__
				. '::$_loader has to be an instance of Zend_Loader_PluginLoader_Interface. Currently given: '
				. gettype($this-&gt;_loader));
		}

		// NOTE: If class can not be loaded by name here, an exception
		// Zend_Loader_PluginLoader_Exception will be thrown.
		$this-&gt;_loader-&gt;load($_sName);

		if ($this-&gt;_loader-&gt;isLoaded($_sName)) {
			$className = $this-&gt;_loader-&gt;getClassName($_sName);
		}

		$plugin = $this-&gt;_factory($_sName, $className);

		if ($plugin !== false) {
			$this-&gt;front-&gt;registerPlugin($plugin);
		} else {
			throw new Bolzz_Exception_Plugger('Register plugin &quot;'. $className .'&quot; failed.');
		}
	}

// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Search in array $areaNeedle for parameters of URL. 
	 * 
	 * First parameter found in array will set $area. So the order is: domain.de/p1/p2/p3
	 * If p1 was found in array, return $areaNeedle[p1]. If not, array will be searched
	 * for p2 and after all p3. There is no need to search for more than 3 parameters,
	 * because of URL structure module/controller/action/...
	 * 
	 * &lt;code&gt;
	 * &lt;?php
	 * $areaNeedle = array('foo' =&gt; 'bar', 'bla' =&gt; 'blubb');
	 * // so when manager calls _loadAreaByNeedle() and parameters are 'blubb' and 'bar' then
	 * // return 'bla', what means that $area is set to 'bla'. Controlled by order of params!
	 * &lt;/code&gt;
	 * @usedby _init()
	 * @uses $_urlParams
	 * @uses $_baseUrl
	 * @uses $_areaNeedle
	 * @return string Value for Bolzz_Zend_PluggerPlugin::$area. By Default: empty string.
	 */	
	private function _loadAreaByNeedle()
	{
		$aParams = array();

		if (!empty($this-&gt;_urlParams)) {
			$params = str_replace($this-&gt;_baseUrl, '', $this-&gt;_urlParams);
			
			if ($params{0} === '/') {
				$params = substr($params, 1);
			}
			
			$aParams = explode('/', $params);	
		}

		if (!empty($aParams)) {
			$counts = count($aParams);
			
			// search for first 3 parameters only.
			if ($counts &gt; 3) {
				$counts = 3;
			}

			for ($i = 0; $i &lt; $counts; $i++) {
				if (in_array($aParams[$i], $this-&gt;_areaNeedle)) {
					$aFlip = array_flip($this-&gt;_areaNeedle);
					
					return $aFlip[$aParams[$i]];
				}
			}
		}
		
		return '';
	}

// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Check Regexes given as VALUES in assoc array $_areaRegex against first 3 parameters in URL.
	 * 
	 * $baseUrl is filtered from URL automatically, before checking. 
	 * A trailing slash also will be filtered.
	 * 
	 * &lt;code&gt;
	 * &lt;?php
	 * $areaRegex = array('foo' =&gt; '(^bar.*)', 'bla' =&gt; '^blubb.*');
	 * // so when manager calls _loadAreaByRegex() then
	 * // check regex (^bar.*) against parameters, on success return 'foo'.
	 * // Controlled by order of array! Unlike _loadAreaByNeedle().
	 * &lt;/code&gt;
	 * @usedby _init()
	 * @uses $_urlParams
	 * @uses $_baseUrl
	 * @uses $_areaRegex
	 * @return string Value of Bolzz_Zend_PluggerPlugin::$area. By Default: empty string.
	 */	
	private function _loadAreaByRegex()
	{
		$params = str_replace($this-&gt;_baseUrl, '', $this-&gt;_urlParams);
		
		if ($params{0} === '/') {
			$params = substr($params, 1);
		}
		
		$aParams = explode('/', $params);

		if (is_array($aParams)) {
			$counts = count($aParams);
			
			if ($counts &gt; 3) {
				$counts = 3;
			}
			
			$params = '';
			
			for ($i = 0; $i &lt; $counts; $i++) {
				$params .= $aParams[$i] . '/';
			}
		}

		foreach ($this-&gt;_areaRegex as $area =&gt; $regex) {
			if ($regex{0} !== '(') {
				$regex = '(' . $regex . ')';
			}
			
			if (preg_match($regex, $params) === 1) {
				return $area;
			}
		}

		return '';
	}

// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Read Module, Controller or Action out of url string when $area is empty (default).
	 * If no parameters found in URL or $areaMode is empty, then return 'default'.
	 * Is called last in the chain of the loadAreaBy*()-methods, if one or both of the other arrays are given.
	 * 
	 * &lt;code&gt;
	 * &lt;?php
	 * $areaMode = 'module';
	 * // so when manager calls loadAreaByMode() then
	 * // check if a module exists in parameters, on success return parameter stands for module.
	 * 
	 * // NOTE:
	 * // So this means, URL should be like module/controller/action/key1/value1/... like Zend does recommend.
	 * // Visit link to Zend Documentation for more details about MVC structure of Zend Framework.
	 * &lt;/code&gt;
	 * @todo optimize code, create _filterTrailingSlash() for loadAreaBy*()-methods
	 * @link http://framework.zend.com/manual/en/zend.controller.modular.html 7.11. Using a Conventional Modular Directory Structure
	 * @usedby _init()
	 * @uses $_urlParams
	 * @uses $_baseUrl
	 * @uses $_areaMode
	 * @return string Value of Bolzz_Zend_PluggerPlugin::$area. Will never be an empty string like in the other loadAreaBy*-methods. By Default: 'default'.
	 */	
	private function _loadAreaByMode()
	{
		$aParams = array();

		if (!empty($this-&gt;_urlParams)) {
			$params = str_replace($this-&gt;_baseUrl, '', $this-&gt;_urlParams);
			
			if ($params{0} === '/') {
				$params = substr($params, 1);
			}
			
			$aParams = explode('/', $params);	
		}

		if (empty($aParams[0])) {
			return 'default'; // no parameter found in URL.
		} else {
			switch ($this-&gt;_areaMode) {
				case 'module':
					return (!empty($aParams[0])) ? $aParams[0] : $aParams[1];

				case 'controller':
					return (!empty($aParams[0])) ? $aParams[1] : $aParams[2];

				case 'action':
					return (!empty($aParams[0])) ? $aParams[2] : $aParams[3];

				default:
					return 'default'; // empty string given in $this-&gt;_areaMode (set by __construct)
			}
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Mark members as initialized, which are needed to run Plugger.
	 * 
	 * @param string $_s
	 * @return void
	 */
	private function _initialized($_s)
	{
		if (false === $this-&gt;isInitialized()
		&amp;&amp; isset($_s)
		&amp;&amp; false === in_array($_s, $this-&gt;_initList, true)) {
			$_s = (string) $_s;

			array_push($this-&gt;_initList, $_s);
			
			$this-&gt;_initialized--;
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Load area by Needle, Regex or Mode.
	 * 
	 * NOTE: If you use isInitialized() in your code, be sure that Area is set.
	 * Therefor you can use setArea(), loadArea() or constructor argument.
	 * 
	 * @usedby run()
	 * @uses setArea()
	 * @return void
	 */
	public function loadArea()
	{
		if (empty($this-&gt;_area)) {
			if (!empty($this-&gt;_areaNeedle)) {				
				$this-&gt;setArea($this-&gt;_loadAreaByNeedle());
			}

			if (empty($this-&gt;_area) &amp;&amp; !empty($this-&gt;_areaRegex)) {				
				$this-&gt;setArea($this-&gt;_loadAreaByRegex());
			}

			if (empty($this-&gt;_area)) {
				$this-&gt;setArea($this-&gt;_loadAreaByMode());
			}
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Check whether all members are initialized.
	 * 
	 * NOTE: This method would return false, if $_area or $_loader are not set.
	 * @return bool
	 */
	public function isInitialized()
	{		
		if (count($this-&gt;_initList) == self::MEMBERS_TO_INIT
		&amp;&amp; 0 === $this-&gt;_initialized) {
			return true;
		}
		
		return false;
	}

// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Setter
	 * 
	 * @usedby loadArea()
	 * @param string $_s
	 * @return void
	 */
	public function setArea($_s)
	{
		if (isset($_s) &amp;&amp; is_string($_s)) {
			$this-&gt;_area = $_s;
			$this-&gt;_initialized(__METHOD__);
		} else {
// @todo wrong type
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Setter
	 * 
	 * @param mixed $_m String: Areaname. | $_a assoc Array. Example: array('AREANAME' =&gt; 'NEEDLE');
	 * @param string $_needle Needle. Default: ''.
	 * @return void
	 */
	public function setNeedle($_m, $_needle = '')
	{
		if (isset($_m) &amp;&amp; is_array($_m)) {
			$this-&gt;_areaNeedle = $_m;
		} elseif (isset($_m) &amp;&amp; is_string($_m)) {
			 $this-&gt;_areaNeedle = array($_m =&gt; $_needle);
		} else {
// @todo wrong type
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Setter
	 * 
	 * @param mixed $_m String: Areaname. | assoc Array. Example: array('AREANAME' =&gt; '(^REGEX.*)');
	 * @param string $_regex Regex. Default: ''.
	 * @return void
	 */
	public function setRegex($_m, $_regex = '')
	{
		if (isset($_m) &amp;&amp; is_array($_m)) {
			$this-&gt;_areaRegex = $_m;
		} elseif (isset($_m) &amp;&amp; is_string($_m)) {
			 $this-&gt;_areaRegex = array($_m =&gt; $_regex);
		} else {
// @todo wrong type
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Setter
	 * 
	 * @param string $_s
	 * @return void
	 */
	public function setMode($_s)
	{
		if (isset($_s) &amp;&amp; is_string($_s)) {
			$this-&gt;_areaMode = $_s;
		} else {
// @todo wrong type
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Setter
	 * 
	 * Overwrite member. If you don't want, use {@see addSpecials()}.
	 * @param array $_a assoc Array. Key: Area (string) Value: Classname (string|num array)
	 * @return void
	 */
	public function setSpecials($_a)
	{
		if (isset($_a) &amp;&amp; is_array($_a)) {
			$this-&gt;_pluginsAreas = $_a;
		} else {
// @todo wrong type
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Adder
	 * 
	 * NOTE: Value of an existing Key/Area will be overwritten.
	 * Variable count of arguments allowed. They represent the constructor arguments
	 * for the plugin class. Only allowed if first parameter is a string!
	 * If Array, arguments will be ignored!
	 * @varargs
	 * @uses ReflectionMethod
	 * @param mixed $_m String: Area | assoc Array. Key: Area (string) Value: Classname (string|num array)
	 * @param mixed $_mClass String: Classname. Default: null. | Num Array. Values: Classnames
	 * @return void
	 */
	public function addSpecials($_m, $_mClass = null)
	{
		if (isset($_m) &amp;&amp; is_array($_m)) {
			foreach ($_m as $area =&gt; $mCls) {
				if (is_string($area)
				&amp;&amp; (is_string($mCls) || is_array($mCls))) {
					$this-&gt;_pluginsAreas[$area] = $mCls;
				}
			}
		} elseif (isset($_m) &amp;&amp; is_string($_m)) {
			if (!empty($_m) &amp;&amp; !empty($_mClass)) {
				// Add specials.
				if (is_string($_mClass) || is_array($_mClass)) {
					$this-&gt;_pluginsAreas[$_m] = $_mClass;
				}

				// Constructor arguments are given.
				if (func_num_args() &gt; 2) {
					$aArgs = func_get_args();
					
					array_shift($aArgs); // remove AREANAME
					
					$addArgs = new ReflectionMethod(__CLASS__, 'addArgs');
					
					$addArgs-&gt;invokeArgs($this, $aArgs);
				}
			}
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Setter
	 * 
	 * Overwrite member. If you don't want, use {@see addArgs()}.
	 * @todo Implement variable arguments - second param needed.
	 * @param array $_a assoc Array. Key: Classname Value: mixed
	 * @return void
	 */
	public function setArgs($_a)
	{
		if (isset($_a) &amp;&amp; is_array($_a)) {
			$this-&gt;_arguments = $_a;
		} else {
// @todo wrong type
		}
	}

// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Adder
	 * 
	 * Variable count of arguments allowed. They represent the constructor arguments
	 * for the plugin class.
	 * @varargs
	 * @param string $_className
	 * @return void
	 */
	public function addArgs($_className)
	{
		if (isset($_className) &amp;&amp; is_string($_className)) {
			$aArgs = null;

			if (func_num_args() &gt; 1) {
				$aArgs = func_get_args();

				if ($aArgs[0] === $_className) {
					array_shift($aArgs);
				}			
			}

			if (is_array($aArgs)) {
				$aArguments = array();
				
				foreach ($aArgs as $key =&gt; $mArg) {
					$aArguments[] = $mArg;
				}

				if (!empty($aArguments)) {
					$this-&gt;_arguments[$_className] = $aArguments;
				} else {
// @todo Exception: &quot;No arguments given.&quot;
				}
			} else {
// @todo Exception: &quot;No arguments given.&quot;
			}
		} else {
// @todo wrong type
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Setter
	 * 
	 * Overwrite member. If you don't want, use addDefaults().
	 * @todo Implement usage with variable count of arguments.
	 * @param mixed $_m Num Array or String.
	 * @return void
	 */
	public function setDefaults($_m)
	{
		if (isset($_m) &amp;&amp; is_array($_m)) {
			$this-&gt;_pluginsDefaults = $_m;
		} elseif (isset($_m) &amp;&amp; is_string($_m)) {
			$this-&gt;_pluginsDefaults = array($_m);
		} else {
// @todo wrong type
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Adder
	 * 
	 * Variable count of arguments allowed. They represent the constructor arguments
	 * for the plugin class. Only allowed if first parameter is a string!
	 * If Array, arguments will be ignored!
	 * @varargs
	 * @uses ReflectionMethod
	 * @param mixed $_m Num Array or String. Array: Classnames. String: Classname.
	 * @return void
	 */
	public function addDefaults($_m)
	{
		if (isset($_m) &amp;&amp; is_array($_m)) {
			foreach ($_m as $key =&gt; $className) {
				if (is_string($className)
				&amp;&amp; false === in_array($className, $this-&gt;_pluginsDefaults)) {
					$this-&gt;_pluginsDefaults[] = $className;
				}
			}
		} elseif (isset($_m) &amp;&amp; is_string($_m)) {
			// Add defaults.
			if (false === in_array($_m, $this-&gt;_pluginsDefaults)) {
				array_push($this-&gt;_pluginsDefaults, $_m);
			}
			
			// Constructor arguments are given.
			if (func_num_args() &gt; 1) {
				$aArgs = func_get_args();
				
				$addArgs = new ReflectionMethod(__CLASS__, 'addArgs');
				
				$addArgs-&gt;invokeArgs($this, $aArgs);
			}
		} else {
// @todo wrong type
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Setter
	 * 
	 * By Default: Value of $_SERVER['REQUEST_URI'].
	 * @param string $_s
	 * @return void
	 */
	public function setUrlParams($_s)
	{
		if (isset($_s) &amp;&amp; is_string($_s)) {
			$this-&gt;_urlParams = $_s;
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Setter
	 * 
	 * BaseUrl comes from Front Controller and is set by constructor. You can
	 * set (overwrite) the BaseUrl by this setter method.
	 * NOTE: This setter will not change the major baseUrl of the front controller!
	 * It is for Plugger use only.
	 * @param string $_s
	 * @return void
	 */
	public function setBaseUrl($_s)
	{
		if (isset($_s) &amp;&amp; is_string($_s)) {
			$this-&gt;_baseUrl = $_s;
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Setter
	 * 
	 * NOTE: A Loader object has been set before run().
	 * @param object $_o Zend_Loader_PluginLoader_Interface
	 * @return void
	 */
	public function setLoader(Zend_Loader_PluginLoader_Interface $_o)
	{
		$this-&gt;_loader = $_o;
		$this-&gt;_initialized(__METHOD__);
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	
	/**
	 * Run Plugger, means register plugins. Plugger has to be initialized otherwise
	 * an exception would be thrown.
	 * 
	 * NOTE: Use only in mode $_run: false (Last argument of constructor - Default: false).
	 * @uses loadArea() 
	 * @throws Bolzz_Exception_Plugger
	 * @return void
	 */
	public function run()
	{
		$this-&gt;loadArea();

		if (true === $this-&gt;isInitialized()) {
			$this-&gt;_registerDefaults();
			
			$this-&gt;_registerSpecials();
		} else {
			throw new Bolzz_Exception_Plugger('Plugger is not full initialized and not ready to run or register plugins.');
		}
	}
	
// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Reset initialization. 
	 * 
	 * Members keep their values, only members which are
	 * important for a minimum of initialization will be cleared!
	 * @uses ReflectionClass
	 * @return void
	 */
	public function reset()
	{
		$clsPlugger = new ReflectionClass(__CLASS__);
		
		$defaultProps = $clsPlugger-&gt;getDefaultProperties();
		
		$this-&gt;_initialized = $defaultProps['_initialized'];
		$this-&gt;_initList 	= $defaultProps['_initList'];
		$this-&gt;_area 		= $defaultProps['_area'];
		$this-&gt;_loader 		= $defaultProps['_loader'];
	}

// MUST +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	/**
	 * Clear all member values.
	 * 
	 * @uses reset()
	 * @uses ReflectionClass
	 * @return void
	 */
	public function clear()
	{
		$this-&gt;reset();

		$clsParent 		= new ReflectionClass(get_parent_class($this));
		$parentProps 	= $clsParent-&gt;getDefaultProperties();

		$clsPlugger 	= new ReflectionClass(__CLASS__);
		$selfProps 	= $clsPlugger-&gt;getDefaultProperties();
		
		// Do not change parent's members
		$props = array_diff_assoc($selfProps, $parentProps);
		
		if (is_array($props)) {
			foreach ($props as $sMember =&gt; $mValue) {
				$this-&gt;{$sMember} = $mValue;
			}
		}
	}
}
</code></pre><h3></h3><pre><code>&lt;?php
/**
 * Bolzz Library
 * http://www.bolzz.com - BOLZZ | IT Entwicklung
 *
 * LICENSE
 * 100% Freeware and Open Source
 *
 * @package Bolzz
 * @subpackage Exception
 */
 
/**
 * Plugin Manager Exception
 *
 * @version Version 0.1.0
 */
class Bolzz_Exception_Plugger extends Exception
{
	public function __construct($_message = '')
	{
		$this-&gt;message = $_message;
	}
}
</code></pre>]]></description>
      <pubDate>Wed, 08 Apr 2009 14:53:04 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Auth Adapter Config]]></title>
      <link>http://zfsnippets.com/snippets/view/id/56</link>
      <guid>http://zfsnippets.com/snippets/view/id/56</guid>
      <description><![CDATA[<p>Adapter allows you authorization via config.<br />
</p><pre><code>&lt;?php
class Dropper_Auth_Adapter_Config implements Zend_Auth_Adapter_Interface
{
	protected $_credential;
	protected $_identity;
	protected $_credentialField;
	protected $_identityField;
	
	/**
	 * Global config
	 *
	 * @var Zend_Config
	 */
	protected $_config;
	
	public function __construct(Zend_Config $config, $credentialField, $identityField)
	{
		$this-&gt;_config = $config;
		$this-&gt;setCredentialField($credentialField)
			-&gt;setIdentityField($identityField);
	}
	
	/**
	 * Set credential field
	 *
	 * @param string $credentialField
	 * @return Dropper_Auth_Adapter_Config
	 */
	public function setCredentialField($credentialField)
	{
		$this-&gt;_credentialField = $credentialField;
		return $this;
	}
	
	/**
	 * Set identity field
	 *
	 * @param string $identityField
	 * @return Dropper_Auth_Adapter_Config
	 */
	public function setIdentityField($identityField)
	{
		$this-&gt;_identityField = $identityField;
		return $this;
	}
	
	/**
	 * Set credential value
	 *
	 * @param string $credentia
	 * @return Dropper_Auth_Adapter_Config
	 */
	public function setCredential($credential)
	{
		$this-&gt;_credential = $credential;
		return $this;	
	}
	
	/**
	 * Set identity value
	 *
	 * @param string $identity
	 * @return Dropper_Auth_Adapter_Config
	 */
	public function setIdentity($identity)
	{
		$this-&gt;_identity = $identity;
		return $this;
	}
	
	/**
	 * Authenticate process
	 *
	 * @return Zend_Auth_Result
	 */
	public function authenticate()
	{
		$crField = explode(&quot;.&quot;, $this-&gt;_credentialField);
		$idField = explode(&quot;.&quot;, $this-&gt;_identityField);
		$tmpConfig = $this-&gt;_config;
		foreach($crField as $part) {
			$tmpConfig = $tmpConfig-&gt;get($part);
			if (!$tmpConfig instanceof Zend_Config) {
				$credential = $tmpConfig;
			}
		}
		
		
		$tmpConfig = $this-&gt;_config;
		foreach($idField as $part) {
			$tmpConfig = $tmpConfig-&gt;get($part);
			if (!$tmpConfig instanceof Zend_Config) {
				$identity = $tmpConfig;
			}
		}

		if (!$credential || !$identity) {
			throw new Zend_Auth_Adapter_Exception(&quot;Credential and Identity fields shouldn't be empty&quot;);
		}
		
		$result = array(
			'code' =&gt; Zend_Auth_Result::FAILURE,
			'messages' =&gt; array('Invalid identity or credential')
		);
		
		if ($this-&gt;_identity == $identity &amp;&amp; $this-&gt;_credential ==md5($credential)) {
			$result = array(
				'code' =&gt; Zend_Auth_Result::SUCCESS,
				'messages' =&gt; array('Identity and credential are valid')
			);
		}
		
		return new Zend_Auth_Result($result['code'], $this-&gt;_identity, $result['messages']);
	}
}
?&gt;
</code></pre><h3></h3><pre><code>/**
 *@example
 */
&lt;?php
    try {
					$authAdapter = new Dropper_Auth_Adapter_Config($this-&gt;_config, &quot;user.password&quot;, &quot;user.login&quot;);
					$authAdapter-&gt;setIdentity($form-&gt;getValue('username'))
								-&gt;setCredential($form-&gt;getValue('password'));
					$result = Zend_Auth::getInstance()-&gt;authenticate($authAdapter);
				} catch (Zend_Auth_Adapter_Exception $e) {
					//exception handling
				}
?&gt;</code></pre>]]></description>
      <pubDate>Tue, 07 Apr 2009 11:10:20 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[FCKEditor a Form Element]]></title>
      <link>http://zfsnippets.com/snippets/view/id/55</link>
      <guid>http://zfsnippets.com/snippets/view/id/55</guid>
      <description><![CDATA[<p>You can use FCKEditor as a normal Form Element in Zend Framework with this snippet.</p><pre><code>Create class FormRTE in library/Zend/Form/Element/

/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */

/** Zend_Form_Element_Xhtml */
require_once 'Zend/Form/Element/Xhtml.php';

/**
 * Textarea form element
 * 
 * @category   Zend
 * @package    Zend_Form
 * @subpackage Element
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: Textarea.php 8064 2008-02-16 10:58:39Z thomas $
 */
class Zend_Form_Element_FormRTE extends Zend_Form_Element_Xhtml
{
    /**
     * Use formTextarea view helper by default
     * @var string
     */
    public $helper = 'formRTE';
}
</code></pre><h3></h3><pre><code>create in Zend/View/Helper the class Zend_View_Helper_FormRTE or use an other HelperPath

&lt;?php
$view-&gt;setHelperPath(APPLICATION_PATH . '/helpers');
?&gt;
</code></pre><h3></h3><pre><code>&lt;?php 

/** 
 * Abstract class for extension 
 */ 
require_once 'Zend/View/Helper/FormElement.php'; 

/** 
 * FCKeditor PHP class 
 */ 
require_once 'formRTE/fckeditor/fckeditor.php'; 


/** 
 * Helper to generate a &quot;textarea&quot; element 
 * 
 * @category   Zend 
 * @package    Zend_View 
 * @subpackage Helper 
 * @copyright  Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) 
 * @license    http://framework.zend.com/license/new-bsd     New BSD License 
 */ 
class Zend_View_Helper_FormRTE extends Zend_View_Helper_FormElement 
{ 
    /** 
     * Generates a richtext element using FCKeditor. 
     * 
     * @access public 
     * 
     * @param string|array $name If a string, the element name.  If an 
     * array, all other parameters are ignored, and the array elements 
     * are extracted in place of added parameters. 
     * 
     * @param mixed $value The element value. 
     * 
     * @param array $attribs Attributes for the element tag. 
     * 
     * @return string The element XHTML. 
     */ 
    public function formRTE($name = null, $value = null, $attribs = null) 
    { 
        if(is_null($name) &amp;&amp; is_null($value) &amp;&amp; is_null($attribs)) { 
            return $this; 
        } 
         
        $info = $this-&gt;_getInfo($name, $value, $attribs); 
        extract($info); // name, value, attribs, options, listsep, disable 

        $editor = new FCKeditor($name); 
         
        // set variables
        $editor-&gt;BasePath    = 'http://localhost/xxxx/application/helpers/formRTE/fckeditor/' ; 
        $editor-&gt;ToolbarSet = empty($attribs['ToolbarSet']) ? 'Basic' : $attribs['ToolbarSet']; 
        $editor-&gt;Width        = empty($attribs['Width']) ? '50%' : $attribs['Width']; 
        $editor-&gt;Height        = empty($attribs['Height']) ? 250 : $attribs['Height']; 
        $editor-&gt;Value        = $value; 
         
        // set Config  
        $editor-&gt;Config['BaseHref'] = $editor-&gt;BasePath;
        $editor-&gt;Config['CustomConfigurationsPath'] = $editor-&gt;BasePath.'editor/fckconfig.js'; 
        $editor-&gt;Config['SkinPath'] = $editor-&gt;BasePath.'editor/skins/silver/';         
        return $editor-&gt;createHtml(); 
         
    } 
         
}
</code></pre><h3></h3><pre><code>You can add this element to your form like other form elements:


$myForm-&gt;addElement('formRTE', 'message', array(
                                                        'label'      =&gt; 'formRTE label:',
											            'required'   =&gt; true,
											            'value'      =&gt; 'Salam, Schalom, Pax vobis &lt;i&gt;this string &lt;/i&gt;is the value variable  of the View_Helper,&lt;br/&gt;
											                         but i give this string to &lt;b&gt;form-&gt;addElement()&lt;/b&gt; ',
                                                        'attribs'    =&gt; array('myattribute') 
                                                        )
                         );
</code></pre>]]></description>
      <pubDate>Sun, 05 Apr 2009 12:54:21 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Zend Bootstrap]]></title>
      <link>http://zfsnippets.com/snippets/view/id/54</link>
      <guid>http://zfsnippets.com/snippets/view/id/54</guid>
      <description><![CDATA[<p>After starting working with zend framework i found all sorts of examples of bootstrap files, but a lot of them seem pretty messy to me since all the calls to zend components were basically thrown in there.<br />
<br />
So after a lot of looking around i came up with a bootstrap files that is more to my liking. I found the initial class on a blog post when i was looking around but i don't remember where, so sorry for not giving it the credit.<br />
<br />
As you can see basicly i just grouped toghether similar comands and make it all look much more nicer and cleaner. And also i added the autoload function since i really think this is a much faster way then the Zend_Loader option. As for what is run, lets take it one by one:<br />
function run<br />
This is the main function that calls the prepare function and starts up the whole Zend Framework.<br />
<br />
function prepare<br />
Calls all the internal methods that setup the framework to start dispatching the request.<br />
<br />
function setupEnvironment<br />
Here i added the error reporting options and also i define some constants like configuration type ( development - production )<br />
<br />
function setupRegistry()<br />
Start the Zend Registry.<br />
<br />
function setupConfiguration<br />
Get the config file ( contains the db conection data etc. ) and save the configuration in Zend_Registry<br />
<br />
function setupFrontController<br />
Starts the front controller and setup the modular aproach.<br />
<br />
function setupErrorHandler<br />
Registers the Error handler plugins and logger.<br />
<br />
function setupController<br />
Here is the place to put your Controll Action Helpers<br />
<br />
function setupView<br />
start the Zend_View and MVC structure, add the custom HelperPath<br />
<br />
function setupDatabase<br />
start your db connection bassed on the configuration we stored in the registry. Also started the Zend_Db_Table cache system.<br />
<br />
function setupSessions<br />
Start you session, i used a custom Session Manager that uses a mysql database as storage.<br />
<br />
And that is about it. I skipped some of them because i thought they were pretty obvious.<br />
<br />
Hope you will find this usefully, and await your comments.</p><pre><code>&lt;?php

function __autoload($className) {
    require $className = str_replace('_', '/', $className) . '.php';
}

class Bootstrap{

    public static $frontController = null;

    public static $root = '';

    public static $registry = null;

    public static function run(){
        self::prepare();

        $response = self::$frontController-&gt;dispatch();
        self::sendResponse($response);
    }


    public static function prepare(){
        self::setupEnvironment();

        self::setupRegistry();
        self::setupConfiguration();

        self::setupFrontController();
        self::setupErrorHandler();

        self::setupController();
        self::setupView();
        self::setupDatabase();
        self::setupSessions();
        self::setupTranslation();
        self::setupRoutes();
        self::setupAcl();
        self::setupDebug();
    }



    public static function setupEnvironment(){
        error_reporting(E_ALL ^ E_NOTICE);
        ini_set('display_errors', true);

        date_default_timezone_set('Europe/Bucharest');

        self::$root = dirname(dirname(__FILE__));

        $configType = (isset($_SERVER['SERVER_NAME']) &amp;&amp; ($_SERVER['SERVER_NAME'] == '127.0.0.1' OR $_SERVER['SERVER_NAME'] == 'localhost')) ? 'development' : 'production';
        define('APPLICATION_ENVIRONMENT', $configType);

        define('HTMLPURIFIER_PREFIX', self::$root . '/library');
    }


    public static function setupRegistry() {
        self::$registry = new Zend_Registry(array(), ArrayObject::ARRAY_AS_PROPS);
        Zend_Registry::setInstance(self::$registry);
    }

    public static function setupConfiguration() {

        $config = new Zend_Config_Ini(
            self::$root . '/application/config/main.ini',
            APPLICATION_ENVIRONMENT
        );

        self::$registry-&gt;configuration = $config;

        //save $siteRootDir in registry:
        self::$registry-&gt;set('siteRootDir', self::$root );
        self::$registry-&gt;set('applicationRootDir', self::$root . '/application' );

        self::$registry-&gt;set('siteUploadDir', self::$root . '/uploads');

        self::$registry-&gt;set('siteRootUrl', 'http://' . $_SERVER['HTTP_HOST'] );
        self::$registry-&gt;set('siteUploadUrl', '/uploads' );
    }


    public static function setupFrontController(){
        self::$frontController = Zend_Controller_Front::getInstance();
        self::$frontController-&gt;throwExceptions(true);
        self::$frontController-&gt;returnResponse(true);

        self::$frontController-&gt;addModuleDirectory(self::$root . '/application/modules');

        self::$frontController-&gt;setParam('registry', self::$registry);

        self::$frontController-&gt;setParam('env', APPLICATION_ENVIRONMENT);


        $response = new Zend_Controller_Response_Http; // Set default Content-Type
        $response-&gt;setHeader('Content-Type', 'text/html; charset=UTF-8', true);
        self::$frontController-&gt;setResponse($response);
    }


    public static function setupErrorHandler() {
        self::$frontController-&gt;throwExceptions(false);

        self::$frontController-&gt;registerPlugin(new Zend_Controller_Plugin_ErrorHandler(
            array(
                'module'     =&gt; 'default',
                'controller' =&gt; 'error',
                'action'     =&gt; 'error')
            ));

        $writer = new Zend_Log_Writer_Firebug();
        $logger = new Zend_Log($writer);
        Zend_Registry::set('logger',$logger);


    }


    public static function setupController(){
        Zend_Controller_Action_HelperBroker::addHelper(new GSD_Controller_Action_Helper_AuthUsers());
        Zend_Controller_Action_HelperBroker::addHelper(new GSD_Controller_Action_Helper_Breadcrumbs());
    }

    public static function setupView() {

        $view = new Zend_View(array('encoding'=&gt;'UTF-8'));
        $view-&gt;addHelperPath('GSD/View/Helper', 'GSD_View_Helper_');

        $viewRendered = new Zend_Controller_Action_Helper_ViewRenderer($view);
        Zend_Controller_Action_HelperBroker::addHelper($viewRendered);

        Zend_Layout::startMvc(
            array(
                'layoutPath' =&gt; self::$root . '/application/layouts',
                'layout' =&gt; 'default'
            )
        );

        if (self::$frontController) {
            self::$frontController-&gt;registerPlugin(new GSD_Layout_Controller_Plugin_Layout());
        }
    }


    public static function sendResponse(Zend_Controller_Response_Http $response){
        $response-&gt;sendResponse();
    }


    public static function setupDatabase($options = array()){
        extract($options);

        $config = self::$registry-&gt;configuration;

        $db = Zend_Db::factory($config-&gt;db-&gt;adapter, $config-&gt;db-&gt;toArray());

        $profiler = new Zend_Db_Profiler_Firebug('All DB Queries');
        $profiler-&gt;setEnabled(true);
        $db-&gt;setProfiler($profiler);

        $db-&gt;query(&quot;SET NAMES 'utf8'&quot;);

        self::$registry-&gt;database = $db;
        Zend_Db_Table::setDefaultAdapter($db);

        if (!isset($dissableCache) &amp;&amp; $dissableCache !== true) {
            $frontendOptions = array(
                'automatic_serialization' =&gt; true
                );


                $backendOptions  = array(
                    'cache_dir' =&gt; self::$root . '/data/cache/db_table'
                );

            $cache = Zend_Cache::factory('Core',
                                         'File',
                                         $frontendOptions,
                                         $backendOptions);


            // Next, set the cache to be used with all table objects
            Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
        }
    }


    public static function setupSessions(){
        if (isset($_POST[&quot;PHPSESSID&quot;])) {
            session_id($_POST[&quot;PHPSESSID&quot;]);
        }

        // Now set session save handler to our custom class which saves the data in MySQL database
        $sessionManager = new GSD_Session_Manager();
        Zend_Session::setOptions(array(
            'gc_probability' =&gt; 1,
            'gc_divisor' =&gt; 5000
            ));
        Zend_Session::setSaveHandler($sessionManager);

        $defSession = new Zend_Session_Namespace('Main', true);
        Zend_Registry::set('defSession', $defSession);
    }


    public static function setupTranslation(){
        $options = array(
                    'scan' =&gt; Zend_Translate::LOCALE_FILENAME,
                    'disableNotices' =&gt; true,
                    );
        $translate = new Zend_Translate('gettext', Zend_Registry::get('siteRootDir') . '/application/languages/', 'auto', $options);
        Zend_Registry::set('Zend_Translate', $translate);

    }


    public static function setupRoutes(){
        // define some routes (URLs)
        $router = self::$frontController-&gt;getRouter();

        $config = new Zend_Config_Ini(
            self::$root . '/application/config/routes.ini',
            'development'
        );

        $router-&gt;addConfig($config, 'routes');
    }


    public static function setupAcl(){
        self::$frontController-&gt;registerPlugin(new GSD_Controller_Plugin_Acl());
    }

    public static function setupDebug() {
        $scBar = new Scienta_Controller_Plugin_Debug(array(
           'database_adapter' =&gt;  self::$registry-&gt;database, // or array of adapters
           'memory_usage' =&gt;      TRUE, // default value shown
           'collect_view_vars' =&gt; TRUE,
           'sort_view_vars' =&gt;    TRUE,
           'show_exceptions' =&gt;   TRUE,
           'handle_errors' =&gt;     FALSE
        ));
        self::$frontController-&gt;registerPlugin($scBar);
    }
} </code></pre>]]></description>
      <pubDate>Thu, 02 Apr 2009 11:54:09 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Zend_Search_Lucene simple index script]]></title>
      <link>http://zfsnippets.com/snippets/view/id/53</link>
      <guid>http://zfsnippets.com/snippets/view/id/53</guid>
      <description><![CDATA[<p>This is the script I knocked up for the coming soon site search.<br />
</p><pre><code>// Foreach snippet

define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application/'));

set_include_path(
    APPLICATION_PATH . '/../library'
    . PATH_SEPARATOR . get_include_path()
);

require_once &quot;Zend/Loader.php&quot;;
Zend_Loader::registerAutoload();

try {
    require '../application/bootstrap.php';
} catch (Exception $exception) {
    echo 'Bootstrapping failed' . $exception-&gt;getMessage();
    exit(1);
}


require_once APPLICATION_PATH . '/models/Snippet.php';
$model = new Model_Snippet;
$model-&gt;setUsePaginator(false);

$client = new Zend_Http_Client();
$client-&gt;setConfig(array(
    'maxredirects' =&gt; 0,
    'timeout'      =&gt; 30));

if (is_file(APPLICATION_PATH . '/data/search/index')) {
    $index = Zend_Search_Lucene::open(APPLICATION_PATH . '/../data/search/index');
} else {
    $index = Zend_Search_Lucene::create(APPLICATION_PATH . '/../data/search/index');
}

foreach($model-&gt;fetch() as $snip) {
    $url = Zend_Registry::get('configuration')-&gt;app-&gt;url . 'snippets/view/id/' . $snip-&gt;snippet_id;
    $client-&gt;setUri($url);
    $response = $client-&gt;request();

    if ($response-&gt;isSuccessful()) {
        $doc = Zend_Search_Lucene_Document_Html::loadHTML($response-&gt;getBody());
        $doc-&gt;addField(Zend_Search_Lucene_Field::UnIndexed('indexed', time())); 
        $doc-&gt;addField(Zend_Search_Lucene_Field::UnIndexed('id', $snip-&gt;snippet_id));

        $index-&gt;addDocument($doc);
    }
}

$index-&gt;commit();

echo $index-&gt;count(), &quot; Documents indexed.&quot;, PHP_EOL;
</code></pre>]]></description>
      <pubDate>Mon, 30 Mar 2009 08:13:30 +0000</pubDate>
    </item>
    <item>
      <title><![CDATA[Firebug View Helper]]></title>
      <link>http://zfsnippets.com/snippets/view/id/52</link>
      <guid>http://zfsnippets.com/snippets/view/id/52</guid>
      <description><![CDATA[<p>A small helper to make using Firefox Firebug extension more easy.<br />
<br />
It requires some configs in your bootstrap file.</p><pre><code>class GSD_View_Helper_Fb extends Zend_View_Helper_Abstract{

    public function fb($message, $label=null){
        if ($label!=null) {
            $message = array($label,$message);
        }
        Zend_Registry::get('logger')-&gt;err($message);
    }

}

</code></pre><h3></h3><pre><code>
$writer = new Zend_Log_Writer_Firebug();
$logger = new Zend_Log($writer);
		Zend_Registry::set('logger',$logger);</code></pre>]]></description>
      <pubDate>Sun, 29 Mar 2009 11:26:45 +0000</pubDate>
    </item>
  </channel>
</rss>
