Category Archives: zend

Zend posts

Zend Form Validation

Simple Bank Form Validation are here.

public function init()
{

// Set Method Post or Get
$this->setMethod(‘post’);

// Set Action Page
$this->setAction(‘register’);
$this->setAttrib(‘enctype’,’multipart/form-data’);
$this->addElement(‘text’,’fullname’,array(‘label’=>’Full Name’,’required’=>’true’,’id’=>’name’));

// Only alphabetical character.
$this->fullname->addValidator(new Zend_Validate_Alpha());

//Validating string length

$this->fullname->addValidator(new Zend_Validate_StringLength(array(‘min’=>’3′,’max’=>’30’)));
$this->addElement(‘text’,’fathername’,array(‘label’=>’Father/Mother Name’,’required’=>’true’,’id’=>’ca’));
$this->fathername->addValidator(new Zend_Validate_Alpha());
$this->fathername->addValidator(new Zend_Validate_StringLength(array(‘min’=>’3′,’max’=>’30’)));

$this->addElement(‘text’,’dob’,array(‘label’=>’Date of Birth’,’required’=>’true’,’id’=>’dob’));

// Validate date format
$this->dob->addValidator(new Zend_Validate_Date(array(‘format’=>’yyyy-mm-dd’)));
$this->addElement(‘textarea’,’address’,array(‘label’=>’Permenent Address’,’cols’=>’16’,’rows’=>’5′,’required’=>’true’));
$this->addElement(‘select’,’accountType’,array(‘label’=>’Account Type’,’multiOptions’=>array(‘0’=>’–Account Type–‘,’Saving’=>’Saving’,’Current’=>’Current’,’Joint’=>’Joint’),’required’=>’true’));
$this->addElement(‘select’,’branchName’,array(‘label’=>’Branch Name’,’multioptions’=>array(‘0’=>’–Select Branch–‘,’Chinnasalem’=>’Chinnasalem’,’Kallakurchi’),’required’=>’true’));
$this->branchName->addValidator(new Zend_Validate_GreaterThan(‘0’));
$this->branchName->addErrorMessage(“Select Your Branch”);

$this->accountType->addValidator(new Zend_Validate_GreaterThan(‘0’));

// Adding Our own Error Message.
$this->accountType->addErrorMessage(“Select Account Type”);
$this->addElement(‘text’,’pincode’,array(‘label’=>’Pincode’,’required’=>’true’));

// Validate Indian Pincode using zend locale

$this->pincode->addValidator(new Zend_Validate_PostCode(array(‘locale’=>’as_IN’)));
$this->addElement(‘checkbox’,’addrProof’,array(‘label’=>’Ration Card Proof’,’checked’=>’checked’));

$this->addrProof->addValidator(new Zend_Validate_GreaterThan(‘0’));
$this->addElement(‘radio’,’idProof’,array(‘label’=>’For IDProof’,’multioptions’=>array(‘VoterID’=>’VoterID’,’PAN’=>’PAN’,’Passport No’=>’Passport No’),’separator’=>’  ‘,’value’=>’VoterID’,’required’=>’true’));
$this->addElement(‘text’,’mobile’,array(‘label’=>’Mobile Number’,’required’=>’true’));

$this->mobile->addValidator(new Zend_Validate_Digits());
$this->mobile->addValidator(new Zend_Validate_StringLength(array(‘max’=>’10’,’min’=>’10’)));
$this->mobile->addErrorMessage(“Must be 10 Digit Valid Number”);

$this->addElement(‘text’,’email’,array(‘label’=>’Valid Email ID’,’required’=>’true’));

// validate E-mail Address
$this->email->addValidator(new Zend_Validate_EmailAddress());
$this->addElement(‘select’,’gender’,array(‘label’=>’Gender’,’multioptions’=>array(‘0’=>’–Gender–‘,’Female’=>’Female’,’Male’=>’Male’),’required’=>’true’));
$this->gender->addValidator(new Zend_Validate_GreaterThan(‘0’));
$this->gender->addErrorMessage(“Choose Your gender”);
$this->addElement(‘submit’,’submit’,array(‘label’=>’Submit Your Form’));

// Set Decorator to display element in table format.

$this->setElementDecorators(array(
‘ViewHelper’,
‘Errors’,
array(array(‘data’ => ‘HtmlTag’), array(‘tag’ => ‘td’, ‘class’ => ‘element’)),
array(‘Label’, array(‘tag’ => ‘td’),
)));
}

