Zend Framework

Archive for May, 2009

Make your children listen to you

Posted by Faheem Abbas on May 31, 2009

I almost always read Sunday “dawn” and find very useful article touching heart and soul.

I think it would be worthy writing a summery about one of them and give my own opinion as well.

Today an article written by Gulrukh Tausif was fabulous. Though I am single and like to be for some time at least for some months if not years, however the tips about children she has given are worthy to be remembered and passed along in the circle.

These tips are

Let them know their boundaries

You need to tell your children what behavior is acceptable in the house and what is not.

Remind them what you want them to do and then make sure its get done on the appointed time. Parents if firm and consistent to put children to work on certain time, can easily achieved it and will get no complaint what so ever once children get used to it.

Don’t give a child a chance to argue

If your child is glued to certain task, give him an ultimatum and walk out of the room. Don’t give him chance to countermand you. Just say that I’m going out and when I’ll get in you must be on your table doing your home work.

Always mean what you say

Well, this is the most important one and I’ve seen many parents doing so. When a child cross his boundary, parents give an ultimatum that If he do the same again he will be punished, but when child repeat that again parent do nothing. This gives the child a sense that all these are idle threats. Make sure you follow what you say and what you mean.

Keep criticism to the point

Your explanation should be as short as possible, because most children cannot endure long lectures and their brain automatically tune off after the first 30 seconds or so.

I’ve seen parent giving long lecture and the end result is nothing. So stick to the point rather then a long lecture.

Modify your own behavior

If you mange to follow this tip you are half done. I’ve seen people telling children to follow rules that they even themselves don’t follow. Children learn more from your actions than from what you say. If you don’t listen to them they won’t listen to you next time. Give them full attention when they need. Next time when you need attention they would give it to you.

Explain your reasons

Nowadays children question everything and anything. Give them logical reasons instead of bossing them around. If they don’t brush their teeth or don’t concentrate on their homework, tell them pros and cons instead of crying and forcing them to do so.

Always use positive reinforcement

Praise you kid for each and every good little thing he does especially if he does it without your saying. Always say “Please” and “Thank you” and they will jump to fulfill your every command.

Listen to their problems

Your children shouldn’t be shy while telling you his problem. You must be closer to your children like his friends, so that he share everything with you. No matter how busy or tired you are, ask your children about their school, homework, teachers and classmates.

Be there for them

Put your kids need before your own. A bored, tired, hungry, sleepy or sick child is more likely to misbehave and flout your wishes. Cut shot the telephone call, switch of your TV, put down your latest best seller and see to their needs first.

Posted in Musings | 1 Comment »

Zend Framework and Facebook: writing a simple facebook application in Zend Framework

Posted by Faheem Abbas on May 31, 2009

In the social networking era, who don’t know about facebook. One of the famous and widely adopted social networking applications, where you can connect to your friends and family.

One the other hand Zend Framework is widely adopted open source MVC framework build in PHP.

Facebook has its own API classes for interacting with application. It also has language called FBML facebook markup language, FBJS facebook javascript for using javascript in facebook application, FQL, facebook query language for fetching data from database. Keep in mind that FBML is subset of HTML with some elements removed, and some added that are specific to facebook application.

Zend Framework on the other hand shipped with its own component like Zend_Auth for authentication, Zend_Acl for Access Control List, Zend_DB for connecting and working with database, Zend_Form for creating html forms and so on.

One of the nice things about Zend Framework is the configuration overhead and the use of component that are not tightly coupled.

To have a good understanding of both, I’d suggest you to read the documentation of both.

In this article I’m going to discuss how you can create a simple facebook application in Zend Framework.

Before Starting, download Zend Framework, create facebook application using faceboo.com/developers and download client library.

Once you successfully downloaded the facebook library. Next step is to create an appropriate directory structure.

I have the following directory structure.

Directory structure for creating facebook application in ZF

Directory structure for creating facebook application in ZF

well, don’t over think. The most important are application directory containing all our controllers, models and views.

The library directory contain two folders, facebook-platform that contain the facebook client library and Zend directory contain all the components shipped with Zend Framework.

