Create Custom Toolbar for ZendDeveloperTools - Zend Framework 2

In this article, we are going to discuss about How to create custom Toolbar for ZendDeveloperTools using Zend Framework 2. ZendDeveloperTools toolbars are great to help us debug our application. However, when we need to have additional toolbar that not yet in it, we need to add it by creating custom toolbar for it. Ok, for example, we want to add a session toolbar that read our current session Container key -> value like this :


To make it easy to learn, let's apply it into new module, I created a new module for it named SanSessionToolbar like the following :


1. Start with the Collector :

namespace SanSessionToolbar\Collector;

use ZendDeveloperTools\Collector\CollectorInterface;
use Zend\Mvc\MvcEvent;
use Zend\Session\Container;

/**
 * Session Data Collector.
 */
class SessionCollector implements CollectorInterface
{
    /**
     * @inheritdoc
     */
    public function getName()
    {
         // this name must same with *collectors* name in the configuration
        return 'session.toolbar';
    }

    /**
     * {@inheritDoc}
     */
    public function getPriority()
    {
        return 10;
    }

    /**
     * @inheritdoc
     */
    public function collect(MvcEvent $mvcEvent)
    {
    }
   
    public function getSessionData()
    {
        $container = new Container;
        $arraysession = $container->getManager()->getStorage()->toArray();
       
        $data = array();
        foreach($arraysession as $key => $row) {
            if ($row instanceof \Zend\Stdlib\ArrayObject) {
                $iterator = $row->getIterator();
                while($iterator->valid()) {
                    $data[$iterator->key()] =  $iterator->current() ;
                    $iterator->next();
                }
            }
        }
       
        return $data;
    }
}

2. Now, create a view to var_dump the
SanSessionToolbar\Collector\SessionCollector::getSessionData().

<?php /* @var $collector \SanSessionToolbar\Collector\SessionCollector */ ?>
<div class="zdt-toolbar-entry">
    <div class="zdt-toolbar-preview">
        <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAATxJREFUeNpi/P//PwMhMJuRkRVItQNxKhBzAPFOIM5O/f//MbpaFgbiAMigYiS+LxCDXOKPrpCJSAP1sYiZY1NIrIGHsYhtw6aQWC8vA2IlIM4EYn6oYRXYFDISEylokQOKlG/ACPlLsguBBggAKRUglgbi70B8EWjQS3x6sLoQaFAikLIDYjcglkKSegHEGUBDN+IyEFekeAOxJRBfAeJPSOISQDwZaKEYSS5Ec20KiEITVgW68g65yeYHAwmAGAN90PgPgPgjWQZCw8oOTXgX0LuvyXWhBxBLIvFBaW8zJV52RePfA+LdZBkI9K44kHJAEz4G9O5Pcl3IA8QyaGJHKYllRixiylDXywCxFKkGvgPiG2hiJUCDQHn5PhBbkGQgMKxABsYC8UEg/grFH4D4BBDHA/EebPoAAgwA3RZUHjvT8+IAAAAASUVORK5CYII=" alt="SESSION Data">
        <span class="zdt-toolbar-info">
                SessionData    
        </span>
    </div>
    <div class="zdt-toolbar-detail">
        <span class="zdt-toolbar-info zdt-toolbar-info-redundant">
            <span class="zdt-detail-label">Session Data</span>
        </span>
        <span class="zdt-toolbar-info">
            <span class="zdt-detail-pre">
                <?php Zend\Debug\Debug::dump($collector->getSessionData()); ?>
            </span>
        </span>
    </div>
</div>

3. Configure the module configuration ( config/module.config.php ), Remember, that the toolbar entries name must same with our SessionCollector::getName().

return array(
   
    'service_manager' => array(
        'invokables' => array(
            'session.toolbar' =>
                'SanSessionToolbar\Collector\SessionCollector',
        ),
    ),
   
    'view_manager' => array(
        'template_map' => array(
            'zend-developer-tools/toolbar/session-data'
                => __DIR__ . '/../view/zend-developer-tools/toolbar/session-data.phtml',
        ),
    ),
       
    'zenddevelopertools' => array(
        'profiler' => array(
            'collectors' => array(
                'session.toolbar' => 'session.toolbar',
            ),
        ),
        'toolbar' => array(
            'entries' => array(
                'session.toolbar' => 'zend-developer-tools/toolbar/session-data',
            ),
        ),
    ),
   
);

The 'session.toolbar' must be registered into ServiceManager with an instance of SanSessionToolbar\Collector\SessionCollector, and registered into 'zenddevelopertools' config profiler and toolbar.

4. The Module.php is a usual Module class.

5. Register your new module into config/application.config.php

6. Now, let's test it by creating session data in our controller :

public function indexAction()
{
    $container = new \Zend\Session\Container;
    $container->a   = 'b';
    $container->foo = 'bar';
   
    return new ViewModel();
}

Source :

https://samsonasik.wordpress.com/2014/06/27/zend-framework-2-create-custom-toolbar-for-zenddevelopertools/