Leave a comment

Filed under zend

Zend_Mail Example

You can write this coding in controllers or models.

// Username -> Your Mail Id

// Password -> Your Password for corresponding mail.

$param=array

( ‘ auth ‘ =>  ‘  login ‘  ,

‘ username ‘ => ‘ example@yahoo.com ‘,

‘ password ‘=>’ YourPassword ‘ );

/*

Mention correct SMTP address for your mail id. If you use yahoo the following will help you. If it is gmail means you have to use smtp.gmail .com.

*/
$smtp=new Zend_Mail_Transport_Smtp( ‘ smtp.mail.yahoo.com ‘ , $param );

// Make $smtp as default transport.
Zend_Mail :: setDefaultTransport( $smtp );
$mail=new Zend_Mail();
$mail->setFrom( ” fromaddress@domain.com ” );
$mail->addTo( ” toaddress@domain.com ” );
$mail->setSubject( ” Test Mail ” );
$mail->setBodyHtml( ” Hi Guest, <br> <b> Welcome to Test Mail </b> ” );
try{
$mail->send();
return “success”;
}
catch (Exception $e){
echo “Sorry! Problem in sending mail.”;
}

Leave a comment

Filed under zend

Example to create Forms using Zend_Form

<?php

// Extend Zend_Form to use form elements
class Application_Form_Login extends Zend_Form
{
public function init()
{
$username=new Zend_Form_Element_Text(‘username’);
$username->setLabel(‘Username’)
->addValidator(new Zend_Validate_Alnum())
->addFilter(‘StripTags’)
->addFilter(‘StringTrim’);

$password=new Zend_Form_Element_Password(‘password’);
$password->setLabel(‘Password’)
->setRequired(true)
->addFilter(‘StripTags’)
->addFilter(‘StringTrim’);

$submit=new Zend_Form_Element_Submit(‘submit’);
$submit->setlabel(‘SignIn’);
$this->setAction(‘index’);
$this->setMethod(‘post’);
$this->addElements(array($username,$password,$submit));
}

}

Leave a comment

Filed under zend

Zend Framework Coding Standard

This topic provides guidelines for code formatting and documentation to individuals and teams. Especially in team project coding standing plays a vital role. Because once we follow the coding standard, it will be consistent and easy to understand by other developers. And it make the code with high quality.

PHP File Formatting:

General:

For files that contain only php code, closing tag ( ?> ) is not required by php, while omitting, it prevents the accidental injection of trailing white space into the response.

Indendation:

Indendation should consists only 4 spaces. Tabs are not allowed.

Line Length:

Minimum line length target by zend framework is 80 whereas maximum is 120.

Naming Conventions:

Classes:

  1. The names of the classes directly map to the directories in which they are stored.
  2.  Class names may only contain alphanumeric characters.Numbers are permitted in class names but are discouraged in most cases.
  3. Underscores are only permitted in place of the path separator; the filename “Zend/Db/Table.php” must map to the class name “Zend_Db_Table”.
  4. If a class name is comprised of more than one word, the first letter of each new word must be capitalized. Successive capitalized letters are not allowed, e.g. a class “Zend_PDF” is not allowed while “Zend_Pdf” is acceptable.

Abstract Classes:

  1. In general, abstract classes follow the same conventions as classes, with one additional rule: abstract class names must end in the term, “Abstract”, and that term must not be preceded by an underscore.
  2. As an example,

Invalid Name:  Zend_Controller_Plugin_Abstract

Valid Name:      Zend_Controller_PluginAbstract  (or)

Zend_Controller_Plugin_PluginAbstract.

Interfaces:

  1. In general, interfaces follow the same conventions as classes, with one additional rule: interface names may optionally end in the term, “Interface”, but that term must not be preceded by an underscore.
  2. As an example,

InValid Name:    Zend_Controller_Plugin_Interface