The most important file here is index.php which serves as bootstrap file, getting all request from users and route them to specific controller/action.

 

The code you will need to include in this bootrap file(index.php), look like this.

<?php

require_once ‘facebook-platform/php/facebook.php’;

$appapikey = ‘dc42122221bc005c9d1153404a39a32667′;

$appsecret = ‘3e5c872ba5c7wew33204f2d153503f37′;

$appcallbackurl = ‘exmaple.com’;

$facebook = array(

                                    ‘appapikey’ => $appapikey,

                                    ‘appsecret’ => $appsecret,

                                    ‘appcallbackurl’ => $appcallbackurl

);

 

 

require_once “Zend/Loader.php”;

Zend_Loader::registerAutoload();

 

$registry = Zend_Registry::getInstance();

$registry->set(‘facebook’,$facebook);

 

$frontController = Zend_Controller_Front::getInstance();

$frontController->throwExceptions(true);

$frontController->setControllerDirectory(‘/application/controllers’);

$frontController->dispatch();

 ?>

This is the minimum code required.

The most important lines for facebook application are first few lines, where we are using require statement to include facebook.php file. Define a variable having own facebook application key, secret key and back url. We define an array and store all these information.

Once array of these facebook variable has been defined we get instance of Zend_Registry and set “facebook” to facebook array defined earlier for future use.

Next we get instance of front controller, set controller directory and call method dispatch.

That’s it. We have now properly defined our bootstrap file.

 

Next step is to create our first controller and define template files.

Go to application/controllers/ and create a file called IndexController.php and write the following code in it.

 

<?php

class IndexController extends Zend_Controller_Action

{

           

            public function indexAction()

            {

                        $face = Zend_Registry::get(‘facebook’);

                        $facebook = new Facebook($face['appapikey'], $face['appsecret']);

                        $user = $facebook->require_login();

                        try {

                        // If app is not added, then attempt to add

                        if (!$userId = $facebook->api_client->users_getLoggedInUser()) {

                                                $facebook->redirect($facebook->get_add_url());

                                    }

                        } catch (Exception $ex) {

                                    // code for handling exception

                        }

                        $friends = $facebook->api_client->friends_get();

                        $this->view->friends = $friends;

                        $this->view->user = $userId;

                       

            }

}

 

Here we have inherited our class from Zend_Controller_Action. And defined a single action named indexAction.

 

The first line

$face = Zend_Registry::get(‘facebook’);

return an array we earlier set in our bootstrap file. This array contain application key, secret key and call back url.

Next we create facebook application object, giving it application key and secret key.

Once we created the object, we call require_login() method. This will force user to logged in to facebook before moving forward.

Logging in is compulsory for fetching information from the facebook application.

Next we check if user has logged in by calling users_getLoggedInUser(). If not logged in we redirect user to the facebook log in page.

This user_getLoggedInUser() return ID of the current logged in user.

Next we get the friends of the user by using another useful method friends_get().

After getting this information, we assign it to our view as.

$this->view->friends = $friends;

$this->view->user = $userId;

That’s it. This is our simple controller/action.

Next step is to create our view and put the code we want.

For this, go to application/views/scripts/index/index.phtml. If this file has not been created, create one and put the following code in it

.

<?php

echo “<p><h4><fb:name uid=\”$this->user\” useyou=\”false\”/></h4></p>”;

echo “<p><h5>You have following friends</h5></p>”;

echo “<ul>”;

foreach ($this->friends as $friend) {

            echo “<li><fb:name uid=\”$friend\” useyou = \” fasle \” />”;

}

echo “</ul>”;

?>

To have a look what this is the output of this, browse

http://apps.facebook.com/orakzai/        

Any query and suggestion would be welcomed.

Posted in Zend Framework | 2 Comments »

PHP: using __autoload() for automatically loading php files

Posted by Faheem Abbas on May 30, 2009

Object oriented programming give great strength to PHP. Now if you need to work on large web application, it’ll be nice to identify entities and construct separate class for each.

Mostly the entities identified in the analysis phase need a separate database tables. So it would be better to define a separate class for each of your database table. The class created encapsulates attributes and methods.