Reference :

  1. http://stackoverflow.com/questions/20325842/how-to-log-something-to-zend-developer-tools-toolbar
  2. Image session icon originally from : http://makemore.info.yorku.ca/files/2012/11/info.png, encoded with base64_encode.

Symfony 2 - Use Dependency Injection as a standalone component

In this article, we are going to discuss about How to use the Dependency Injection component as a standalone component without using the whole Symfony 2 framework. I will also use ClassLoader from Symfony and just for the sake of the demo I will integrate it with Zend Framework. The code requires PHP 5.3 (mostly for namespaces support).

Create a directory for your project. Inside create "lib" directory. Inside lib, create directory structure: Symfony/Component. Put ClassLoader code inside Component – the easiest thing to do is to clone if from Symfony github:

cd lib/Symfony/Component
git clone https://github.com/symfony/ClassLoader.git

The same goes for DependencyInjection component:

cd lib/Symfony/Component
git clone https://github.com/symfony/DependencyInjection.git

Finally download Zend Framework and put the contents of Zend directory into lib/Zend (so for instance Log.php file will be available in lib/Zend/Log.php).

The actual source code will go into "src" directory, which is a sibling directory of "lib".

Configuring the ClassLoader

DependencyInjection uses namespaces for managing classes, so it needs to be registered with registerNamespace method. Zend Framework follows PEAR naming convention for classes – registerPrefix will do the work for us. Finally, I will register our own code that will be stored in src directory. I will use namespaces as well. Create a new file (let's call it main.php) in the top-level directory:

require_once('lib/Symfony/Component/ClassLoader/UniversalClassLoader.php');

$loader = new Symfony\Component\ClassLoader\UniversalClassLoader();
$loader->registerNamespace('PHPCmsframework',__DIR__.'/src');
$loader->registerNamespace('Symfony',__DIR__.'/lib');
$loader->registerPrefix('Zend',__DIR__.'/lib');
$loader->register();

set_include_path(get_include_path().PATH_SEPARATOR.__DIR__.'/lib');

ClassLoader should now work just fine but we still need set_include_path so require functions inside Zend code will work correctly.

Dependency Injection container

Create a sample class that we'll use for testing. I will call it Test and put it into PHPCmsframework\Techblog, which means it should be located at src/PHPCmsframework/Techblog/Test.php:

namespace PHPCmsframework\Techblog;

class Test
{
    private $logger;

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

    public function run() {
     $this->logger->info("Running...");
    }
}

$logger should be injected using container – here is where we will use Zend_Log class. This one in turn requires a Writer, so we will create it as well. The rest of main.php will look like this:

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

$sc = new ContainerBuilder();

$sc->register('log.writer','Zend_Log_Writer_Stream')
    ->addArgument('php://output');
$sc->register('logger', 'Zend_Log')
    ->addArgument(new Reference('log.writer'));
$sc->register('test','PHPCmsframework\Techblog\Test')
    ->addArgument(new Reference('logger'));

$sc->get('test')->run();

Running the code should give an output like below:

% php main.php 
2011-06-09T15:17:22+01:00 INFO (6): Running...

Zend Framework - Content Indexing using Zend_Search_Lucene component

In this article, we are going to discuss about in Zend Framework How to index the content using Zend_Search_Lucene component. Lucene is indexing and retrieval library that originally was developed in Java technology and supported by the Apache Software Foundation. When the data has been indexed in the file system, it does not require a database server. Zend_Search_Lucene is one of the components of the Zend Framework that implements this technology.

Zend_Search_Lucene supports the following features:

  1. Ranking of search results 
  2. Powerful query types: Boolean, wildcard, phrase queries 
  3. Search by specific field


Ok, let's go to the example:

Suppose we have data that we store the article in our index file system. We have a call controller Zend_Search_Lucene components as follows:

class TestluceneController extends Zend_Controller_Action
{
    public function init()
    {
        /* Initialize action controller here */
        $this->indexPath = APPLICATION_PATH.'/indexsearch/index';
    }
}

In the init function, we declare the path where we store the index. If so, we created an action to index data from the database, such as the following:

//...................
public function reindexAction()
{
    // action body
    //just SAMPLE , access to db
    // ( in your REAL DEVELOPMENT, access to db is only in model ) !!!!
    //asumption , 'db' is already registered in registry !!!
    $db = Zend_Registry::get('db');
    $fetch = $db->query("select * from articles")->fetchAll();

    $index = Zend_Search_Lucene::create($this->indexPath);

    foreach($fetch as $key=>$row)
    {
        $doc = new Zend_Search_Lucene_Document();
        $doc->addField(Zend_Search_Lucene_Field::Text('title', $row['title']));
        $doc->addField(Zend_Search_Lucene_Field::UnStored('content', $row['content'] ));

        $index->addDocument($doc);
        echo 'Added ' . $row['title'] . ' to index.
';
    }
    //optimize index...
    $index->optimize();

    die;
}
//................................

Well, we run the action reindexAction first before attempting to scan the data. If so, now we can test:

//.......Search data is already indexed.
public function searchAction()
{
    $data  = array();

    // If a search_query parameter has been posted, search the index.
    $indexopen = Zend_Search_Lucene::open($this->indexPath);
     // Get results.
    $data  = $indexopen->find('"PHP framework" AND "Zend Framework"');
    foreach($data as $key=>$row)
    {
        echo $row->title; echo "<br>";
    }
    die;
}
//......................

Steps to install Zend Framework on Ubuntu 12.04 VPS

In this article, we are going to discuss about the step by step procedure to install Zend Framework on Ubuntu 12.04 VPS. Zend is one of the best PHP Framework. Zend Framework (ZF) is a powerful web application framework that is sponsored by Zend Technologies. ZF has lots of features like support for multiple database systems, a nice caching system, a "loosely coupled" architecture (meaning components have minimal dependency on each other), and is enterprise ready as advertised.

Prerequisites:

LAMP stack should be installed on your Ubuntu VPS. It should work equally well on other Linux distros with LAMP stack. We will be installing with Zend Framework 1 as it is more widely used and has more educational material available.

ZF requires that you have enabled mod_rewrite. You can do it by typing this command:

a2enmod rewrite

Installation:

Latest version of ZF1 branch is 1.12.7.

Change into home directory:

cd /home

and get the ZF1 installation,

wget https://packages.zendframework.com/releases/ZendFramework-1.12.7/ZendFramework-1.12.7.tar.gz

Extract the archive with the command:

tar -xvzf ZendFramework-1.12.7.tar.gz

After this, we should inform php5 interpreter of our Zend library by changing php.ini. It is located in: /etc/php5/apache2:

nano /etc/php5/apache2/php.ini

Find the line:

;include_path = ".:/usr/share/php"

and change it with:

include_path = ".:/home/ZendFramework-1.12.7/library"

Then save the changes and exit.

ZF1 comes with a command line tool to easily create projects, models, controllers, and other useful actions related to your Zend application. We should make our terminal aware of this tool. We will change into root directory and edit our .bashrc file then source it.

cd /root
nano .bashrc

Now, add the line below to the end of the file:

alias zf=/home/ZendFramework-1.12.7/bin/zf.sh

Save the file and exit.

Source your .bashrc file so that the terminal is now aware of our ZF tool and zf command.

source .bashrc

Creating Your First Application

We will begin to create our first project. Change into /var/www directory.

cd /var/www

Let's create our first project named ZendApp. We have a few steps until we can see our project is running, so don't worry if you don't see anything when you visit http://youripadress

zf create project ZendApp

This command creates the related project files for our project "ZendApp". It has several subdirectories and one of them, "public", is where our web server should be pointed to.

This is done by changing our settings as the default web root directory. Go to your Apache settings directory which has the settings for the currently enabled sites:

cd /etc/apache2/sites-enabled

You can optionally backup your default settings file with the command:

cp 000-default 000-default.bck

Now change the contents of "000-default":

nano 000-default

with the lines below:

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot /var/www/ZendApp/public

    SetEnv APPLICATION_ENV "development"

    <Directory /var/www/ZendApp/public>
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

We are done. Restart apache:

service apache2 restart

Thats all... !

Steps to create JQuery form in Zend Framework

In this tutorial, we are going to discuss about How to create jQuery form in Zend framework. I'm here to show you how to use JQuery extension provide with latest version of Zend Framework for creating wonderful JQuery form. You will need to follow the steps bellow to create JQuery form.

  1. Placing ZendX directory in right place
  2. Make necessary configuration in bootstrap file
  3. Write necessary code in your layout.phtml file.
  4. Create JQuery form
  5. Show that form in the template.

Step 1 : Placing ZendX directory in right place

When you download latest version of Zend Framework and extract the zip file. You will see a directory called "extras". When open that directory you will find ZendX folder. Copy this to your Library/ folder at the same level of your Zend directory. You directory structure will be like this.

Library/
    Zend/
    ZendX/
   
Step 2 : Making necessary configuration in bootstrap

After placing the directory you will need to add a bit of code in your bootstrap file. Add the following lines to your bootstrap file.

$view = new Zend_View();
$view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);