Valid Name:         Zend_Controller_PluginInterface  (or)

Zend_Controller_Plugin_PluginInterface.

File Names:

  1. Only alphanumeric characters, underscores, and the dash character (“-“) are permitted.
  2. Spaces are strictly prohibited.
  3. Any file that contains PHP code should end with the extension “.php“. Eg: db.php

Functions and Methods:

  1. Function names may only contain alphanumeric characters.
  2. Underscores are not permitted.
  3. Numbers are permitted in function names but are discouraged in most cases.
  4. Function names must always start with a lowercase letter. When a function name consists of more than one word, the first letter of each new word must be capitalized. This is commonly called “camelCase” formatting.
  5. Verbosity is generally encouraged. Function names should be as verbose as is practical to fully describe their purpose and behavior.

Variables:

  1. Variable names may only contain alphanumeric characters.
  2. Underscores are not permitted.
  3. Numbers are permitted in variable names but are discouraged in most cases.
  4. For instance variables that are declared with the “private” or “protected” modifier, the first character of the variable name must be a single underscore. This is the only acceptable application of an underscore in a variable name. Member variables declared “public” should never start with an underscore.
  5. Verbosity is generally encouraged.
  6. If a loop contains more than 20 lines of code, the index variables should have more descriptive names.

Constants:

  1. Constants may contain both alphanumeric characters and underscores.
  2. Numbers are permitted in constant names.
  3. All letters used in a constant name must be capitalized, while all words in a constant name must be separated by underscore characters.
  4. For example, EMBED_SUPPRESS_EMBED_EXCEPTION is permitted but EMBED_SUPPRESSEMBEDEXCEPTION is not.
  5. Constants must be defined as class members with the “const” modifier. Defining constants in the global scope with the “define” function is permitted but strongly discouraged.

 

Leave a comment

Filed under zend

Create RSS Feeds with ZendFramework

In this post I’ll introduce how to create RSS feeds using Zend Framework through Zend_Feed Component.

We have got some mandatory elements in the channel, and the articles. Every Channel has to have the title, description, link and description elements. The articles also have some mandatory fields, as title, link, GUID (Globally Unique Identifier) and you can import as optional parameters as you want.

First, We’ll create a controller for the RSS, we’ll name it, rssController.php and create the method for the action, which by default will be the index action

class RssController extends Zend_Controller_Action {

    /**
     * The default action for the rss controller
     * Which shows the rss document
     */
    public function indexAction() {
        // method body
    }
}
I’ll use sample data in an array for the ease of this tutuorial, you will normally retrieve these data from your database.
We’ll Assume that we have got 2 articles to syndicate:
$feedData = array(

            'title'=>'Channel Title',
            'description'=>'Channel Description here',
            'link'=>'http://www.example.com',
            'charset'=>'utf8',
            'entries'=>array(
                array(
                    'title'=>'Article 1',
                    'description'=>'Article 1 contents goes here',
                    'link'=>'http://www.example.com/article-1',
                    'guid'=>'1A'
                ),
                array(
                    'title'=>'Article 2',
                    'description'=>'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
                    'link'=>'http://www.example.com/article-2',
                    'guid'=>'2A'
                )
            )
        );
We have got 2 methods of generating the RSS document. The first is using the Zend_Feed’s importArray method and the other one using the importBuilder, I’ll explain how to use both in the following snippet.
importArray accepts 2 parameters, first is the data array and the second is the format(string) with ‘rss’ or ‘atom’ defaults to ‘atom’
    1| feed = Zend_Feed::importArray($feedData,'rss');
importBuilder method accepts 2 parameter, first Zend_Feed_Builder object and the second is the feed format(string) either ‘rss’ or ‘atom’ defaults to ‘atom’.           
   1| $feed = Zend_Feed::importBuilder(new Zend_Feed_Builder($feedData),'rss');
Then we’ll set the content type of the document to be xml
   1| header('Content-type: text/xml');
After that we’ll generate and print the rss XML document we are building using send() method which returns the generated xml document.
   1| echo $feed->send();
Finally, we need to suppress the view, because we need no view for this action:
   1| $this->_helper->viewRenderer->setNoRender();
