zf2 cheat sheet

Controller

Request and Response object

                    $this->getRequest();             //Request object
                    $this->getResponse();            //Response object

                    $this->getRequest()->getUri();     //URI
                    $this->getRequest()->getCookie();  //Cookies
                    $this->getRequest()->getServer();  //Server vars

                    $this->params()->fromPost('foo');  //POST
                    $this->params()->fromQuery('foo'); //GET
                    $this->params()->fromRoute('foo'); //RouteMatch
                    $this->params()->fromHeader('foo');//Header
                    $this->params()->fromFiles('foo'); //Uploaded file

                    $this->getRequest()->isXmlHttpRequest();
                    $this->getRequest()->isPost();
                            

Redirecting in a controller

                    $this->redirect()->toRoute('route',
                    array('action' => 'name'), array('param => 1'));

                    $this->redirect()->toUrl('http://google.com');
                            

Redirect to 404 not found

                    $this->getResponse()->setStatusCode(404);
                            

Forwarding

                    $this->forward()->dispatch('controllerName',
                                array('action' => 'actionName'));
                            

Working with Session

You can manage session with

                public function indexAction() {
                    $session = new Zend\Session\Container('user');
                    $session->username = 'Foo'; //store username
                }

                public function addAction() {
                    // Retrieve username from session
                    $session = new Zend\Session\Container('user');
                    $username = $session->username;
                }
                            

Flash messages

Self-expiring, session-based messages

                    public function indexAction() {
                        $this->flashMessenger()->addMessage('Message');
                    }
                                
Attach flashMessages to view through EventManager
                    $em = $e->getApplication()->getEventManager();
                    $em->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER, function($e) {
                    $messenger = new \Zend\Mvc\Controller\Plugin\FlashMessenger();
                    if ($messenger->hasMessages()) {
                        $messages = $messenger->getMessages();
                        $e->getViewModel()->setVariable('flashMessages', $messages);
                    }
                    });
                                

Literal all flash messages in layout

 
                    <?php if (isset($flashMessages)) : ?>
                    
    <?php foreach ($flashMessages as $message) : ?>
  • <?= $message; ?>
  • <?php endforeach; ?>
<?php endif; ?>

Controller class example

                    namespace MyModule\Controller;

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

                    class IndexController extends AbstractActionController {
                    public function indexAction() {
                        // get request
                        // do something
                        // return view object
                        return array('id' => $id, 'form' => $form);
                    }

                    }
                            

View

View Model

Different template for View

                $view->setTemplate('my-template.phtml');
                            

Set variables in view

                $view->setVariables(array('var' => 'foo'));
                            

Adding multiple view model object as View variable

                $view = new ViewModel();
                $sideblockView = new ViewModel();
                $sideblockView->setTemplate('content/sideblock');
                $view->addChild($sideblockView, 'sideblock');
                return $view;
                            

Disable View

                $response = $this->getResponse();
                $response->setStatusCode(200);
                return $response;
                            

Json Response

                $view = new JsonModel(
                    array('success' => '1','data'=>'foo'));
                return $response;
                            

Json Response for whole Module

            //module.config.php
            return array(
                'view_manager' => array(
                    'strategies' => array(
                       'ViewJsonStrategy',
                    ),
                ),
            )
                            

Custom view strategy

//todo

Layout

Set different layout template.

                $this->layout()->setTemplate('layout/new-layout');
                            

Inject new ViewModel to layout.

                $view = new ViewModel();
                $sideView = new ViewModel();
                $sideView->setTemplate('content/sidebar');
                $this->$layout->addChild($sideView, 'side-view');
                return $view;
                            

Disable Layout

                $view = new ViewModel();
                $view->setTerminal(true);
                return $view;
                            

Different layout file for different controller.

            //module.php
            public function init(ModuleManager $moduleManager){
                $sharedEvents = $moduleManager->getEventManager()->getSharedManager();
                $sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
                    $controller = $e->getTarget();
                    if ($controller instanceof Controller\FrontEndController) {
                        $controller->layout('layout/front');
                    }
                }, 100);
            }
                            

Get access to view in module

            //module.php
            public function onBootstrap($e){
              $app = $e->getApplication();
              $viewModel = $app->getMvcEvent()->getViewModel();
            }
                            

Retrieve view value in layout

            //layout.phtml
            $viewModel = $this->viewModel()->getCurrent();
            $children = $viewModel->getChildren();
            $viewModel = $children[0];
            $viewModel->foo;
                            

View configuration example

                //module/config/module.config.php
                return array(
                    'view_manager' => array(
                    'template_map' => array(
                        'application/index/index' => __DIR__ .  '/../view/application/index/index.phtml',
                        'site/layout'           => __DIR__ . '/../view/layout/layout.phtml',
                        'error/index'             => __DIR__ . '/../view/error/index.phtml',
                        'error/404'               => __DIR__ . '/../view/error/404.phtml',
                    ),
                    'template_path_stack' => array(
                        'application' => __DIR__ . '/../view',
                    ),
                    'layout' => 'site/layout',
                    'display_exceptions' => true,
                    'exception_template' => 'error/index',
                    'display_not_found_reason' => true,
                    'not_found_template'       => 'error/404',
                    ),
                    'strategies' => array(
                        'ViewStrategy',
                    ),
                );
                            

Template

Header

Doctype

                $this->doctype();
                            

Embedding CSS

                $this->headLink()->appendStylesheet(
                    $this->basePath(). '/ccsFile.css)
                            

Embedding Meta Tags, keywords

                $this->headMeta()->appendName('keywords',
                    'framework, PHP, productivity')
                            

Embedding Java Script

                $this->headScript()->appendFile('/js.js',
                    'text/javascript',
                    array('conditional' => 'lt IE 7')
                );
                            

Links

                Click
                            

Base Path (point to the public folder)

                
                            

Escaping

            $this->escapeHtml();
            $this->escapeHtmlAttr();
            $this->escapeJs();
            $this->escapeCss();
            $this->escapeUrl();
                            

Json Encode

                $this->json($this->data, array $params)
                            
Body

Including partials and component

            $this->partial('partial.phtml', array(
            'from' => 'Team Framework',
            'subject' => 'view partials'));
                            

Convert array to ordered/unordered list

                $this->htmlList(array $data);
                            

Cycle Helper

                $this->cycle()->assign(array $data));
                $this->cycle()->next();
                $this->cycle()->prev();
                            

Currency

                $this->currencyFormat(1234.56, "USD", "en_US");
                // This returns: "$1,234.56"
                            

Date/Time

                $this->dateFormat(new DateTime(),
                IntlDateFormatter::SHORT);   // "7/2/12"

                $this->dateFormat(new DateTime(),
                IntlDateFormatter::NONE,  // date
                IntlDateFormatter::SHORT, // time
                "en_US"
                ); // This returns: "6:44 PM"
                            