In the code above, we instantiate our Zend_View object, set helper path, add view to the viewRenderer and finally add viewRenderer the helper broker. Keep in mind that if you have already instantiate Zend view in your bootstrap, you don't need to instantiate it twice.

Step 3: Write necessary code in your layout.phtml file

The only line you will need to include in your layout file is

echo $this->jQuery();

If you don't use two step view, you can include this line at the top of each of your view template file instead.

Step 4: Create JQuery form

Now you have done all the necessary configuration, its time to create the actual form. Create JQuery form in Zend framework is piece of cake. If you want to create form in your controller, write the following code.

$form = new ZendX_JQuery_Form();
$date1 = new ZendX_JQuery_Form_Element_DatePicker(
                        'date1',
                        array('label' => 'Date:')
        );
$form->addElement($date1);
$elem = new ZendX_JQuery_Form_Element_Spinner(
                    "spinner1", 
                    array('label' => 'Spinner:')
        );
$elem->setJQueryParams(array(
                'min' => 0,
                'max' => 1000,
                'start' => 100)
        );
$form->addElement($elem);
$this->view->form = $form;

In the code above we have created our JQuery form object, and add two element date and spinner to it. And then assigned the form to the view template file. Although you can create the form in your controller, however I will strongly discourage it. I will prefer using separate php file and add following code to that file.