Now let’s wrap up all the code,
// uncomment this if you have autoloading disabled.

// require_once 'Zend/Controller/Action.php';
 
class RssController extends Zend_Controller_Action {
    /**
     * The default action for the rss controller
     * Which shows the rss document
     */
    public function indexAction() {
        $feedData = array(
            'title'=>'Channel Title',
            'description'=>'Channel Description here',
            'link'=>'http://www.example.com',
            'charset'=>'utf8',
            'entries'=>array(
                array(
                    'title'=>'Article 1',
                    'description'=>'Article 1 contents goes here',
                    'link'=>'http://www.example.com/article-1',
                    'guid'=>'1A'
                ),
                array(
                    'title'=>'Article 2',
                    'description'=>'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
                    'link'=>'http://www.example.com/article-2',
                    'guid'=>'2A'
                )
            )
        );
        // create our feed object and import the data
        $feed = Zend_Feed::importArray ( $feedData, 'rss' );
         
        // set the Content Type of the document
        header ( 'Content-type: text/xml' );
         
        // echo the contents of the RSS xml document
        echo $feed->send()
    }
}
Now, let’s test it using this url: http://example.com/rss/
You should get this output:
<?xml version="1.0" encoding="utf8"?>

<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0">
  <channel>
    <title><![CDATA[Channel Title]]></title>
    <link>http://www.example.com</link>
 
    <description><![CDATA[Channel Description here]]></description>
    <pubDate>Fri, 25 Mar 2011 20:42:58 +0200</pubDate>
    <generator>Zend_Feed</generator>
    <item>
      <title><![CDATA[Article 1]]></title>
      <link>http://www.example.com/article-1</link>
 
      <guid isPermaLink="false">1A</guid>
      <description><![CDATA[Article 1 contents goes here]]></description>
      <pubDate>Fri, 25 Mar 2011 20:42:58 +0200</pubDate>
    </item>
    <item>
      <title><![CDATA[Article 2]]></title>
      <link>http://www.example.com/article-2</link>
 
      <guid isPermaLink="false">2A</guid>
      <description><![CDATA[Lorem ipsum dolor sit amet, consectetur adipiscing elit.]]></description>
      <pubDate>Fri, 25 Mar 2011 20:42:58 +0200</pubDate>
    </item>
  </channel>
</rss>
That’s it  you get happy coding right?

Leave a comment

Filed under zend

Zend releases new IDE

PHP company Zend Technologies announced a new release of its integrated development environment (IDE). Zend Studio 7.0 features support for the newly-released PHP version 5.3 as well as tight integration with Zend Server and Zend Framework.

“PHP is rapidly becoming a mainstay in the enterprise, and Zend Studio 7.0 provides everything a developer needs to quickly build dynamic, professional-grade PHP applications with high performance, security, and reliability,” said Andi Gutmans, CEO and co-founder of Zend Technologies. “Zend Studio, together with Zend Framework and Zend Server, provides a PHP solution that addresses the entire Web application lifecycle, from development to production.”

New features and enhancements in this version of Zend Studio 7.0 include support for PHP 5.3, Zend framework integration, enhanced source code editing and Zend Server integration.

Leave a comment

Filed under zend

Getting started with Zend Framework

Getting-Started-with-Zend-Framework

Leave a comment

Filed under zend

ZF commands in Zend Framework

Create Controller:

  1. To create new controller in controllers directory in your application go to command prompt.
  2. C:\xampp\htdocs\hello-world> zf create controller controller-name.
  3. Eg: C:\xampp\htdocs\hello-world> zf create controller login.
  4. It will then create loginController.php in controllers and login folder in views->scripts with one index.phtml file.

Create Action:

  1. To create new action in controller
  2. C:\xampp\htdocs\hello-world> zf create action action-name controller-name.
  3. Eg: C:\xampp\htdocs\hello-world> zf create action validation Auth.
  4. So it creates a new function with validationAction in AuthController.php and validation.phtml in auth folder in views->scripts.

Create Model:

  1. To create Models in your application
  2. C:\xampp\htdocs\hello-world> zf create model model-name.
  3. Eg: C:\xampp\htdocs\hello-world> zf create model dboperation.
  4. It will create a new folder called models with dpoperation.php. In this file you can do all database operation by extendind Zend_Db_Table_Abstract(use keyword extends).

