Archive | March, 2009

Ubuntu: Working with text editor (vim)

19 Mar

If you are following my blog, you will find my last few articles are on Ubuntu.

Yeah, that’s where I am working now.

I’ve installed Ubuntu and working to have some knowledge, coz I’m going to develop my own extension for php in next few weeks.

Before going to get my hands dirty with extension development, I will need to get a bit used to the Ubuntu. I have already learnt some commands like how to install and update apache, php and other stuff. However until now I was unable to write something using any text editor. Thought I tried to use text editor by going to Application/Accessories/Text editor, however I was unable to create document other than my home directory. So I decided to use vim. I is never an easy job to work with vim if you are newbie.

Let’s tell you what I have learnt so for.

  1. To open a file you will need to write the following command in you shell terminal.

$ sudo vim /etc/resolv.conf

The above command will open if file already exist or will create new one.

  1. To make changes to the file you will need to press “Insert” key of your keyboard.
  2. You can use arrow keys to move left, right, up and down. You can use h, j, k, l for this purpose too.
  3. Once you write something in the file. Press “escape” key. This will take you to the command mode. Its necessary to go to the command mode for saving the document.
  4. After pressing the “escape” key, press colon(:). This will take you to the end of the file.
  5. write :wq for save and quite. And press enter at the end.
  6. you can you use i for going to “insert” mode and a for append mode.

That’s it for now. Hopefully I’ll learn more next time and will share with you too.

Zend Framework: working with layout and views (two step view)

19 Mar

In this article I’m going to discuss layout and views and will give a practical example.

You may have heard of two step view.

The term two step view is used when we use layout and view templates for making our page look and feel.

Mostly you will need header, menu and footer same for the entire web application, only contents in the center of the page changes. So if this is the case you can get benefits out of two step views.

Create a layout containing header, menus and footer etc and view will have the contents relevant that specific page.

To implement two step view  in Zend framework you will need to make some configuration in bootstrap file.

Add the following lines to your bootstrap file.

$options = array(

    'layout'     => 'layout_name',

    'layoutPath' => '/path/to/layouts',

    

);
 
$layout = Zend_Layout::startMvc($options);

Keep in mind two things.
1.    Specify correct layout_name.
2.    Path to the layout file must be correct.
I usually prefer to create my layout directory in scripts directory under application/views.
 
If you create layout.phtml in your layouts directory you will need to define it as follows.
 

<?php
        include "header.phtml";
        
?>
// view contents goes here.
<?php
        
        <?=$this->layout()->content?>
 
?>
// footer goes here.
<?php
        include "footer.phtml"
?>

        
Now whatever request (controller/action) you made to your page, header and footer will be included in the response.

There may be cases (in some of your actions) where you don’t want your header and footer be appeared in the look and feel.

So write in those actions, the following line of code

$this->_helper->layout->disableLayout();

After including this line in your action, only the view contents will appear. It mean the contents in the header and footer will not be served.

Some time you need to execute only action code and redirect your request to another action instead of showing anything.

Write the following code in this case

$this->_helper->layout->disableLayout();

$this->_helper->viewRenderer->setNoRender();

Another very important thing is when you call a specific action, Zend Framework render a template file with the name similar to the action name. for example if you request view action, Zend will look for view.phtml file in the specific template directory.

If you want to render other then the default template, view.phtml in the above example. Write the following in your action.

$this->render(‘thanks’);

Ubuntu: Installing apache and Php

18 Mar

Its very easy to install apache and php on Ubuntu.

After installing Ubuntu you will need to do the following.

Go to Application/Accessories/Terminal

And write

$ sudo apt-get install apache2

A process will start when you will give correct password and apache will be installed in few minutes depending on your internet speed.

Next, for installing Php, write

$ sudo apt-get install php5

This will install Php5 for you.

If you want to create php extension you will need to install phpize.

This will need some extra steps.

Like, you will first need to install pear as

$ sudo apt-get install php-pear

This will prompt for y. enter y and press enter.

Now use the following code for installing phpize.

$ sudo apt-get install php5-dev

You may have heard about PECL extension. To install these extension you will need the following steps.

Before taking these step you will need to go through all the steps discussed above.

  1. install apache
  2. install php
  3. install pear
  4. install phpize

After installing all the above you will need to install another package named libcurl3-openssl-dev. To install this package you will need to run the following in terminal.

$ sudo apt-get install libcurl3-openssl-dev

And now install PECL as

$ sudo pecl install pecl_http