class JQueryForm extends ZendX_JQuery_Form
{
    public function init()
    {
        $this->setMethod('post');
        $this->setName('frm');
        $this->setAction('path/to/action');
        
        $date1 = new ZendX_JQuery_Form_Element_DatePicker(
                'date1',
                array('label' => 'Date:')
             );
             
        $this->addElement($date1);
        
        $elem = new ZendX_JQuery_Form_Element_Spinner(
                "spinner1", 
                array('label' => 'Spinner:')
        );
        
        $elem->setJQueryParams(array('min' => 0, 'max' => 1000, 'start' => 100));
        $this->addElement($elem);
    }
}

We have extended our form from ZendX_JQuery_Form, set its method, name and action and add two elements date and spinner. Now in your controller/action

$form = new JQueryForm();
$this->view->form = $form;

Step 5 : Showing form in the template

In your view template file add only the following line.

<?php
echo $this->form;
?>

Zend Form - Existing Email Address checking in Database

In this tutorial, we are going to discuss about How to check the existing email address in database in zend form. If you are creating a user registration form, you will either want to check if a username or an email address is already exist in the database. This is very easy to do, assuming you are familiar with using Zend_Form:

$validator = new Zend_Validate_Db_NoRecordExists('user', 'email'); // user is the table name, and email is the column
    $validator->setMessage("Error: The e-mail has already been registered"); // set your own error message
    $this->addElement('text', 'email', array(
       'label' => 'E-mail Address',
       'required' => true,
       'filters' => array('StringTrim'),
       'validators' => array(
           'EmailAddress',
           $validator
       )
));

That's all.

NOTE: This might be obvious but you cannot chain the setMessage(…) function directly to the end of new Zend_Validate_Db_NoRecordExists('user', 'email');

If you are not familiar Zend_Form, here's a full example:

/* application/forms/Register.php */
class Default_Form_Register extends Zend_Form {
public function init($options = null) {
$this->setMethod('post');
$this->addElement('text', 'firstName', array(
'label' => 'First Name',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'StringLength', 'options' => array(1, 255))
)
));
$this->addElement('text', 'lastName', array(
'label' => 'Last Name',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
array('validator' => 'StringLength', 'options' => array(1, 255))
)
));

        $validator = new Zend_Validate_Db_NoRecordExists('user', 'email');
$validator->setMessage("Error: The e-mail has already been registered");
$this->addElement('text', 'email', array(
'label' => 'E-mail Address',
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
'EmailAddress',
$validator
)
));

$password = $this->addElement('password', 'password', array(
'filters' => array('StringTrim'),
'validators' => array(
array('StringLength', false, array(8, 20)),
),
'required' => true,
'label' => 'Password',
'id' => 'password'
));

$register = $this->addElement('submit', 'register', array(
'required' => false,
'ignore' => true,
'label' => 'Register Now',
));
}

Extending ZfcUser module in Zend Framework 2

In this article, we are going to discuss about How to extend the ZfcUser module in Zend Framework 2. ZfcUser is a user registration and authentication module for Zend Framework 2. Out of the box, ZfcUser works with Zend\Db, however alternative storage adapter modules are available (see below). ZfcUser provides the foundations for adding user authentication and registration to your ZF2 site. It is designed to be very simple and easily to extend.

Creating Zend Framework 2 module

Zend Framework 2 uses a module system and we can organize our main application-specific code within each module.

The module system in ZF2 has been designed to be a generic and powerful foundation from which developers and other projects can build their own module or plugin systems.

The easiest way to create a new module is by using ZFTool. I think the easiest way to install it is to use a .phar file from that site and just pur it in your /vendor folder inside your project directory.

After you downloaded/installed ZFTool, run this in your console (I ran it inside vendor directory, if you are running from somewhere else, be sure to adjust the last parameter which is path to your project directory):

zftool.phar create module Blog ./

This will create a module called Blog with all the necessary folders and files needed for a module to function. It will also add your newly created module to modules array in your application.config.php file.

If you go to zf2blog.home/blog now, you will get an 404 error, which is fine as we don't have a controller and views for our module yet.

So, let's first adjust that, open /module/Blog/config/module.config.php and make it look like this:

return array(
        'controllers' => array(
                'invokables' => array(
                        'Blog\Controller\Blog' => 'Blog\Controller\BlogController'
                ),
        ),
        'view_manager' => array(
                'template_path_stack' => array(
                        'blog' => __DIR__ . '/../view',
                ),
        ),
);

Preparing Blog module

Let's prepare Blog module for further work. We will first add some routes to our module config file:

/module/Blog/config/module.config.php