Create Layout:

  1. To create a layout in your application
  2. C:\xampp\htdocs\hello-world> zf enable layout.
  3. It will then create layouts folder in your application with layout.phtml file. Also it automatically add a path to layout in your application.ini as
    resources.layout.layoutPath = APPLICATION_PATH “/layouts/scripts/”.
  4. Don’t delete the line <?php echo $this->layout()->content; ?> in layout.phtml because it is used to show the content in your display.

Create Form:

  1. To create forms in your application
  2. C:\xampp\htdocs\hello-world> zf create form form-name.
  3. Eg: C:\xampp\htdocs\hello-world> zf create form login.
  4. It will then create a forms folder in your application with login.php and here you can create any form elements by using Zend_Form_Element.
  5. Add this code resources.view[] = ,in your application.ini  [production] section i.e as line 12.
  6. Add this function in application->Bootstrap.php
  7. protected function _initDoctype()
    {
    $this->bootstrap(‘view’);
    $view=$this->getResource(‘view’);
    $view->doctype(‘XHTML1_STRICT’);
    }

  8. And add <?php echo $this->doctype(); ?> in your layour.phtml file.
  9. Why all this process is because to make forms and it elements visible all over your application. Declaration in bootstrap file is helpful for global access.

Leave a comment

Filed under zend

Example to start working with Zend Framework

First Create a project with command prompt in the correct directory. Like,

command to create project
After that copy zend library folder in your application library directory.
To understand folder structure

First see the application.ini in config directory change the first two lines
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0

to

phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1.

This is not necessary but it is used to show errors in development stage.

Next open the indexController.php in controllers directory. There already a init function which then acts like constructor will be there and then indexAction for your index.phtml i.e for every phtml file in index folder which is in views directory should have an action in index controller. At the same time for for every controller there should be a folder in views like for IndexController there is a index folder in views.

Then to display anything in view page for example i want to display a title in view page as “Hello World”. The coding is

<?php

class IndexController extends Zend_Controller_Action
{

public function init()
{
/* Initialize action controller here */
}

public function indexAction()
{

/* $this mentions current object, $this->view mentions for view page and title is a variable name which we declared for index.phtml page */
$this->view->title=”hello world”;
$this->view->content=”Welcome to Zend Framework”;
}

}

Then in index.phtml in index folder, some default coding will be there just clear those thing and

we can code like this

<html>
<head>
<title>

/* Getting value from controller which we declared */
<?php echo $this->title?>
</title>
</head>
<body>

/* Getting value from controller which we declared */
<center><h1><?php echo $this->content ?></h1></center>
</body>
</html>

Thats it now open the browser and type localhost/hello-world/public.

Leave a comment

Filed under zend

Module-specific layouts in Zend Framework 2

First, I should point out that the title of this post is a bit of an intentional misnomer. There’s really no such thing as “module-specific” anything in ZF2, so what we’re really talking about is the topmost namespace of the controller being dispatched. So in the case ofMyModule\Controller\SomeController, the topmost namespace would be MyModule. In most cases, this will be the name of a given module.

Here’s how you can easily switch the layout (or perform any other arbitrary logic) for a specific module in Zend Framework 2.0 (as of d0b1dbc92):

<?php
namespace MyModule;

use Zend\ModuleManager\ModuleManager;

class Module
{
    public function init(ModuleManager $moduleManager)
    {
        $sharedEvents = $moduleManager->getEventManager()->getSharedManager();
        $sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
            // This event will only be fired when an ActionController under the MyModule namespace is dispatched.
            $controller = $e->getTarget();
            $controller->layout('layout/alternativelayout');
        }, 100);
    }
}

This event listener will only be triggered if an ActionController under the MyModule namespace is dispatched, so you do not need to perform any additional logic to check which “module” or namespace the controller being dispatched is under.

Keep in mind, as of writing this, ZF2 is still in beta. There are plans to add a convenience layer to the framework before the GA release which will likely make common tasks like this much simpler.

Leave a comment

Filed under zend