Number

                $this->numberFormat(
                1234567.891234567890000,
                NumberFormatter::DECIMAL,
                NumberFormatter::TYPE_DEFAULT,
                "de_DE"
                ); // This returns: "1.234.567,891"

                $this->numberFormat(
                0.80,
                NumberFormatter::PERCENT,
                NumberFormatter::TYPE_DEFAULT,
                "en_US"
                ); // This returns: "80%"
                            

Custom Helper

Implementation of a custom view helper.

                namespace MyModule\View\Helper;

                use Zend\View\Helper\AbstractHelper;

                class testHelper extends AbstractHelper {

                public function __invoke($output = 'bar') {
                    return "$output , this is ZF2 View Helper";
                }

                }
                                

Registering Helper

                public function getViewHelperConfig()
                {
                    return array(
                        'invokables' =>  => array(
                            'testHelper' => 'MyModule\View\Helper\TestHelper';
                    );
                }
                                

Calling in view

                $this->testHelper('foo');
                                

Doctrine

Instalation and Configuration

Instalation

        php composer.phar require doctrine/doctrine-orm-module:0.7.*
                            

Enabling the modules

        config/application.config.php

        return array(
            'modules' => array(
                'Application',
                'DoctrineModule',
                'DoctrineORMModule',
                'MyModule',
            ),
            // [...]
        );
                            

Configure the connection

        config/autoload/doctrine.local.php

        return array(
          'doctrine' => array(
            'connection' => array(
              'orm_default' => array(
                'driverClass' =>'Doctrine\DBAL\Driver\PDOMySql\Driver',
                'params' => array(
                  'host'     => 'localhost',
                  'port'     => '3306',
                  'user'     => 'username',
                  'password' => 'password',
                  'dbname'   => 'database',
        )))));
                            

Configure mappings

        module/MyModule/config/module.config.php
        namespace MyModule;

        return array(
        'doctrine' => array(
            'driver' => array(
                __NAMESPACE__ . '_driver' => array(
                    'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
                    'cache' => 'array',
                    'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity')
                ),
                'orm_default' => array(
                    'drivers' => array(
                        __NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
        ))))),
        // [...]
                            

Validate Mapping

        ./vendor/bin/doctrine-module orm:validate-schema
                            

Generate Tables

        ./vendor/bin/doctrine-module orm:schema-tool:create
                            

Generate Entities

        ./vendor/bin/doctrine-module orm:generate-entities 'path' --generate-annotations=true
                            

Access the entity manager

In Controller

        module/MyModule/src/MyModule/Controller/IndexController.php

        public function indexAction() {
            $entityManager = $this->getServiceLocator()
                ->get('doctrine.entitymanager.orm_default');
        }
                            

Inject the Entity Manager to Service

        module/MyModule/src/Module.php
        public function getServiceConfig() {
            return array(
                'factories' => array(
                    'my_service' => function ($sl) {
                        $entityManager = $sl->get('doctrine.entitymanager.orm_default');
                        $myService = new Service\MyService();
                        $myService->setEntityManager($entityManager);
                        //or you can set repository
                        $repository = $entityManager->getRepository('MyModule\Entity\MyEntity');
                        $myService->setRepository($repository);
                        return $myService;
                    },
                ),
            );
        }

        module/MyModule/src/MyModule/Serice/MyService.php
        class MyService
        {
            public function setRepository(MyRepository $repository) {
                // [...]
            }
            public function setEntityManager(EntityManager $entityManager) {
                // [...]
            }
        }
                            