...
// Routes
        'router' => array(
                'routes' => array(
                        'blog' => array(
                                'type'    => 'segment',
                                'options' => array(
                                        'route'    => '/blog[/:action][/:id]',
                                        'constraints' => array(
                                                'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                                'id'     => '[0-9]+',
                                        ),
                                        'defaults' => array(
                                                'controller' => 'Blog\Controller\Blog',
                                                'action'     => 'index',
                                        ),
                                ),
                        ),
                ),
        ),

...

Now, we need a Blog Controller and it's index Action and index view, so create


/module/Blog/src/Controller/BlogController.php

<?php
namespace Blog\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class BlogController extends AbstractActionController
{
    /**
     * (non-PHPdoc)
     * @see \Zend\Mvc\Controller\AbstractActionController::indexAction()
     */
    public function indexAction()
    {
        return new ViewModel();
    }

}

and also create the view:


/module/Blog/view/blog/blog/index.phtml

<div class="page-header">
    <h1><?php echo $this->translate('Blog'); ?></h1>

</div>

That's it, if you point your browser to zf2blog.home/blog, you will see that it works.

Extending ZfcUser views

Let us now adjust ZfcUser views to Twitter Bootstrap 3 which is used in Zend Skeleton application we used. To override ZfcUser module's views, we just need to create a proper folders in our module's views folder and put the ZfcUser views we wish to override inside.

So create /module/Blog/view/zfc-user/user folder and add following files to it:

/module/Blog/view/zfc-user/user/register.phtml:

<div class="page-header">
    <h1><?php echo $this->translate('Register'); ?></h1>
</div>

<?php
if (!$this->enableRegistration) {
    print "Registration is disabled";
    return;
}
$form = $this->registerForm;
$form->prepare();
$form->setAttribute('action', $this->url('zfcuser/register'));
$form->setAttribute('method', 'post');
echo $this->form()->openTag($form);
?>

<?php foreach ($form as $element) : ?>

    <div style="width: 330px;" class="form-group <?php if ($this->formElementErrors($element)) echo "has-error" ?>">
        <?php
            if ('submit' != $element->getAttribute('type')) { ?>
                <label class="control-label"><?php echo $element->getLabel() ?></label>
                <?php
                $element->setAttribute('class', 'form-control')
                        ->setAttribute('placeholder', $element->getLabel());
            } else {
                $element->setAttribute('class', 'btn btn-success');
            }
            if ($element instanceof Zend\Form\Element\Captcha) {
                echo $this->formCaptcha($element);
            } else {
                echo $this->formElement($element);
            }
            if ($this->formElementErrors($element)) : ?>
                <?php
                echo $this->formElementErrors()
                    ->setMessageOpenFormat('<p class="help-block">')
                    ->setMessageSeparatorString('</p><p class="help-block">')
                    ->setMessageCloseString('</p>')
                    ->render($element);
                ?>
            <?php endif; ?>
    </div>

<?php
endforeach;
    if ($this->redirect): ?>
        <input type="hidden" name="redirect" value="<?php echo $this->escapeHtml($this->redirect) ?>" />
    <?php endif ?>

<?php echo $this->form()->closeTag() ?>

/module/Blog/view/zfc-user/user/login.phtml:

<div class="page-header">
    <h1><?php echo $this->translate('Sign in'); ?></h1>
</div>

<?php
$form = $this->loginForm;
$form->prepare();
$form->setAttribute('action', $this->url('zfcuser/login'));
$form->setAttribute('method', 'post');
?>

<?php echo $this->form()->openTag($form) ?>
<?php foreach ($form as $element) : ?>

    <div style="width: 330px;" class="form-group <?php if ($this->formElementErrors($element)) echo "has-error" ?>">
        <?php
            if ('submit' != $element->getAttribute('type')) { ?>
                <label class="control-label"><?php echo $element->getLabel() ?></label>
                <?php
                $element->setAttribute('class', 'form-control')
                        ->setAttribute('placeholder', $element->getLabel());
            } else {
                $element->setAttribute('class', 'btn btn-success');
            }
            echo $this->formElement($element);
            if ($this->formElementErrors($element)) : ?>
                <?php
                echo $this->formElementErrors()
                    ->setMessageOpenFormat('<p class="help-block">')
                    ->setMessageSeparatorString('</p><p class="help-block">')
                    ->setMessageCloseString('</p>')
                    ->render($element);
                ?>
            <?php endif; ?>
    </div>

<?php
endforeach;

echo $this->form()->closeTag() ?>

<?php if ($this->enableRegistration) : ?>
<?php echo $this->translate('Not registered?'); ?> <a href="<?php echo $this->url('zfcuser/register') . ($this->redirect ? '?redirect='.$this->redirect : '') ?>"><?php echo $this->translate('Sign up!'); ?></a>

<?php endif; ?>

/module/Blog/view/zfc-user/user/index.phtml:

<div class="page-header">
    <h1><?php echo $this->translate('User details'); ?></h1>