After running this command and accept default options PECL extension will be installed.

However to use this you will need to add a line to php.ini file. Do the following for this purpose

$ sudo nano /etc/php5/apache2/php.ini

And add the following line of code

“extension = http.so”

And restart your services as

$ sudo /etc/init.d/apache2 restart

$ sudo /etc/init.d/httpd restart

That’s it you have now installed apache, php, phpize and PECL extension.

Ubuntu: Creating resolv.conf file and connecting to internet

18 Mar

Yesterday I installed Ubuntu’s latest version for the first time in my life. It was no doubt a good experience. One thing that irritate me was, I was unable to connect to the internet. Thanks to our MIS department engineer who help me in getting out of the problem.

Here is what he did.

  • Create resolv.conf in /etc/ directory and place the following code.

nameserver 68.34.1.3

nameserver 68.34.1.4

These should be the first two line of the resolv.conf file.

Here first line contain the DNS sever IP and the second line is for alternate DNS.

Now in terminal write

sudo vim /etc/network/interfaces

This will open interfaces file

This file should contain the following code.

auto lo

iface lo inet loopback

iface etho0 inet static

address 66.45.5.55

netmask 45.45.5.55

network 45.45.4.44

broadcast 45.45.5.66

gateway 45.45.4.33

dns-nameserver 45.23.4.44, 45.23.4.64

dns-search example.org

auto eth0

Keep in mind that the address are not real, you will need to make sure all these address are correct in your case.

Zend Framework: Using Zend Session and Session Namespace

17 Mar

Session handling was one of the boring topic in plan php atleast for me, but in Zend Framework it really shines. If you like to work with Object oriented programming, you will definitely become fan of it.

In this article I’m going to discuss some useful techniques of using Zend Framework Session and Session namespace.

Keep in mind that Both Zend_Session and Zend_Session_Namespace extends abstract class Zend_Session_Abstract. So both inherit methods avaliable in Zend_Session_Abstract automatically.

If you want to go under the hood, you can open Zend/Session/Abstract.php and have a look at the functions available.

Instead of delve into the function available, I’d rather discuss some useful techniques.

“Read full article here”, http://zendgeek.blogspot.com/2009/07/zend-framework-session-usage-and.html

Zend Framework Form: working with multiselect list

10 Mar

I am writing articles on Zend Framewrok form component since few days. I’ve already discussed how to use select(dropdown) list and radio buttons in separate articles.
In this article I’m going to discuss how to use multiselect in zend framework application.
In your form, write the following code

<?php

class CustomForm extends Zend_Form
{

public function init()
{

$this->setMethod(‘post’);
$this->setAction(”);

$subjects = $this->createElement(‘multiselect’,’subjects’);
$subjects->setLabel(‘Subjects’)

->addMultiOptions(array(
‘en’ => ‘English’,
‘gr’ => ‘German’,
‘sp’ => ‘Spanish’
));

$this->addElement($subjects);

$submit = $this->createElement(‘submit’,’submit’);
$submit->setLabel(‘Submit’);
$this->addElement($submit);

}

}

That’s it, we have now created our form with multiselect. The next step is to get values in the Controller/Action.
Keep in mind that using multiselect you can select one or more options using shift key on your keyboard.
One the form is submitted you can take the form values as

$form = new CustomForm();
$values = $form->getValues();

$values with contain the entire set of values submitted. To get individual values of the multiselect option, you will need the following code.

$subjects = $values[‘subjects’];

Keep in mind that subjects is our element name in the form.

$subjects is an array like the following.

array(2) {
[0] => string(2) “gr”
[1] => string(2) “sp”
}

PHP: Listing files in particular directory, a real world example

6 Mar

We are preparing our static files specially java script, css and images files to be moved to Amazon CDN. The thing we need to make sure here is that only those files that are in use should be moved. I was given a task to list all the js, css and images we are currently using in our application.

Initially I opened notepad and start writing down the names of those files.

Hehe, we don’t think out of the box.

The whole process was disgusting and I was feeling tired.

However working for a bit of time, an idea come to my mind, why not use computer to do the task for me.

And this is what I did.

Create .php file and write the following code in that file.

<form action=”” method=”post”>

<input type=”text” name=”path” />

<br>

<input type=”submit” value=”Submit” />

</form>

<?php

$pathName = $_POST[‘path’];

if($pathName){

$dir = new DirectoryIterator($pathName);

foreach($dir as $fileInfo) {

if($fileInfo->isDot()) {

// do nothing

} else {

echo $fileInfo->__toString().'<br>’;

}

}

}