Give it a try, and honestly you will feel lot of strength of object oriented programming.

For example, we have a database table named users, having id, username, email and address.

You can define your table for this table as

<?php

class Users

{

private $_id;

private $_username;

private $_email;

public function __construct()

{

// code for connecting to the database

}

public save($data)

{

// code for saving user data.

}

}

Well, this isn’t a perfect definition of the class, however you can get an idea from this and construct your own according to your needs/requirements.

Large web application often need lots of require/require_once statements.

If you define a separate class for each of you business entity and need multiple classes in a single page, you will need to write as many require statements as the classes you need.

If your application page needs five php files, you will need to write five require statements.

The people behind PHP has given a very simple solution to get rid of this. You need to define a simple __autoload() method in the page, which will load all the class you need using a single require statement.

Let have a simple example.

We have two separate class for person and car.

The person class is define as

<?php

class Person

{

private $_name;

public function setName($n)

{

$this->_name = $n;

}

public function getName()

{

return $this->_name;

}

}

And class Car is defined as

<?

class Car

{

private $_made;

public function setMade($m)

{

$this->_made = $m;

}

public function getMade()

{

return $this->_made;

}

}

Now if you need both these classes in the same file, you can either user two require statements as

require_once(‘person.php’);

require_once(‘car.php’);

And then create objects of each of these classes and call appropriate methods.

$person = new Person();

$car = new Car();

$person->setName(‘faheem’);

$car->setModel();

Although its simple to have two require statements, however if you need more, it becomes painful.

If you remove these two require statements, you will face “Class not found” fetal error.

Using __autoload() method you can get rid of these or as many requirement statements as you require.

Define the following function in the file where you create objects of different classes as

function __autoload($class) {

require_once($class.’.php’);

}

let we have a file named index.php where we need these classes. So our index.php will look like this.

<?

function __autoload($class)

{

require_once($class.’.php’);

}

$person = new Person();

$car = new Car();

$person->setName(‘faheem’);

$car->setModel();

?>

No matter, where you define this method, at the beginning or at the end, result will be the same.

Give it a try and let me know if you face any problem.

Posted in Php | 1 Comment »

PHP: Using DateTime Class to take the pain out of working with dates

Posted by Faheem Abbas on May 28, 2009

Well, since few days I’m writing about object oriented programming. Object orientation has many advantages over structural programming. It not only lessen your burden by allow you to achieve your desired results with less code, but also enable you to reuse your code in as much places as you wish in your application.

Implementation Object orientation give lot of strength to PHP. Many people may still stick to conventional programming, but all will one day stop writing code in old style structural programming and adopt object oriented programming instead.

I am not going to discuss the benefits of object oriented programming and down sides of conventional, but instead share some knowledge about DateTime class available in the latest version of php.

If you have some knowledge of php and have developed any application, you’ll certainly come across a requirement demanding usage of date or time.

In conventional programming displaying date need to write the following.

echo ‘Current date is ‘ date(‘m-d-y’);

It displays the following.

Current date is 05-28-09

While using the DateTime class, you will need to write the following.

$date = new DateTime();

echo $date->format(‘l, F jS, Y’);

This gives the following result.

Thursday, May 28th, 2009

Well, you may feel that the conventional method is more easy to use, as it only require one line of code.

The Usage of the DateTime class comes handy when you wish to perform some complex tasks.

For example, if you like to display the next Thursday, you will need to writ the following code.

$date = new DateTime(‘next Thursday’);

echo $date->format(‘l, F jS, Y’);

The result of the about would be.

Thursday, June 4th, 2009

As today is Thursday, May 28th, 2009

Only passing “next Thursday” to the constructor, it display the next Thursday for us.

This is one simple usage of the DateTime class. Lets look at some other useful methods of this class.

To have the current date, write

$date = new DateTime();

If you want to set specified date, you can do it either by passing string argument to its constructor as

$date = new DateTime(“18-July-2008 16:30:30”);

And then display as

echo $date->format(‘l, F jS, Y’);

Or call empty constructor and then use setDate method as