</div>
<div class="container">
<div class="row">
<div style="float:left; padding-right:16px;"><?php echo $this->gravatar($this->zfcUserIdentity()->getEmail()) ?></div>
<h3><?php echo $this->translate('Hello'); ?>, <?php echo $this->zfcUserDisplayName() ?>!</h3>
<a href="<?php echo $this->url('zfcuser/logout') ?>">[<?php echo $this->translate('Sign Out'); ?>]</a>
</div>
</div>

/module/Blog/view/zfc-user/user/changepassword.phtml:

<?php echo $this->form()->closeTag(); ?>
<div class="page-header">
    <h1><?php echo sprintf($this->translate('Change Password for %s'), $this->zfcUserDisplayName()); ?></h1>
</div>
<?php if ($status === true) : ?>
<div class="alert alert-success"><?php echo $this->translate('Password changed successfully.');?></div>
<?php elseif ($status === false) : ?>
<div class="alert alert-danger"><?php echo $this->translate('Unable to update your password. Please try again.'); ?></div>
<?php endif; ?>
<?php
    $form = $this->changePasswordForm;

    $form->prepare();
    $form->setAttribute('action', $this->url('zfcuser/changepassword'));
    $form->setAttribute('method', 'post');

    $emailElement = $form->get('identity');
    $emailElement->setValue($this->zfcUserIdentity()->getEmail());

    echo $this->form()->openTag($form);
?>

<?php foreach ($form as $element) : ?>

    <div style="width: 330px;" class="form-group <?php if ($this->formElementErrors($element)) echo "has-error" ?>">
        <?php
            if ('submit' != $element->getAttribute('type')) { ?>
                <label class="control-label"><?php echo $element->getLabel() ?></label>
                <?php
                $element->setAttribute('class', 'form-control')
                        ->setAttribute('placeholder', $element->getLabel());
            } else {
                $element->setAttribute('class', 'btn btn-success');
            }
            if ($element instanceof Zend\Form\Element\Captcha) {
                echo $this->formCaptcha($element);
            } else {
                echo $this->formElement($element);
            }
            if ($this->formElementErrors($element)) : ?>
                <?php
                echo $this->formElementErrors()
                    ->setMessageOpenFormat('<p class="help-block">')
                    ->setMessageSeparatorString('</p><p class="help-block">')
                    ->setMessageCloseString('</p>')
                    ->render($element);
                ?>
            <?php endif; ?>
    </div>

<?php
endforeach;?>
<?php if ($this->redirect): ?>
        <input type="hidden" name="redirect" value="<?php echo $this->escapeHtml($this->redirect) ?>" />
    <?php endif ?>
<?php echo $this->form()->closeTag() ?>

/module/Blog/view/zfc-user/user/changeemail.phtml:

<div class="page-header">
    <h1><?php echo sprintf($this->translate('Change Email for %s'), $this->zfcUserDisplayName()); ?></h1>
</div>
<?php if ($status === true) : ?>
<div class="alert alert-success"><?php echo $this->translate('Email address changed successfully.'); ?></div>
<?php elseif ($status === false) : ?>
<div class="alert alert-danger"><?php echo $this->translate('Unable to update your email address. Please try again.'); ?></div>
<?php endif; ?>
<?php
    $form = $this->changeEmailForm;

    $form->prepare();
    $form->setAttribute('action', $this->url('zfcuser/changeemail'));
    $form->setAttribute('method', 'post');
    echo $this->form()->openTag($form);
?>

<?php foreach ($form as $element) : ?>

    <div style="width: 330px;" class="form-group <?php if ($this->formElementErrors($element)) echo "has-error" ?>">
        <?php
            if ('submit' != $element->getAttribute('type')) { ?>
                <label class="control-label"><?php echo $element->getLabel() ?></label>
                <?php
                $element->setAttribute('class', 'form-control')
                        ->setAttribute('placeholder', $element->getLabel());
            } else {
                $element->setAttribute('class', 'btn btn-success');
            }
            if ($element instanceof Zend\Form\Element\Captcha) {
                echo $this->formCaptcha($element);
            } else {
                echo $this->formElement($element);
            }
            if ($this->formElementErrors($element)) : ?>
                <?php
                echo $this->formElementErrors()
                    ->setMessageOpenFormat('<p class="help-block">')
                    ->setMessageSeparatorString('</p><p class="help-block">')
                    ->setMessageCloseString('</p>')
                    ->render($element);
                ?>
            <?php endif; ?>
    </div>

<?php
endforeach;?>
<input class="btn btn-success" type="submit" value="Submit" />
<?php if ($this->redirect): ?>
        <input type="hidden" name="redirect" value="<?php echo $this->escapeHtml($this->redirect) ?>" />
    <?php endif ?>
<?php echo $this->form()->closeTag() ?>


This code is adjusting ZfcUser forms to Twitter Bootstrap markup. If you now go to zf2blog.home/user/register, you will see that the form looks awesome now. Even the validation messages looks better (try to submit the register form without entering the username).

Simple Form Validator For Zend Framework 2 Forms