Inject the Entity Manager to Form (doctrine form select)

        module/MyModule/src/Module.php
        public function getFormElementConfig() {
            return array(
                'factories' => array(
                    'commentForm' => function($sm) {
                        $locator = $sm->getServiceLocator();
                        $em = $locator->get('doctrine.entitymanager.orm_default')
                        $form = new Form\MyForm($em);
                        return $form;
                    },
                )
            );
        }

        module/MyModule/src/MyModule/Form/MyForm.php
        public function __construct(EntityManager $entityManager){
        // [...]
        $this->add(array(
            'type' => 'DoctrineModule\Form\Element\ObjectSelect',
            'name' => 'doctrine',
            'options' => array(
                'object_manager' => $entityManager,
                'target_class'   => '\Comment\Entity\Comment',
                'property'       => 'comment',
                'empty_option'   => '--- please choose ---',
                'is_method'      => true,
                'find_method'    => array(
                    'name'   => 'findBy',
                    'params' => array(
                        'criteria' => array('active' => 1),
                        'orderBy'  => array('comment' => 'ASC'),
                    ),
                ),
            ),
        ));
        // [...]
                            

Basic Usage

Persisting objects

                $user1 = new User();
                $user1->setFullName('MyName');
                $em->persist($user1);

                $user2 = new User();
                $user2->setFullName('MyName2');
                $em->persist($user2);

                $em->flush();
                            

Updating an object

                $user = $em->find('User', 1);
                $user->setName('MyName');
                $em->flush();
                            

Deleting an object

                $user = $em->find('User', 1);
                $em->remove($user);
                $em->flush();
                            

Retrieving an object

                // single user by id
                $user1 = $em->find('User', 1);
                $user2 = $em->getRepository('User')->find(1);

                // single user by name and type.
                $user = $em->getRepository('User')->findOneBy(
                    array('name' => 'MyName', 'type' => 'MyType'));

                // single user by its Name
                $user = $em->getRepository('User')->findOneByName('MyName');

                // find All users
                $users = $em->getRepository('User')->findAll();

                // group users by type
                $users = $em->getRepository('User')->findByType('MyType');

                // group users by criteria, order, limit, offset.
                $users = $em->getRepository('User')->findBy(
                    array('name' => 'MyName'), array('id' => 'ASC'), 10, 0);

                //DQL

                //Query Builder

                            

Associations

Mapping One to One

                class User
                {
                    /**
                     * @ORM\OneToOne(targetEntity="Address", mappedBy="user", cascade={"persist"})
                     */
                    protected $address;
                }

                class Address
                {
                    /**
                     * @ORM\OneToOne(targetEntity="User", inversedBy="address", cascade={"persist"})
                     * @ORM\JoinColumn(name="userId", referencedColumnName="id", unique=false, nullable=false)
                     */
                    protected $user;
                }
                                

Usage example One to One

                    // persisting
                    $plumber = new \DoctrineTest\Entity\User();
                    $plumber->setEmail('email');
                    $plumber->setName('name');

                    $address = new \DoctrineTest\Entity\Address;
                    $address->setPremise('premise23');
                    $address->setStreet('street23');

                    $address->setUser($plumber);
                    $plumber->setAddress($address);

                    $em->persist($plumber);
                    $em->flush();

                    //retrieving
                    $plumber = $em->find('User', $plumber->getId());
                    $plumber->getAddress();
                                

Mapping One to Many

            class User
            {
                /**
                 * @ORM\OneToMany(targetEntity="Comment", mappedBy="user", cascade={"persist"})
                 */
                protected $comments;

                public function __construct()
                {
                    $this->comments = new \Doctrine\Common\Collections\ArrayCollection();
                }
            }

            class Comment
            {
                /**
                 * @ORM\ManyToOne(targetEntity="User", inversedBy="comments", cascade={"persist"})
                 * @ORM\JoinColumn(name="userId", referencedColumnName="id", unique=false, nullable=false)
                 */
                protected $user;
            }
                                

Usage example One to Many

                    // persisting
                    $plumber = new \DoctrineTest\Entity\User();
                    $plumber->setEmail('email');
                    $plumber->setName('name');

                    $comment1 = new \DoctrineTest\Entity\Comment;
                    $comment1->setCommentText('comment1');
                    $comment1->setUser($plumber);
                    $comment2 = new \DoctrineTest\Entity\Comment;
                    $comment2->setCommentText('comment2');
                    $comment2->setUser($plumber);

                    $plumber->getComments()->add($comment2);
                    $plumber->getComments()->add($comment1);

                    $em->persist($plumber);
                    $em->flush();

                    //retrieving
                    $plumber = $em->find('User', $plumber->getId());

                    $plumber->getComments()->toArray();

                                

Mapping One to Many Self Ref


                class Comment
                {
                    /**
                     * @ORM\OneToMany(targetEntity="Comment", mappedBy="parent", cascade={"persist"})
                     */
                    protected $children;

                    /**
                     * @ORM\ManyToOne(targetEntity="Comment", inversedBy="children", cascade={"persist"})
                     * @ORM\JoinColumn(name="parentId", referencedColumnName="id", unique=false, nullable=true)
                     */
                    protected $parent;

                    public function __construct()
                    {
                        $this->children = new \Doctrine\Common\Collections\ArrayCollection();
                    }
                }
                                

Usage example One to Many Self Ref

                    // persisting
                    $comment2 = new \DoctrineTest\Entity\Comment;
                    $comment2->setCommentText('parent');

                    $comment1 = new \DoctrineTest\Entity\Comment;
                    $comment1->setCommentText('children1');
                    $comment1->setParent($comment2);
                    $comment3 = new \DoctrineTest\Entity\Comment;
                    $comment3->setCommentText('children2');
                    $comment3->setParent($comment2);

                    $comment2->getChildrens()->add($comment1);
                    $comment2->getChildrens()->add($comment3);

                    $em->persist($comment2);
                    $em->flush();

                    //retrieving
                    $comment = $em->find('Comment', $comment2->getId());
                    $comment->getChildrens();
                                

Mapping Many to Many

                class User
                {
                    /**
                     * @ORM\ManyToMany(targetEntity="Category", inversedBy="users", cascade={"persist"})
                     * @ORM\JoinColumn(name="categoryId", referencedColumnName="id", unique=false, nullable=true)
                     */
                    protected $categories;

                    public function __construct()
                    {
                        $this->categories = new \Doctrine\Common\Collections\ArrayCollection();
                    }
                }

                class Category
                {
                    /**
                     * @ORM\ManyToMany(targetEntity="User", mappedBy="categories", cascade={"persist"})
                     */
                    protected $users;

                    public function __construct()
                    {
                        $this->users = new \Doctrine\Common\Collections\ArrayCollection();
                    }
                }
                                

Usage example Many to Many

                    // persisting
                    $plumber = new \DoctrineTest\Entity\User();
                    $plumber->setEmail('email');
                    $plumber->setName('Plumber Builder');

                    $plaster = new \DoctrineTest\Entity\User;
                    $plaster->setEmail('email');
                    $plaster->setName('Plaster Builder');

                    $categoryPlumber = new \DoctrineTest\Entity\Category;
                    $categoryPlumber->setName('Plumber Category');
                    $categoryBeer_Drinkers = new \DoctrineTest\Entity\Category;
                    $categoryBeer_Drinkers->setName('Beer_Drinkers Category');

                    $categoryPlumber->getUsers()->add($plumber);
                    $categoryBeer_Drinkers->getUsers()->add($plaster);
                    $categoryBeer_Drinkers->getUsers()->add($plumber);

                    $plumber->getCategories()->add($categoryPlumber);
                    $plumber->getCategories()->add($categoryBeer_Drinkers);
                    $plaster->getCategories()->add($categoryBeer_Drinkers);

                    $em->persist($plumber);
                    $em->persist($plaster);
                    $em->flush();

                    //retrieving
                    $plumber = $em->find('User', $plumber->getId());
                    //get last categories for plumber
                    $plumber->getCategories()->toArray());
                    //get last category(Beer_Drinkers Category) and all users for this category
                    $plumber->getCategories()->last()->getUsers()->toArray();
                                

Mapping Inheritance

                /**
                 * @ORM\Entity
                 * @ORM\InheritanceType("JOINED")
                 * @ORM\DiscriminatorColumn(name="discr", type="string")
                 * @ORM\DiscriminatorMap({"user" = "User", "soleTrader" = "SoleTrader"})
                 */
                class User
                {
                    // [...]
                }

                /**
                * @ORM\Entity
                */
                class SoleTrader extends User
                {
                    /**
                     * @ORM\Column(type="string")
                     */
                    protected $specialNumber;
                }
                                

Usage example Inheritance

                    // persisting
                    $soletrader = new \DoctrineTest\Entity\SoleTrader();
                    $soletrader->setEmail('email');
                    $soletrader->setName('name');
                    $soletrader->setSpecialNumber('112333');

                    $address = new \DoctrineTest\Entity\Address;
                    $address->setPremise('premise23');
                    $address->setStreet('street23');

                    $address->setUser($soletrader);
                    $soletrader->setAddress($address);

                    //retrieving
                    $plumber = $em->find('SoleTrader', $plumber->getId());
                    $plumber->getAddress();
                                

Advanced

Lifecycle callbacks

                @HasLifecycleCallbacks
                @PostLoad, @PrePersist, @PostPersist,
                @PreRemove, @PostRemove, @PreUpdate, @PostUpdate

                /**
                 * @ORM\MappedSuperclass
                 * @ORM\HasLifecycleCallbacks
                 */
                abstract class AbstractUser
                {
                     /**
                      * @ORM\Column(name="updated_at", type="datetime")
                      */
                     private $updatedAt;

                     /**
                      * @ORM\PrePersist()
                      * @ORM\PreUpdate
                      */
                     public function preUpload()
                     {
                         $this->updatedAt = new \DateTime();
                     }
                }

                /**
                 * @ORM\Table(name="users")
                 */
                class User extends AbstractUser
                {
                    // [...]
                }
                            