$date = new DateTime();

$date->set(“year”,”month”,”day”);

For example

$date->setDate(“2008″,”05″,”18″);

Similarly you can set time as

$date->setTime(int $hour, int $minutes [, int $seconds]);

For example

$date->setTime(“16”,”30”,”30”);

Another useful method is modify for modification of the date time.

If you want to add a day to the current date, write

$date = new DateTime();

$date->modify(“+1 day”);

This add a single day to the current date and display the next day.

Similarly if you want to subtract a day, write

$date->modify(“-1 day”);

Also you can add and subtract month and years as

$date->modify(“+1 month”);

$date->modify(“+1 year”);

And

$date->modify(”-1 month”);

$date->modify(“-1 year”);

If you want to get the time zone, writ an single line

$date->getTimeZone()->getName();

And similarly setting time zone can be done like this.

$date->setTimeZone(new DateTimeZone(“Asia/Karachi”));

Posted in Php | 1 Comment »

PHP: Method chaining using object oriented programming

Posted by Faheem Abbas on May 27, 2009

While in my previous article I discussed some of the nice thing of object oriented programming. Inheritance –creating sub classes from inheriting parent, contain all the attributes of the parent class plus its own. Polymorphism, means different form, like overloading and overriding methods and dynamic binding- deciding which class in the inheritance tree should be called on runtime, are techniques that give great benefits to programmers.

In this article I am going to show you a simple but very useful trick while using “this” keyword for method chaining. “this” when use in the class refer to the same class.

Consider the following example.

class Person {

protected $_name;

protected $_age;

protected $_gender;

public function setName($name) {

$this->_name  = $name;

}

public function getName() {

return $this->_name;

}

public function setAge ($age) {

$this->_name  = $age;

}

public function getAge() {

return $this->_age;

}

public function setGender($gender) {

$this->_gender  = $gender;

}

public function getGender() {

return $this->_gender;

}

}

While in object oriented programming it’s always a good practice to define getter and setters.

To create an object of the above class and define person properties, we will need to write the following code.

$person = new Person();

$person->setName(“person_name”);

$person->setAge(24);

$person->setGender(“male”);

And now If you want to get these values, write

$person->getName();

$person->getAge();

$person->getGender();

Well, if you want to set values using a single statement, you will need a code similar to this.

$this->setName(‘person_name’)->setAge(24)->setGender(“male”);

To achieve this, you will need to write the following statement in all your setters.

public function setName($name) {

$this->_name  = $name;

return $this;

}

The only thing we need here is “return $this”. This statement return a reference to the same object.

Place this statement in your setAge() and setGender(), and now you can write

$this->setName(‘person_name’)->setAge(24)->setGender(“male”);

for setting all the three properties

Posted in Php | 3 Comments »

PHP: Object Oriented Programming

Posted by Faheem Abbas on May 26, 2009

Object oriented programming concepts were introduced in PHP version 1.4, I guess.

How many people around you play with object oriented programming?

If not working in any kind of MVC frameworks, I guess very short number of people.

Developers are often used to structured programming and don’t bother themselves learning object oriented programming concepts and paradigm.

Well, when software engineers realized that it’d become very difficult to manage and maintain thousand lines of code, object oriented programming was introduced. Since then dramatic improvements have been done to OOP.

In object oriented programming inheritance, polymorphism, encapsulation, dynamic binding and exception handling has great usage and advantage, however class and objects are the most basic concept.

Class is blue print containing properties and method associated with same entity. Object is the instance of the class and is used to access properties and method of the class.

In addition to OOP, design pattern make jobs easier for the programmers.

Singleton, factory and specially MVC design patterns are very useful these days.

In singleton design pattern one object of the class exist throughout the life cycle of the software application. If programmer tries to instantiate another object of the same class, a reference to the object instantiated earlier, is granted.

A class implementing factory design pattern works as bridge between multiple classes. Consider an example of using multiple database servers like SQL Server and Oracle. If you are developing an application using SQL Server database as backend, but in future need to change backend database to oracle. Without using factory design pattern, you will need to modify all your code.