In this article, we are going to discuss about How to implement the form validator in the Zend Framework 2 forms. Zend Framework is based on simplicity, object-oriented best practices, corporate friendly licensing, and a rigorously tested agile codebase.

Zend Framework is focused on building more secure, reliable, and modern Web 2.0 applications & web services, and consuming widely available APIs from leading vendors like Google, Amazon, Yahoo!, Flickr, as well as API providers and cataloguers like StrikeIron and Programmable Web.

Here is some extended core helping to auto validate Zend Framework 2 Forms.

Step 1 : Extending Zend Framework 2 Form.

<?php
//File : App_folder/module/Module_name/src/Module_name/Form/ExtendedForm.php
namespace Application\Form;
use Zend\Form\Form;

class ExtendedForm extends Form {
    protected $_name;
    protected $_rawElements = array();
    public function __construct($name = null) {
        parent::__construct($name);

    }
    public function isValid($request = null) {
        $this->__addValidator();
        if ($request -> isPost()) {
            $query = $request -> getQuery();
            $query = is_object($query) ? $query->toArray() : $query;
            $post = $request -> getPost();
            foreach($post as $var=>$value){
                $query[$var] = $value;
            }
            $this -> setData($query);
            return parent::isValid();
        } else {
            return false;
        }
    }
    public function add($elementOrFieldset, array $flags = array()) {
        $form = parent::add($elementOrFieldset, $flags);
        $this->_rawElements[] = $elementOrFieldset;
        return $form;
    }
    private function __addValidator() {
        $this -> setInputFilter(new ExtendedFormValidator($this->_rawElements));
    }

}

Step 2 : Creating Zend Framework 2 Form validator

//File : App_folder/module/Module_name/src/Module_name/Form/ExtendedFormValidator.php
namespace Application\Form;
use Zend\InputFilter\InputFilter;

class ExtendedFormValidator extends InputFilter {

    public function __construct($elements) {
        foreach ($elements as $element) {
            if (is_array($element)) {
                if (isset($element['type'])) {
                    unset($element['type']);
                }
                $this -> add($element);
            }
        }
    }

}

Step 3 : Creating simple Zend Framework 2 Form and extending it with ExtendedForm

//File : App_folder/module/Module_name/src/Module_name/Form/ResendPassword.php
namespace Application\Form;

class ResendPassword extends ExtendedForm
{
    public function __construct($name = null)
    {

        parent::__construct('login');
        $this->setAttribute('method', 'post');

        $this->add(array(
            'required'=>true,
            'name' => 'usermail',
            'type'  => 'Zend\Form\Element\Text',
            'options' => array(
                'label' => 'Email',
            ),
            'filters'=>array(
                array('name'=>'StripTags'),
                array('name'=>'StringTrim'),
            ),
            'validators'=>array(
                array('name'=>'EmailAddress')
            ),

        ));

        $this->add(array(
            'name' => 'submit',
            'type' => 'Zend\Form\Element\Text',
            'attributes' => array(
                'type'  => 'submit',
                'value' => 'Submit',
                'id' => 'submitbutton',
            ),
        ));
    }
}

Step 4 : Instantiating the Zend Framework 2 Form.

//File : App_folder/module/Module_name/src/Module_name/Controller/IndexController.php
use Application\Form as Form; //at the top of the file.

public function forgotAction(){

    $form = new Form\ResendPassword();
    if($form->isValid($this->getRequest())){
          //do your magic
    }
    return new ViewModel(array('form'=>$form));  
}

Step 5 : Rendering Zend Framework 2 Form in the View.

//File : App_folder/module/Module_name/View/Module_name/index/index.phtml
$form =  $this->form;
$form->prepare();

echo $this->view->form()->openTag($form) . PHP_EOL;
$elements = $form->getElements();
foreach($elements as $element){
    echo $this->view->formRow($element) . PHP_EOL;
}
echo $this->view->form()->closeTag($form) . PHP_EOL;

Change the ErrorController to work with AJAX in Zend Framework

In this article, we are going to discuss about How to change the ErrorController to work with AJAX in Zend Framework. Zend Framework is mostly used for web application. By deafult, in Zend Framework we have a set of default ErrorControllers. If we create a web application using Zend app which makes AJAX calls , it will notify that if an error occurs, we'll get a chunk of JSON followed by the HTML for the error page. This is fine if our users hit the page in the browser but it can cause problems with our JavaScript being able to correctly decode your JSON.

By changing the ErrorController, we can easily get the JSON by using the AJAX call.

Open the file "/application/controllers/ErrorController.php". In this we need to register the errorAction in an AJAX context. It will tell the Zend Framework that if it detects an XML HTTP Request and there's a parameter called "format" with a value of "json" that it should automatically turn off the view and the layout. This will leave us with just the JSON part of the response.

If you don't have an init method in your ErrorController class, create one like this:

/** 
 * Initializes the error action to deal with AJAX responses
 * 
 * @return null
 */
public function init()
{
    $this->_helper->ajaxContext->addActionContext(
        'error', array('json')    
    )->initContext();
}