?>

The code above did everything for me. Created a list of files in particular directory. I took print out of that list and crossed (x) files under construction.

In the first few lines I am creating form, adding input box for the directory path to be entered and submit button.

In the php code

  1. I get the path
  2. If path is not empty, I create an instance of DirectoryIterator available in PHP5, giving it directory path entered via input box.

3.Loop the $dir object and echo the result as string.

Zend Framework Form: working with dropdown(select) list

6 Mar

Though I’ve already discuss how to create dropdown in one of my previous article, however here I would discuss it a bit in detail.

You can create dropdown using the following code.

<?php

class CustomForm extends Zend_Form

{

public function init()

{

$this->setMethod(‘post’);

$this->setAction(‘user/process’);

$country = $this->createElement(‘select’,’countries’);

$country ->setLabel(‘Countries:’)

->addMultiOptions(array(

‘US’ => ‘United States’,

‘UK’ => ‘United Kingdom’

));

}

}

Or can also be created using the following code.

<?php

class CustomForm extends Zend_Form

{

public function init()

{

$this->setMethod(‘post’);

$this->setAction(‘user/process’);

$country = new Zend_Form_Element_Select(‘countries’);

$country ->setLabel(‘Countries:’)

->addMultiOptions(array(

‘US’ => ‘United States’,

‘UK’ => ‘United Kingdom’

));

}

}

The options are hard code in both of the cases. This will not be requirement always.

Sometime or most of the time application need that drop down should be populated fetching records from the data base. So for this purpose I would like to implement the following code.

Fist in your model write the following.

<?php

class Countries extends Zend_Table

{

protected $_name = “countries”;

public function getCountriesList()

{

$select  = $this->_db->select()

->from($this->_name,

array(‘key’ => ‘id’,’value’ => ‘country_name’));

$result = $this->getAdapter()->fetchAll($select);

return $result;

}

}

Keep in mind that the records we fetch will have an associated array having id as key and country name as value. If you don’t defined the above array, array(‘key’ => ‘id’,’value’ => ‘country_name’), as I have defined, you will not get what you want. So be careful while fetching records for constructing drop down.

And now in your form write the following code.

<?php

class CustomForm extends Zend_Form

{

public function init()

{

$this->setMethod(‘post’);

$this->setAction(‘user/process’);

$countries = new Countries();

$countries_list = $countires->getCountriesList();

$country = new Zend_Form_Element_Select(‘countries’);

$country ->setLabel(‘Countries:’)

->addMultiOptions( $countriesList

));

}

}

In the above code the only thing changes is

  1. I have instantiated model  using

$countries  =  new Countries();

2. Call getCountiresList() method. And assigned that list to the drop down,  instead of assigning hard coded values.

Zend Framework Form: working with radio buttons

5 Mar

I have already discussed creation of Zend_From in my previous articles. In this article I’d discuss how to work with radio buttons in Zend Framework Form.

In your Zend_Form, radio buttons can be created using two methods.

The first one is

<?php

class CustomForm extends Zend_Form

{

public function init()

{

$this->setMethod(‘post’);

$this->setAction(‘user/process’);

$gender = $this->createElement(‘radion’,’gender’);

$gender->setLabel(‘Gender:’)

->addMultiOptions(array(

‘male’ => ‘Male’,

‘female’ => ‘Female’

))

->setSeparator(”);

}

}

In the above code we first create our form by extending it from Zend_Form, override its init() method and setting its method and action attributes.

Next we create our radio button as

$gender = $this->createElement(‘radion’,’gender’);

Here first argument specify that we want to create radion button element of the form and the second argument set the name

and id of the radio button element group. In the next line we call addMultiOptions() method giving its array of optional

values. and lost but not least, I am calling method setSeparator for placing both radio buttons on the same line. If this

setSeparator method is not called, each radion button will appear on separate line.

The above radio button can also be created as

<?php

class CustomForm extends Zend_Form

{

public function init()

{

$this->setMethod(‘post’);

$this->setAction(‘user/process’);

$gender = new Zend_Form_Element_Radio(‘gender’);

$gender->setLabel(‘Gender:’)

->addMultiOptions(array(

‘male’ => ‘Male’,

‘female’ => ‘Female’

))

->setSeparator(”);

}

}

The only difference in the above two example is that I have placed

$gender = $this->createElement(‘radion’,’gender’);

With

$gender = new Zend_Form_Element_Radio(‘gender’);