In factory design pattern you need to do very little work to achieve this. A class implementing factory design pattern takes care for you and lessen your burden.

In MVC design pattern M stands for Model. Model contains your application’s business logic.

V stands for View. It’s the presentation layer.

While C stands for controller that work as glue between view and model.

Posted in Php | 2 Comments »

Bloging experience

Posted by Faheem Abbas on May 26, 2009

It’s been months since I’m writing my blog. So far so good. When facing situation like we confront in Pakistan, believe me writing and helping other give lot of relief.

I dramatically started writing my blog when I met Singaporean who is a web developer and entrepreneur. Initially it was like taking a bull by horn, but with the passage of time I got used to it and now I can easily write articles.

There may be grammatical as well as spelling mistake in my articles, however software engineer and developer don’t care much about this.

Posted in Musings | Leave a Comment »

Old Posts: Maxing HTML and PHP code

Posted by Faheem Abbas on May 25, 2009

After working for about one year in website development industry of Pakistan I’ve realized a very serious issue. This may be happening in other countries as well, as I haven’t had worked with international organization, especially professionals.

The problem is maxing presentational logic with business logic. In simple words I would say maxing HTML with server scripting language like php, asp, coldfusion etc.
Here I would appreciate Microsoft professionals who have done tremendous job by developing Asp.net language. The way they have separated asp.net and html code from C# and VB.NET code is fabulous. However I would like to mention that in the beginning-in early versions of ASP.NET-the problem was there. However with the passage of time and introducing newer and more mature versions like ASP.NET 2.0 they have addressed lots of issues.
Before going into the details of problem mentioned above I would also like to comment about some companies who are providing open source solutions for languages like PHP etc. The contribution made by oscommerce (having the above drawback), zencart(I haven’t studied but heard that it is a bit mature shopping cart solution than oscommerce) and joomla(very nice and more mature content management system) to php cannot be ignored.
The most important contribution is made by those who have developed frameworks(MVC’s) like Zend, Symfony, cakePhp, mojave(lacking documentation and community support) etc. One cannot imagine how worthy and brilliant job they have done and how easier they have made work for lazy professionals like me.

Two months back I was introduced to mojavi by our company senior web developer. In the first few days I was exhausted and bored. However after developing a simple login application in mojavi I found it quite helpful. But things didn’t move forward coz of lacking documentation and community support.

I stopped working in mojavi but the virus of working in frameworks sneak in my heart and I started googling different frameworks.

Next few days I studied cakePhp, symfony and then zend, red their documentation, browse their community support sites and forums and also red articles about their differences.

Finally and luckily I selected Zend framework-This was because of small configuration overhead of zend framework than other frameworks.

After working in zend MVC I realized how easier it is to make a web application and how easy it is to extend and maintain existing one.

Now let me discuss the real problem which has made me sick since last few days.

After joining new organization 6 days back I was assigned a project for modification. The project was constructed in oscommerce. Boss was expecting that I would finish some small modification in few hours but I trapped in the middle and was unable to browser where modification needs to be made.

When boss arrived and asked me about the modification I was having no idea what to say and I felt a bit shy at that time. After telling him that I haven’t completed the modification he was a bit shocked and worried because he might be thinking that I was not a right person for the post I had been hired. He took me to his office and asked me about projects I had previously worked on. After showing him my projects he got satisfied but still I could see uncertainty in his eyes.

Why all this happened and why I trapped in the middle will I think clear the problem I have mentioned in the beginning..

As I have already mentioned that project was constructed in oscommerce so those how know or have worked in oscommerce will better understand the way oscommerce has been developed. Although they have separated php code form html up to some extent, however it is not as mature as joomla content management system or model view controller frameworks.

Well, oscommerce was not a big obstacle. The more irritating thing was the way previous programmer had implemented and constructed the pages. After working in office for about 10 hours I managed to complete some modifications but not entire.

When I came home, installed oscommerce and started doing the same modifications it took me minutes to complete them.

So I took some deep breathes and started thinking about whom to be blamed. But after thinking for about two hours I realized that no one could be blamed because client needs their projects soon, so developers only think about the construction not about what will happen in future if he himself or someone else try to extend or modify the project.