Criteria Example (not tested)

                use Doctrine\Common\Collections\Criteria;
                use Doctrine\Common\Collections\ArrayCollection;

                $collection = new ArrayCollection(array($user1, $user2, $user3));
                $criteria   = new Criteria();
                $criteria->andWhere(
                    $criteria->expr()->gt(
                        'lastLogin',
                        new \DateTime('-1 day')
                    )
                );

                $recentVisitors = $collection->matching($criteria);
                $recentVisitors = $em->getRepository('User')->matching($criteria);
                            

Custom Repository

                //Entity mapping for repository class
                use Doctrine\ORM\Mapping as ORM;

                /**
                 * @ORM\Entity(repositoryClass="DoctrineTest\Repository\Comment")
                 */
                class Comment
                // [...]

                //repository Class
                use Doctrine\ORM\EntityRepository;

                class Comment extends EntityRepository
                {
                    public function findUserComments($userId)
                    {
                        $query = $this->_em->createQuery("SELECT u FROM
                        DoctrineTest\Entity\Comment u WHERE u.userId = :userId");
                        $query->setParameters(array('userId' => $userId));
                        return $query->getResult();
                    }
                }

                //in controller
                $repository = $em->getRepository('\DoctrineTest\Entity\Comment');
                $comments = $repository->findUserComments(10);

                            

Form

Basic Form

Form configuring

            FormTest/src/Module.php
            public function getFormElementConfig() {
                return array(
                    'factories' => array(
                        'commentForm' => function($sm) {
                            $form = new Form\CommentForm();
                            $form->setInputFilter(new \FormTest\Form\CommentFilter);
                            $form->setHydrator(new \Zend\Stdlib\Hydrator\ObjectProperty());
                            return $form;
                        },
                    ),
                );
            },
                            

Form Object

            namespace FormTest\Form;

            use Zend\Form\Element;
            use Zend\Form\Form;

            class CommentForm extends Form {

                public function __construct() {
                    parent::__construct();

                    $this->setName('Comment');
                    $this->setAttribute('method', 'post');

                    $this->add(array(
                        'name' => 'parentId',
                        'attributes' => array(
                            'type' => 'hidden',
                        ),
                    ));

                    $this->add(array(
                        'name' => 'type',
                        'type' => 'select',
                        'options' => array(
                            'label' => 'Type',
                            'empty_option' => 'Select',
                            'value_options' => array(
                                '1' => 'type1',
                                '2' => 'type2',
                                '3' => 'type3',
                            ),
                        )
                    ));

                    $this->add(array(
                        'name' => 'comment',
                        'attributes' => array(
                            'type' => 'textarea',
                        ),
                        'options' => array(
                            'label' => 'Comment',
                        )
                    ));

                    $this->add(new Element\Csrf('security'));
                    $this->add(array(
                        'name' => 'submit',
                        'attributes' => array(
                            'type' => 'submit',
                            'value' => 'Submit',
                        ),
                    ));
                }
            }
                            

Accessing Form in Controller

            public function simpleAction() {
                $formManager = $this->serviceLocator->get('FormElementManager');
                $form = $formManager->get('commentForm');

                $comment = new Comment();
                $comment->type = 3;
                $comment->comment = 'Test';

                $form->bind($comment);

                $request = $this->getRequest();
                if ($request->isPost()) {
                    $form->setData($request->getPost());
                    if ($form->isValid()) {
                        var_dump($comment);
                    }
                }

                return array('form' => $form);
            }
                            

Render Form in View


            $form = $this->form;
            $form->setAttribute('action', $this->url('formTest', array('action' => 'simple')))->prepare();
            echo $this->form()->render($form);
                            

Form Validation and Filtering

            namespace FormTest\Form;
            use Zend\InputFilter\InputFilter;

            class CommentFilter extends InputFilter {

                public function __construct() {

                    $this->add(array(
                        'name' => 'parentId',
                        'required' => true,
                        'filters' => array(
                            array('name' => 'Int'),
                        ),
                    ));
                    $this->add(array(
                        'name' => 'type',
                        'required' => true,
                    ));

                    $this->add(array(
                        'name' => 'comment',
                        'required' => true,
                        'filters' => array(
                            array('name' => 'StripTags'),
                            array('name' => 'StringTrim'),
                        ),
                        'validators' => array(
                            array(
                                'name' => 'StringLength',
                                'options' => array(
                                    'encoding' => 'UTF-8',
                                    'min' => 1,
                                    'max' => 100,
                                ),
                            ),
                        ),
                    ));
                }
            }
                            

Form using Annotation Builder

Entity with form Annotation

            namespace FormTest\Entity;

            use Zend\Form\Annotation;

            /**
             * @Annotation\Hydrator("Zend\Stdlib\Hydrator\ObjectProperty")
             * @Annotation\Name("comment")
             */
            class Comment
            {
                /**
                 * @Annotation\Exclude()
                 */
                public $parentId;

                /**
                 * @Annotation\Type("select")
                 * @Annotation\Options({"label":"Type","value_options":{"1":"Type1","2":"Type2","3":"Type3"}})
                 */
                public $type;

                /**
                 * @Annotation\Attributes({"type":"textarea" })
                 * @Annotation\Options({"label":"Comment:"})
                 */
                public $comment;

            }
                            

Generating Form In Controller

            public function annotationAction() {
                $comment = $this->getCommentData();
                $builder = new AnnotationBuilder();
                $form = $builder->createForm($comment);
                $form->add(array(
                    'name' => 'submit',
                    'attributes' => array(
                        'type' => 'submit',
                        'value' => 'Go',
                        'id' => 'submitbutton',
                    ),
                ));

                $form->bind($comment);

                $request = $this->getRequest();
                if ($request->isPost()) {
                    $form->setData($request->getPost());
                    if ($form->isValid()) {
                        var_dump($comment);
                    }
                }
                return array('form' => $form);
            }
                            

Render Form in View

            $form = $this->form;
            $form->setAttribute('action', $this->url('formTest', array('action' => 'annotation')))->prepare();
            echo $this->form()->openTag($form);
            echo $this->formRow($form->get('type'));
            echo $this->formRow($form->get('comment'));
            echo $this->formInput($form->get('submit'));
            echo $this->form()->closeTag($form);
                            

Form with relationship One-to-One, One-to-Many(highlighted)

Configuration

        FormTest/src/Module.php
        public function getFormElementConfig() {
            return array(
                'createUser'=> function($sm) {
                    $addressFieldset = new AddressFieldset();
                    $addressFieldset //->setInputFilter()
                    ->setHydrator(new ObjectProperty(false))
                    ->setObject(new Address());

                    $commentFieldset = new CommentFieldset();
                    $commentFieldset //->setInputFilter()
                    ->setHydrator(new ObjectProperty)
                    ->setObject(new Comment());

                    $collection = new \Zend\Form\Element\Collection;
                    $collection->setName('comments');
                    $collection->setOptions(array(
                                'label' => 'Comments',
                                'should_create_template' => true,
                                'allow_add' => true,
                        ));
                    $collection->setTargetElement($commentFieldset);

                    $userFieldset = new UserFieldset();
                    $userFieldset //->setInputFilter()
                    ->setHydrator(new ObjectProperty(false))
                    ->setObject(new User)
                    ->setOptions(array('use_as_base_fieldset' => true))
                    ->add($addressFieldset)
                    ->add($collection);

                    $form = new CreateUser();
                    $form->setInputFilter(new InputFilter);
                    $form->add($userFieldset);
                    return $form;
                },
            );
        },
                            

Form

        namespace FormTest\Form;

        use Zend\Form\Form;

        class CreateUser extends Form
        {
            public function __construct()
            {
                parent::__construct('create_user');

                $this->setAttribute('method', 'post');

                $this->add(array(
                    'type' => 'Zend\Form\Element\Csrf',
                    'name' => 'security'
                ));

                $this->add(array(
                    'name' => 'submit',
                    'attributes' => array(
                        'type' => 'submit',
                        'value' => 'Send'
                    )
                ));
            }
        }
                            

Entities

        namespace FormTest\Entity;

        class Address
        {

            public $street;
            public $postcode;

        }

        namespace FormTest\Entity;

        class User
        {
            public $name;
            public $email;
            public $address;

        }

        namespace FormTest\Entity;

        class Comment
        {

            public $parentId;
            public $type;
            public $comment;

        }
                            

Render Form in View

        $form = $this->form;
        $form->setAttribute('action', $this->url('formTest', array('action' => 'one-to-one')))->prepare();
        echo $this->form()->openTag($form);
        $user = $form->get('user');
        echo $this->formRow($user->get('name'));
        echo $this->formRow($user->get('email'));
        echo $this->formCollection($user->get('comments'));
        $address = $user->get('address');
        echo $this->formRow($address->get('street'));
        echo $this->formRow($address->get('city'));
        echo $this->formHidden($form->get('security'));
        echo $this->formElement($form->get('submit'));
        echo $this->form()->closeTag();
                            

Accessing Form in Controller

        public function oneToOneAction() {
            $user = new User;
            $user->name = "Name";
            $user->email = "email@foo.bar";

            $address = new Address;
            $address->street = "My Street";
            $address->city = "My City";
            $user->address = $address;

            $comment1 = new Comment;
            $comment1->comment = 'Testing1';
            $comment1->type = 1;
            $comment1->parentId = 2;

            $comment2 = new Comment;
            $comment2->comment = 'Testing2';
            $comment2->type = 1;
            $comment2->parentId = 2;
            $user->comments = array($comment1, $comment2);

            $formManager = $this->serviceLocator->get('FormElementManager');
            $form = $formManager->get('createUser');

            $form->bind($user);
            if ($this->request->isPost()) {
                $form->setData($this->request->getPost());
                if ($form->isValid()) {
                    var_dump($user);
                }
            }
            return array('form' => $form);
        }
                            

Fieldsets Objects


        namespace FormTest\Form;

        use Zend\Form\Fieldset;

        class UserFieldset extends Fieldset
        {
            public function __construct()
            {
                parent::__construct('user');

                $this->add(array(
                    'name' => 'name',
                    'options' => array(
                        'label' => 'Name'
                    ),
                    'attributes' => array(
                        'required' => 'required'
                    )
                ));

                $this->add(array(
                    'name' => 'email',
                    'options' => array(
                        'label' => 'Email'
                    ),
                    'attributes' => array(
                        'required' => 'required'
                    )
                ));
            }
        }

        namespace FormTest\Form;

        use Zend\Form\Fieldset;

        class AddressFieldset extends Fieldset
        {
            public function __construct()
            {
                parent::__construct('address');

                $this->add(array(
                    'name' => 'street',
                    'options' => array(
                        'label' => 'Street'
                    ),
                    'attributes' => array(
                        'required' => 'required'
                    )
                ));
                $this->add(array(
                    'name' => 'city',
                    'options' => array(
                        'label' => 'City'
                    ),
                    'attributes' => array(
                        'required' => 'required'
                    )
                ));
            }
        }
        namespace FormTest\Form;

        use Zend\Form\Fieldset;

        class CommentFieldset extends Fieldset
        {
            public function __construct()
            {
                parent::__construct('comment');

                $this->add(array(
                    'name' => 'parentId',
                    'attributes' => array(
                        'type' => 'hidden',
                    ),
                ));

                $this->add(array(
                    'name' => 'type',
                    'type' => 'select',
                    'options' => array(
                        'label' => 'Type',
                        'empty_option' => 'Select',
                        'value_options' => array(
                            '1' => 'type1',
                            '2' => 'type2',
                            '3' => 'type3',
                        ),
                    )
                ));

                $this->add(array(
                    'name' => 'comment',
                    'attributes' => array(
                        'type' => 'textarea',
                    ),
                    'options' => array(
                        'label' => 'Comment',
                    )
                ));
            }
        }
        
Validation Groups

validate only a subset of form elements.

                $form->setValidationGroup('comment', 'email', 'subject', 'message');
                            

validate only a subset of the fieldsets.

            $form->setValidationGroup(array(
                 'csrf',
                 'username' => array(
                    'name',
                    'email',
                    'address' => array(
                        'premise',
                        'street',
                        'city'
                    ),
                ),
            ));
                            

Creating custom elements // todo

Doctrine select element
            $form->add(array(
                'type' => 'DoctrineModule\Form\Element\ObjectSelect',
                'name' => 'doctrine',
                'options' => array(
                    'object_manager' => $locator->get('doctrine.entitymanager.orm_default'),
                    'target_class'   => '\Comment\Entity\Comment',
                    'property'       => 'comment',
                    'empty_option'   => '--- please choose ---',
                    'is_method'      => true,
                    'find_method'    => array(
                        'name'   => 'findBy',
                        'params' => array(
                            'criteria' => array('parentId' => 1),
                            'orderBy'  => array('comment' => 'ASC'),
                        ),
                    ),
                ),
            ));
                            

Form View Helpers

Form Usage
Form $this->form()->render($form);
Opening Form Tag $this->form()->openTag($form);
Closing Form Tag $this->form()->closeTag($form);
Label, Element & Error $this->formRow($element);
Fieldset with all elements $this->formCollection($collection);
Label $this->formLabel($element);
Element $this->formElement($element);
List errors $this->formElementErrors($element);
Any Input $this->formInput($element);
Captcha $this->formCaptcha($element);
Form Elements Usage
File $this->formFile($element);
Image $this->formImage($element);
Text $this->formText($element);
Textarea $this->formTextarea($element);
Select $this->formSelect($element);
Checkbox $this->formCheckbox($element);
Radio $this->formRadio($element);
MultiCheckbox $this->formMultiCheckbox($element);
Hidden $this->formHidden($element);
Password $this->formPassword($element);
Button $this->formButton($element);
Reset $this->formReset($element);
Submit $this->formSubmit($element);
HTML5 Elements Usage
Color $this->formColor($element);
Date $this->formDate($element);
DateTime $this->formDateTime($element);
Date Time Local $this->formDateTimeLocal($element);
Email $this->formEmail($element);
Month $this->formMonth($element);
Number $this->formNumber($element);
Range $this->formRange($element);
Search $this->formSearch($element);
Tel $this->formTel($element);
Time $this->formTime($element);
Url $this->formUrl($element);
Week $this->formWeek($element);

ServiceManager

The Service Manager can be configured in 7 different ways:

            return array(

                // instantiate the class for you when needed
                'invokables' => array(
                    'commentController' => '\Comment\Controller\CommentController';
                ),

                // Aliasing a name to a known service name
                'aliases' => array(
                    'Comment\Service' => 'commentService';
                ),

                // configure the instance of the object
                'factories' => array(
                    'commentController' => function ($sm) {
                        $locator = $sm->getServiceLocator();
                        $controller = $locator->get('commentController');
                        $controller->setCommentService($locator->get('Comment\Service'));
                        return $controller;
                    }
                ),

                // register already instantiated objects
                'services' => array(
                    'commentController' => new \Comment\Controller\CommentController(),
                ),

                //factory instance that can create multiple services based on the name supplied to the factory.
                'abstract_factories' => array(
                    'SomeModule\Service\FallbackFactory',
                ),

                // initialize the service whenever service created
                'initializers' => array(
                    function ($instance, $sm) {
                        if ($instance instanceof \Comment\Controller\CommentController){
                            $instance->setCommentService($sm->get('Comment\Service'));
                        }
                    }
                ),

                // indicating whether or not a service should be shared
                'shared' => array(
                    'commentController' => false,
                ),
            );
                            

ServiceManager

Registering Repository and Service

            public function getServiceConfig() {
                return array(
                    'factories' => array(
                        'commentRepository' => function ($sm) {
                            $em = $sm->get('doctrine.entitymanager.orm_default');
                            $comment_repository = $em->getRepository('Comment\Entity\Comment');
                            return $comment_repository;
                        },
                        'commentService' => function ($sm) {
                            $comment_service = new Service\CommentService();
                            $comment_service->setRepository($sm->get('commentRepository'));
                            return $comment_service;
                        }
                    ),
                );
            }
                            

ViewHelperManager

Registering new view Helper base on Provided Service

            public function getViewHelperConfig() {
                return array(
                    'factories' => array(
                        'commentList' => function ($helpers) {
                            $locator = $helpers->getServiceLocator();
                            $viewHelper = new View\Helper\CommentList();
                            $viewHelper->setCommentService($locator->get('commentService'));
                            return $viewHelper;
                        },
                    )
                );
            }
                            

ControllerPluginManager

Registering Controler plugin base on View Helper

            public function getControllerPluginConfig() {
                return array(
                    'factories' => array(
                        'commentPlugin' => function($plugins) {
                          $helper = $plugins->get('commentList');
                          return $helper;
                        },
                    )
                );
            }
                            

ControllerManager

Registering Controler with Form and Service seted

            public function getControllerConfig() {
                return array(
                    'factories' => array(
                        'commentController' => function ($sm) {
                            $controller = new \Comment\Controller\CommentController();
                            $locator = $sm->getServiceLocator();
                            $controller->setCommentForm($locator->get('commentForm'));
                            $controller->setCommentService($locator->get('commentService'));
                            return $controller;
                        }
                    )
                );
            }
                            

FormElementManager

Registering Form with Filter, Hydrator and EM (getting list for select)

            public function getFormElementConfig() {
                return array(
                    'invokables' => array(
                        'commentHydrator' => '\Zend\Stdlib\Hydrator\ClassMethods'
                        'commentFilter' => 'Form\CommentFilter'
                    )
                    'factories' => array(
                        'commentForm' => function($sm) {
                            $locator = $sm->getServiceLocator();
                            $form = new Form\CommentForm($locator->get('doctrine.entitymanager.orm_default'));
                            $form->setInputFilter($locator->get('commentFilter'));
                            $form->setHydrator($locator->get('commentHydrator'));
                            return $form;
                        }
                    )
                );
            }
                            

Routing

Literal

Matches and assembles literal strings

            //http://site.com/route-test
            'routeTestLiteral' => array(
                'type' => 'Literal',
                'options' => array(
                    'route' => '/route-test',
                    'defaults' => array(
                        'controller' => 'routeTest',
                        'action' => 'literal',
                    ), ), ),
                            

Segment

Matching any segment of a URI path. Provides parameter matching based on delimiters and constraints,

            //http://site.com/route-test/controller/action/34
            'routeTestSegment' => array(
               'type' => 'Segment',
               'options' => array(
                   'route' => '/route-test[/:controller][/:action][/:id]',
                   'constraints' => array(
                       'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                       'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                       'id' => '[0-9]+',
                   ),
                   'defaults' => array(
                       'controller' => 'routeTest',
                       'action' => 'default',
                   ), ), ),
                            

Regex

Matches based on a regular expression

            //http://site.com/route-test/page-33.html
            'routeTestRegex' => array(
                'type' => 'Regex',
                'options' => array(
                    'regex' => '/route-test/page-(?<id>[0-9]+).html',
                    'spec' => '/route-test/%id%',
                    'defaults' => array(
                        'controller' => 'routeTest',
                        'action' => 'regex',
                    ), ), ),
                            

Hostname

Allows matching and assembling hostnames

            //http://subdomain.site.com/
              'routeTestHostname' => array(
                'type' => 'hostname',
                'options' => array(
                    'route' => ':subdomain.site.com',
                    'defaults' => array(
                        'controller' => 'routeTest',
                        'action' => 'hostname',
                 ), ), ),
                            

Scheme

Matches and assembles a specific scheme (http, https, ...)

            //https://sitename.com
              'routeTestScheme' => array(
                'type' => 'scheme',
                'options' => array(
                    'scheme' => 'https',
                    'defaults' => array(
                        'https' => true,
                        'controller' => 'routeTest',
                        'action' => 'scheme',
                    ), ), ),
                            

Child routes, using Wildcard and Method routes

            //http://site.com/route-test/wil/1/wil2/3/wil3/4
            'routeTestLiteral' => array(
                'type' => 'Literal',
                'options' => array(
                    'route' => '/route-test',
                    'defaults' => array(
                        'controller' => 'routeTest',
                        'action' => 'literal',
                    ), ),
                'may_terminate' => false,

                'child_routes' => array(
                    // matches key/value pairs,
                    // allows to modify key/value and parameter delimiters
                    'routeTestWildcard' => array(
                        'type' => 'wildcard',
                        'options' => array(
                            'key_value_delimiter' => '/',
                            'param_delimiter'     => '/',
                            'defaults' => array(
                                'controller' => 'routeTest',
                                'action' => 'wildcard',
                            ), ), ),
                    // maches post methhod
                    'routeTestPost' => array(
                          'type' => 'Method',
                          'options' => array(
                              'verb' => 'post',
                              'defaults' => array(
                                  'action' => 'methodpost'
                              ), ), ),
                      // maches get,head,put,delete methhods
                      'routeTestGetPut' => array(
                          'type' => 'Method',
                          'options' => array(
                              'verb' => 'get,head,put,delete',
                              'defaults' => array(
                                  'action' => 'methodget'
                              ), ), ),
                   ),
                            

Custom

Find and redirect to the page base on record from DB

Router Factory

            public function getRouteConfig()
            {
                return array(
                    'factories' => array(
                        'pageRoute' => function ($routePluginManager) {
                            $locator = $routePluginManager->getServiceLocator();
                            $params = array('defaults' => array('controller' => 'routeTest','action' => 'page','id' => 'pages'));
                            $route = \RouteTest\Route\PageRoute::factory($params);
                            $route->setServiceManager($locator);
                            return $route;
                        },
                    ),
                );
            }
                                

Adding Route

            'routeTestCustom' => array(
                'type' => 'pageRoute',
                ),
                                

Page Entity


            use Doctrine\ORM\Mapping as ORM;
            class Page {

                /**
                 * @ORM\Id
                 * @ORM\Column(type="integer");
                 * @ORM\GeneratedValue(strategy="AUTO")
                 */
                protected $id;
                /**
                 * @ORM\Column(type="string")
                 */
                protected $pageUrl;

                // seters geters
            }
                                

In Controller

                $router = $this->params()->fromRoute();
                $em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
                $page = $em->getRepository('\DoctrineTest\Entity\Page')->findOneById($router['id']);
                                

Route File

            namespace RouteTest\Route;

            use Zend\Mvc\Router\Http\RouteInterface;
            use Zend\ServiceManager\ServiceManagerAwareInterface;
            use Zend\ServiceManager\ServiceManager;
            use Zend\Stdlib\RequestInterface as Request;
            use Zend\Mvc\Router\Http\RouteMatch;

            class PageRoute implements RouteInterface, ServiceManagerAwareInterface
            {

                protected $serviceManager;

                protected $defaults;

                public function getServiceManager()
                {
                    return $this->serviceManager;
                }

                public function setServiceManager(ServiceManager $serviceManager)
                {
                    $this->serviceManager = $serviceManager;

                    return $this;
                }

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

                public static function factory($options = array())
                {
                    if ($options instanceof Traversable) {
                        $options = ArrayUtils::iteratorToArray($options);
                    } elseif (!is_array($options)) {
                        throw new Exception\InvalidArgumentException(__METHOD__ . ' expects an array or Traversable set of options');
                    }

                    if (!isset($options['defaults'])) {
                        $options['defaults'] = array();
                    }

                    return new static($options['defaults']);
                }

                public function match(Request $request)
                {
                    $uri  = $request->getUri();
                    $path = $uri->getPath();

                    $em = $this->getServiceManager()->get('doctrine.entitymanager.orm_default');
                    $repository = $em->getRepository('\DoctrineTest\Entity\Page');
                    $page = $repository->findOneByPageUrl(str_replace("/", "", $path));
                    if($page){
                        $params = $this->defaults;
                        $params['id'] = $page->getId();
                        return new RouteMatch($params);
                    }

                    return null;
                }

                public function assemble(array $params = array(), array $options = array()){
                  return $this->route;
                }

                public function getAssembledParams()
                {
                    return array();
                }
            }
                                

Mail

Mail body:

                        use Zend\Mime;
                        // html
                        $html = new Mime\Part('

email body

'); $html->type = Mime\Mime::TYPE_HTML; // plaintext $text = new Mime\Part('email body'); $text->type = Mime\Mime::TYPE_TEXT; // attachment $attachment = new Mime\Part(fopen('file.pdf', 'r')); $attachment->type = 'application/pdf'; $attachment->disposition = Mime\Mime::DISPOSITION_ATTACHMENT; // add to body $body = new Mime\Message(); $body->setParts(array($text, $html, $attachment));

Mail container:

                        use Zend\Mail;
                        $mail = new Mail\Message();
                        $mail->addFrom('your@mail.com');
                        $mail->addTo('send@mail.com');
                        $mail->setSubject('subject');
                        $mail->setBody($body);
                        $mail->setEncoding('UTF-8');
                    

Mail sending:

                        use Zend\Mail\Transport;
                        $transport = new Transport\Sendmail();
                        $transport->send($mail);
                    

Use view to create html mail body:

                        use \Zend\View\Model\ViewModel;
                        $view = new ViewModel(array('body' => 'email body'));
                        $view->setTemplate('mail-template');
                        $htmlMail = $sm->get('ViewRenderer')->render($view);
                        $body = new Mime\Message();
                        $body->setParts(array($htmlMail));
                    

Reset header:

                        $headers = $mail->getHeaders();
                        $headers->removeHeader('Content-Type');
                        $headers->addHeaderLine('Content-Type', 'text/html; charset=UTF-8');
                    

Send Smtp mail:

                        use Zend\Mail\Transport;
                        $options = array(
                            'host' => 'smtp.gmail.com',
                            'port' => 587,
                            'connection_class' => 'login',
                            'connection_config' => array(
                            'username' => 'yourMail@gmail.com',
                            'password' => 'yourPassword',
                            'ssl' => 'tls'
                        ));
                        $smtpOptions = new Transport\SmtpOptions($options);
                        $smtp = new Transport\Smtp($smtpOptions);
                        $smtp->send($mail);
                    

Validation

Name Alone In Form
NotEmpty
        $valid = new NotEmpty();
        $valid->isValid('foo'); //true
                                        
        'validators' => array(array('name' => 'not_empty'),)
                                        
Digits
        $valid = new Digits();
        $valid->isValid('foo123'); //false,
                                        
        'validators' => array(array( 'name' => 'digits'),)
                                        
Alpha
        $valid = new Alpha();
        $valid->isValid('foo123'); //false
                                        
        'validators' => array(array('name' => 'alpha', 
            'options' => array('allowWhiteSpace' => true),),)
                                        
Alnum
        $valid = new Alnum();
        $valid->isValid('foo123'); //true
                                        
        'validators' => array(array('name' => 'alnum',
                'options' => array('allowWhiteSpace' => true),),)
                                        
Hex
        $valid = new Hex();
        $valid->isValid('123ABC'); //true
                                        
        'validators' => array(array('name' => 'hex'),)
                                        
StringLength
        $valid = new StringLength();
        $valid->isValid('foo123'); //true
                                        
        'validators' => array(array('name' => 'string_length',
          'options' => array('encoding' => 'UTF-8','min' => 1,'max' => 10),),)
                                        
Between
        $valid = new Between(array('min' => 0,'max' => 10));
        $valid->isValid('12'); //false
                                        
        'validators' => array(array('name' => 'between',
          'options' => array('inclusive' => false,'min' => 1,'max' => 10),),)
                                        
LessThan
        $valid = new LessThan(array('max' => 10));
        $valid->isValid('12'); //false accept only digits
                                        
        'validators' => array(array('name' => 'less_than',
            'options' => array('inclusive' => false, 'max' => 10),),)
                                        
GreaterThan
        $valid = new GreaterThan(array('min' => 10));
        $valid->isValid('12'); //false
                                        
        'validators' => array(array('name' => 'greater_than',
            'options' => array('inclusive' => false,'min' => 10),),)
                                        
Date
        $valid = new Date(
            array('locale' => 'en', 'format' => 'Y'));
        $valid->isValid('2010 December'); //false
                                        
        'validators' => array(array('name' => 'date',
            'options' => array('locale' => 'en', 'format' => 'Y'),),)
                                        
DB records

RecordExists

NoRecordExists

        $valid = new RecordExists(
            array('table' => 'users','field' => 'email')));
        $valid->isValid('2010 December'); //false
                                        
        'validators' => array(array('name' => 'record_exists',
            'options' => array( 'table' => 'users', 'field' => 'id',
                // optional  'schema' => 'PostgreSQL', 'adapter' => $adapter,
                //for NoRecordExists
                'exclude' => array( 'field' => 'id', 'value' => 1),),)
                                        
Identical
        $valid = new Identical(
            array('token' => 123, 'strict' => FALSE));
        $valid->isValid('123'); //false
                                        
        'validators' => array(array('name' => 'identical',
          'options' => array('strict' => 'false','token' =>'elementOne'),),)
                                        
Special
CreditCard
        $valid = new CreditCard(array(CreditCard::VISA));
        $valid->isValid('12'); //false
                                        
        'validators' => array(array( 'name' => 'credit_card',
            'options' => array('type' => array(CreditCard::VISA,),),)
                                        
EmailAddress
        $valid = new EmailAddress(array('domain' => false));
        $valid->isValid('2010 Dezember'); //false
                                        
        'validators' => array(array('name' => 'record_exists',
            'options' => array(
                'allow' => Hostname::ALLOW_DNS,
                'deep' => FALSE, 'domain' => TRUE, 'mx' => FALSE),),)
                                        
PostCode
        $valid = new PostCode(array('locale' => 'de_AT')));
        $valid->isValid('ec1 1pq'); //false
                                        
        'validators' => array(array('name' => 'post_code',
            'options' => array('locale' => 'de_AT','format' => 'AT_\d+'),),)
                                        
Hostname
        $valid = new Hostname(
            array('allow' => Hostname::ALLOW_DNS));
        $valid->isValid('domain.com'); //false
                                        
        'validators' => array(array( 'name' => 'hostname',
          'options' => array(
            'allow' => Hostname::ALLOW_IP,
            'idn' => FALSE, // 'ip' => Zend\Validator\Ip,
            'tld' => FALSE,'useIdnCheck' => true,'useTldCheck' => false),),)
                                        
Ip
        $valid = new Hostname(array('allowipv6' => false));
        $valid->isValid('192.168.50.1'); //false
                                        
        'validators' => array(array('name' => 'hostname',
            'options' => array(
                'allowipv4' => true, 'allowipv6' => true,
                'allowipvfuture' => false,'allowliteral' => true),),)
                                        
Regex
        $valid = new Regex(
            array('allow' => Hostname::ALLOW_DNS));
        $valid->isValid('Testing'); //true
                                        
        'validators' => array(array('name' => 'regex',
            'options' => array('pattern' => '/^Test/'),),)
                                        
File
UploadFile
        $request = new Request();
        $files   = $request->getFiles();
        $valid = new UploadFile();
        $valid->isValid($files['my-upload'])); //valid
                                        
Zend\InputFilter\FileInput will automatically prepend this validator in it's validation chain.
Exists/NotExists
        $valid = new Exists(array('/tmp', '/var/tmp'));
        $valid->isValid('/tmp/myfile.txt'); //true
                                        
        'validators' => array(array('name' => 'exists',
            'options' => array('directory' => '/tmp'),),)
                                        
Size
        $valid = new Size(
        array('min' => '10kB', 'max' => '4MB'));
        $valid->isValid('/tmp/myfile.txt'); //false
                                        
        'validators' => array(array('name' => 'size',
            'options' => array(
                'min' => '10kB', 'max' => '4MB',
                'useByteString' => true,),),)
                                        

Extension

ExcludeExtension

        $valid = new Extension(array('php', 'exe'), true);
        $valid->isValid('/tmp/myfile.txt'); //false
        //or
        $valid = new ExcludeExtension(array('php', 'exe'), true);
                                        
        'validators' => array(array('name' => 'extension',
            'options' => array('extension' => array('php', 'exe'), 
                'case' => true,),),)
                                        
ImageSize
        $valid = new ImageSize(320, 200, 640, 480);
        $valid->isValid('./myfile.jpg'); //valid
                                        
        'validators' => array(array('name' => 'image_size',
            'options' => array(
                'minWidth' => 320,'minHeight' => 200,
                'maxWidth' => 640,'maxHeight' => 480,),),)
                                        

MimeType

ExcludeMimeType

        $valid = new MimeType(array('image/gif', 'image/jpg'));
        $valid->isValid('./myfile.jpg'); //valid
        //or
        $valid = new MimeType(array('image/gif', 'image/jpg'));
                                        
        'validators' => array(array('name' => 'image_size',
            'options' => array(
                'mimeType' => array('image/gif', 'image/jpg'),
                'magicFile' => '/path/to/magicfile.mgx',
                'enableHeaderCheck' => true),),)
                                        
IsCompressed
        $valid = new IsCompressed();
        $valid->isValid('./myfile.zip'); //false
                                        
        'validators' => array(array('name' => 'is_compressed',),)
                                        
IsImage
        $valid = new IsImage();
        $valid->isValid('./myfile.jpg'); //false
                                        
        'validators' => array(array('name' => 'is_image'),)
                                        
WordCount
        $valid = new WordCount(array('min'=>'1','max'=>'5'));
        $valid->isValid('/tmp/myfile.txt'); //false
                                        
        'validators' => array(array('name' => 'word_count',
            'options' => array('min' => '1','max' => '5',),),)