Both statements give the same result.

For setting different radio button options, you can also use the following method.

$gender->addMultiOption(‘male’,’Male’);

$gender->addMultiOption(‘female’,’Female’);

Zend Framework: Creating custom Zend form

4 Mar

As I have already written in one of my article that when I was developing my first application in Zend Framework, I was unable to use Zend Framework Zend_Form component.

However developing my second application in Zend I was forced by my client to use it. And honestly and frankly I found it and still finding it quite helpful and interesting. Although I have written an article on Zend_Form earlier, however It will not be possible to discuss every aspect of it in single article. In this article I will try to cover as much as possible, however I know It will still be hard to go through each and every corner of it.

You can start your Zend Framework form creation journey from different places. You can create it through ini files, using separate functions for it in your controllers, however I will like and recommend you to create a separate php files for each of your form in a separate directory.

Why I recommend separate directory and separate php files for Zend_Form?

Well, this is because I feel its easy to create and use them. Further more if you need similar form in different pages, you can call the same form in multiple places.

What directory structure I recommend?

I’ll recommend the following directory structure.

 

            application/

                        controllers/

                        models/

                        forms/

                        views/

                                    scripts/

            library/

                        Zend/

            wwwroot/

                        js/

                        css/

                        images/

                        index.php

I’ll create separate file for each form in my html_root/application/forms directory.

 

How to create first custom Zend Framework Form?

Its very easy to create Zend_Form. You will only need to extend your form from Zend Framework Zend_Form component and override init() method as

<?php

class CustomForm extends Zend_Form

{

            public function init()

            {

               }

}

 

That’s it, we have now created our custom form. Keep in mind that we haven’t added anything to our form yet.

You can see how easy it is to create form in Zend Framework.

Next step is to add some elements to it.

 In your init() method write the following statements.

 

$firstname = $this->createElement(‘text’,’firstname’);

$firstname->setLabel(‘First Name:’);

$this->addElement($firstname);

 

In the first line, I called the createElement() method of the Zend_Form passing two parameters “text” and “firstname”. The first parameter tell Zend_Form that I like to create text element of the html form and the second parameter is set as name and id of the form. In the next line I set the label to the form element and finally I add element to the form using addElement() method.

Using the above method you can create as many element as possible and add them to your custom Zend Form.

Another very nice thing, about Zend Framework form, I would like to discuss is that Zend provide separate class for different form elements like

 

$firstname = Zend_Form_Element_Text(‘firstname’);

$firstname->setLabel(‘First Name:’);

$this->addElement($firstname);

 

In the above code I used Zend_Form_Element_Text for creating text element of the form,  passing element name/id as parameter.

The class available for creating different form elements are

 

Zend_Form_Element_Button

Zend_Form_Element_Captcha

Zend_Form_Element_Checkbox

Zend_Form_Element_File

Zend_Form_Element_Hidden

Zend_Form_Element_Hash

Zend_Form_Element_Image

Zend_Form_Element_MultiCheckbox

Zend_Form_Element_Multiselect

Zend_Form_Element_Password

Zend_Form_Element_Radio

Zend_Form_Element_Reset

Zend_Form_Element_Select

Zend_Form_Element_Submit

Zend_Form_Element_Text

Zend_Form_Element_Textarea

 

You can use either of the above to create each of these element.

Beside creating different form element you can add validator, filtors and decorator on each form element.

What are validator?

Validator are used to ensure that the submission is valid.

For example you want that the form specific elements shouldn’t be empty. i.e you don’t want the form to be submitted untill and unless some specific element are filled, or you may want the data entered in some elements must be alphbetic only etc. So validator come handly for this purpose.

How to add validators to the Form element?

Its very simple, write the following line of code

 

$firstname->addValidator(‘NotEmpty’);

 

This means that the form will not be submitted untill and unless you entered something in the firstname form element.

If you want that the data entered in the firstname should all be alphabetic characters. Then you will need to add the following line of code.

 

$firstname->addValidator(“Alpha”);

 

The most valuable example would be to validate a specific form element against valid email address. This is extremely easy in Zend Framework Zend_Form. Add only the following line of code.

 

$email->addValidator(‘EmailAddress’);

 

Following validators are shipped with Zend Framework.

 

Alnum

Alpha

Barcode

Between

Ccnum

Date

Digits

EmailAddress

Float

GreaterThan

Hex

Hostname

InArray

Int

Ip

LessThan

NotEmpty

Regex

StringLength