Lot of website have been made in similar scenarios and situations.

So as a professional one needs to be very careful while modifying the project.

Although professional developed application based on the client recommendations however I think we professional should think seriously about the future extensions and maintenance and try to make application both client and professional friendly.

Note : This article was written about one year ago.

Posted in Old Posts | 2 Comments »

Joomla and Zend: creating joomla component in Zend Framework

Posted by Faheem Abbas on May 15, 2009

Joomla is a nice CMS(content management system) and Zend Framework is once of the famous and widely adopted MVC Framework since its first release. One of the nice thing about Zend is its loosely coupled components.

Keep in mind that  component in joomla and Zend Framework don’t refer to the same concept. Those who have worked in Joomla and Zend Framework know the difference.

In this article I’m not going to discuss what Zend and Joomla are all about and how component is different in both, but instead I’m going to share a little secret of how to develop joomla component in Zend Framework.

This article is not for those who are unaware of joomla and Zend.

Although joomla has own API for developing its components and modules, but you can use any php code in addition to its own API.

Reason is simple. Joomla is developed in php.

As Zend also used php behind the scene, so both can interact easily.

This was a bit of introduction.

While discussing all these things I assumed that you have little knowledge of joomla and have some knowledge of Zend Framework as well.

So let’s dig in.

Before writing any code you will need to successfully download and install joomla. Also download Zend and save it in the directory of your choice.

Once successfully installed joomla, open joomla/administrator/components and create a folder called com_yourcomp.

This is your component folder. You will need to create a file named yourcomp.php

If you want to add component in your administrator, the name should be admin.yourcomp.php.

That’s it, you have now created a the necessary directory structure for your joomla component development.

If you write a line “Hello world!” in youcomp.php or admin.yourcomp.php and browse your page as

http://localhost/joomla/index.php?option=com_yourcomp

you will see

“Hello world” printed.

These are the minimum requirements for developing joomla component.

Now we will using Zend Framework classes to add code to this file plus we will create Zend directory structure in order to work with Zend MVC.

Create following directory structure in your joomla/administrator/components.

Directory structure for joomla component in zend.

Directory structure for joomla component in zend.

“Read full version here”. http://zendgeek.blogspot.com/2009/07/joomla-component-in-zend-framework.html

Posted in Joomla | Tagged: | 9 Comments »

PHP Extensions: Understanding and working with hash API Part 1

Posted by Faheem Abbas on May 10, 2009

Hash table is collection. It is specialized form of doubly linked list. As it’s heavily used in zend engine and PHP Core, so therefore an entire subset of API is devoted to it.

Hash table is important because

  1. All upper space variable are stored in hash table.
  2. Hash table can store any piece of data of any size

General syntax for initializing hash table is

zend_hash_init(HashTable *ht, uint nSize,

hash_func_t pHashFunction,

dtor_func_t pDestructor, zend_bool persistent);

Here

ht is pointer to HashTable variable.

nSize is maximum number of elements that HashTable is expected to hold. It will always be power of 2.

pHashFunction  is no longer used in new versions, so it must always be NULL.

pDestructor is pointer to function that is called whenever an element is removed such as when using zend_hash_del or zend_hash_update.

The prototype of the destructor must be

void method_name(void *pElement)

Where pElement is pointer to the element to be removed.

The final option, persistent is flag passed by zend engine to the pemalloc() function.

An example of initializing the hash table can be

zend_hash_init(&EG(symbol_tabel), 50, NULL, ZVAL_PTR_DTOR, 0);

Populating the hash table

The following functions are used to populate HashTable.

  1. int zend_hash_add(HashTable *ht, char *arrKey, uinit nKeySize, void *pData, uinit nDataSize, void **pDest)
  2. int zend_hash_update(HashTable *ht, char *arrKey, uinit nKeySize, void *pData, uinit nDataSize, void **pDest)
  3. int zend_hash_index_update(HashTable *ht, ulong h, void *pDate, uinit nDataSize, void **pDest)
  4. int zend_hash_next_index_insert(HashTable *ht, void *pData, uinit nDataSize, void **pDest)