The above code does most of the work, but chances are you may want to add a few more useful pieces of information to your JSON response. Typically in any AJAX calls we'll have a success variable that indicates whether the call we made worked or not.

Add this line to the top of the errorAction method:

$this->view->success = false;

To test the above code, you can have your action your AJAX call hits throw an exception that you don't catch. This is as simple as:

throw new Exception('Foo');

If we do this, and view the JSON in chrome or Firebug, you'll see a success = false, an empty exception object, an empty request object and a very helpful message with a value of "Application error".

The empty request and exception object are because those are PHP objects that are getting set into the view within the ErrorController. In a JSON response, it may be helpful to add some more information from within those objects.

Near the end of the errorAction method, we should see some code like:

// conditionally display exceptions        
if ($this->getInvokeArg('displayExceptions') == true) {
    $this->view->exception = $errors->exception;        
}

If you want this additional information to only be sent to the view if displayExceptions is turned on and if it's an AJAX call, you can make the following modifications.

// conditionally display exceptions        
if ($this->getInvokeArg('displayExceptions') == true) {            
    if ($this->_request->isXmlHttpRequest()) {                
        $this->view->exception  = $errors->exception
            ->getMessage();                
        $this->view->stackTrace = $errors->exception
            ->getTrace();             
    } else {                
        $this->view->exception = $errors->exception;        
    }        
}

This code will replace that empty exception object with the message from the exception. It will also create a new stackTrace object in the JSON which is an array of objects containing information about the stack trace.  It's completely up to you if you want to include that information or not.

The other empty object showing up in the JSON is the empty request. If knowing more about the request would be useful, change this

$this->view->request = $errors->request;

to this:

if ($this->_request->isXmlHttpRequest()) {
    $this->view->request = $this->_request->getParams();
} else {
    $this->view->request = $errors->request;
}

This chunk of code will replace that empty request object with an array of key: value pairs for all of the parameters in the request.

That's all there is to it. Your AJAX calls will now get a JSON response even if an error happens in one of your controllers.

I hope this helps and I look forward to hearing from you.

Create POP3 filter in PHP using Zend Framework

In this article, we are going to discuss about how to create POP3 filter in PHP using Zend Framework. POP3 is nothing but Post Office Protocol (POP) is an application-layer Internet standard protocol used by local e-mail clients to retrieve e-mail from a remote server over a TCP/IP connection. It is mostly used to send and receive an Email in an application. I'm going to explain about how to create POP3 filter in php using Zend framework.

Create a file in the server named "pop3filter.php" and add the below codes in that file.

<?php
require_once 'Zend/Mail/Storage/Pop3.php';

$spammers = array(
    "email1@example.com",
    "email2@example.com",
);

$mail = new Zend_Mail_Storage_Pop3(array('host' => 'pop3.example.com', 'user' => 'john.doe@example.com', 'password' => 'example', 'port' => 110));

echo $mail->countMessages() . " messages found\n";

foreach ($mail as $messageId => $message) {
  echo "{$messageId} : Mail from '{$message->from}': {$message->subject}\n";

  if(in_array(strtolower($message->from), $spammers, true)) {
    $mail->removeMessage($messageId);
    echo "Message removed\n";
  }
}

?>

Crontab

$ crontab -e
# m h  dom mon dow   command
*/10 * * * * /usr/bin/php /home/john/bin/pop3filter/pop3filter.php > /dev/null 2>&1

Reading and Writing Session Data Using Zend Session Namespace

In this article we are going to discuss about how to reading and writing the session data using the Zend Session Namespace in Zend Framework. Also discuss about some useful techniques of Zend Framework session and Session Namespace.

In Zend framework, you can use both Zend_Session and Zend_Session_Namespace which extends abstract class Zend_Session_Abstract. So these two inherited methods are available in Zend_Session_Abstract automatically. In Zend/Session/Abstract.php file, you can find all functions related to session handling.

$mysession = new Zend_Session_Namespace(’Namespace’);

The argument for namespace is optional, but it’s better to pass it. if you don’t pass it, Zend Session Namespace will assign its name a string “default”. To store values in session variable, you will need to do the following.

$mysession->fruits = ‘Apple’;

Below is the example code to retrieve values from session.

$yoursession = new Zend_Session_Namespace(’Namespace’);
$fruits = $yoursession->fruits;

If you want to go deep, you can get many useful functions in Zend_Session_Abstract.php, Zend_Session_Nampspace.php, and Zend_Session.php.

Zend Framework - Introduction

Extending the art & spirit of PHP, Zend Framework is based on simplicity, object-oriented best practices, corporate friendly licensing, and a rigorously tested agile codebase. Zend Framework is focused on building more secure, reliable, and modern Web 2.0 applications & web services, and consuming widely available APIs from leading vendors like Google, Amazon, Yahoo!, Flickr, as well as API providers and cataloguers like StrikeIron and ProgrammableWeb.

Expanding on these core themes, we have implemented Zend Framework to embody extreme simplicity & productivity, the latest Web 2.0 features, simple corporate-friendly licensing, and an agile well-tested code base that your enterprise can depend upon.