Let’s have a look at some examples

If you want to represent $foo[“bar”] = “baz”; write

zval barValue;

MAKE_STD_ZVAL(barValue);

Z_TYPE_P(barValue) = IS_STRING;

Z_STRVAL_P(barValue) = “baz”;

S_STRLEN_P(barValue) = sizeof(‘baz’) + 1

zend_hash_add(fooHashTable, “bar”, sizeof(“bar”), &barValue, sizeof(zval *), NULL);

Some time you will need to find the free element before performing insert, update etc on the Zend table. In this case you can get the next free element by writing

ulong nextid = zend_hash_next_free_element(ht);

and now perform update as

zend_hash_upate(ht, nextid, &data, sizeof(data), NULL)

Finding data in HashTable

In the above paragraphs I discuss how to initialize and populate HashTable, Here I’d discuss how to find particular key/index value in the HashTable

Two methods are used.

One if you want to find value of particular key in case of associative array. The syntax as

int zend_hash_find(HashTable *ht, char *key, uint nKeySize, void **pData);

And the other function is used to find value at specified index in case of indexed array.

The general syntax of the method is

int zend_hash_find(HashTable *ht, ulong index, void **pData);

Another very important functionality Hash API provide is to check whether or not the specified key or index exists. Two method are used for this purpose.

zend_hash_exists(HashTable *ht, char *key, unit nKeySize);

This method is used to check the key in case of associative array.

While

zend_hash_exists(HashTabel *ht, ulong index);

The upper space function for checking the key is

isset($foo);

To achieve this using Hash API, use

zend_hash_exists(EG(active_symbol_table), “foo”, sizeof(“foo”));

This function will return true or false.

Iterating through HashTable

Hash API provides some useful functions for iterating through hash table.

  1. zend_hash_apply(HashTable *ht, (apply_func_t) apply func TSRMLS_DC);
  2. zend_hash_apply_with_argument(HashTable *ht, (apply_func_arg_t) apply_func void *data TSRLMS_DC);
  3. zend_hash_apply_with_arguments(HashTable *ht, (apply_func_args_t) apply_func, int numargs, …)

Each of the apply_func_t return the following

  1. ZEND_HASH_APPLY_KEEP
  2. ZEND_HASH_APPLY_STOP
  3. ZEND_HASH_APPLY_REMOVE

Beside these functions there are some other useful functions for working with HashTables.

Try these functions as well

  1. zend_get_hash_value(char *arrKey, uint nKeyLen);
  2. zend_hash_quick_add(HashTable *ht, char *arKey, uint nKeyLen, ulong hashval void *pData, uint nDataSize, void **pDest);
  3. zend_hash_quick_update(HashTable *ht, char *arKey, uint nKeyLen, ulong hashval void *pData, uint nDataSize, void **pDest);
  4. zend_hash_find(HashTable *ht, char *arKey, uint nKeyLen, ulong hashval, void **pDest)
  5. zend_hash_quick_exists(HashTable *ht, char *arKey, uint nKeyLen, ulong hashval);

Destruction

There four method you need to keep in mind while removing element(s) from HashTable.

  1. zend_hash_del(HashTable *ht, char *nKey, uint nKeySize);
  2. zend_hash_index_del(HashTable *ht, ulong h)
  3. zend_hash_clean(HashTable *ht)
  4. zend_hash_destroy(HashTable *ht)

The first two method remove single element from the HashTable.

zend_hash_clean iterate through each element and clean the entire hash table.

zend_hash_destroy all the function of zend_hash_clean plus free the structure allocated during zend_hash_init.

While working with the hash table, you may need the following as well

HashTable *ht;

// allocate memory

ALLOC_HASHTABLE(ht);

// initialize it internal state

zend_hash_init(ht, 50, NULL, ZVAL_PTR_DTOR, 0);

// destroy the hash table

zend_hash_destroy(ht);

// free the hash table itself

FREE_HASHTABLE(ht);

Posted in PHP Extensions | Leave a Comment »