I worked on enterprise level application for one year using Eclipse, Php Designer, and Dreamweaver. We were using Eclipse for checking in and out (updating and committing)
When I joined the team, configuration was already in place in the Eclipse, so I never intend to make configuration. Whenever configuration needed, Team lead was up to the task and was responsible for the entire configuration. I came across new terms like SVN, Commit, and Update for the first time as I was using cute ftp for uploading and downloading files from server before.
Here our job was to write code, complete tasks and commit them using our team lead system. First job in the morning was to update the change as some developers were making change to our project in United States. Our team lead system went of order few times during this period, but we were always looking toward him for the configuration. I remember that once he configured everything on my system, but I never intended to look how everything are done.
Today I found myself stuck in the middle. As I’m going to start working on new project, I tried to do the entire configuration myself.
Believe I was having no clue how to do it. Thanks to some nice soul out there on the internet who have posted the entire step by step procedure. I am going to write those steps for you.
Import project in Eclipse
1. File >> New >> Project >> SVN >> Checkout projects from SVN
2. Next
3. Create a new repository location
4. Next
5. Enter URL as
http://yourserver.com/alpa_proj
6. Next
7. Select the directory
8. Next
9. Choose: checkout as project configured using the New Project Wizard
10. Finish
Thursday, September 17, 2009
Wednesday, August 26, 2009
Maxing HTML and PHP code
Note: This article was written in 2008, when I was working in small firm. Publishing it again here for newbies.
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.
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.
Labels:
Php
Tuesday, August 18, 2009
Installing Ruby on rails in four easy steps
Ruby on rail is used for web application development.
Ruby is object oriented language.
Rail is framework that uses Ruby language to develop robust and scalable web application.
Ruby on rail installation is simple, newbie however find it a bit tricky first.
Here in this article I am going to tell you how can Ruby on rails be installed in windows XP.
1. Download latest version of Ruby from http://rubyforge.org/projects/rubyinstaller/
2. after the installation double click the exe file. this will start setup wizard which will guide you to the end.
3. once Ruby is installed next step is to set path
=>start => control panel => system =>advance => environment versiables
click path and press edit.
add
at the end of the path, I assumed that you have installed Ruby in drive c.
press oK.
4. now in command prompt
write
when the process completed, write
you have done. now its time to create your first project
in command prompt, write
Once the projec is create, in command prompt, write
now browse
http://localhost:3000/
you will see ruby on rails welcome page.
Ruby is object oriented language.
Rail is framework that uses Ruby language to develop robust and scalable web application.
Ruby on rail installation is simple, newbie however find it a bit tricky first.
Here in this article I am going to tell you how can Ruby on rails be installed in windows XP.
1. Download latest version of Ruby from http://rubyforge.org/projects/rubyinstaller/
2. after the installation double click the exe file. this will start setup wizard which will guide you to the end.
3. once Ruby is installed next step is to set path
=>start => control panel => system =>advance => environment versiables
click path and press edit.
add
;C:\Ruby\bin
at the end of the path, I assumed that you have installed Ruby in drive c.
press oK.
4. now in command prompt
write
gem update --system
when the process completed, write
gem install rails
you have done. now its time to create your first project
in command prompt, write
rails firstproject
Once the projec is create, in command prompt, write
cd firstproject
ruby script/server
now browse
http://localhost:3000/
you will see ruby on rails welcome page.
Labels:
Ruby on Rails
Public transport some facts
Public transport (also public transportation or public transit or mass transit) comprises passenger transportation service which is used by public [1].
An important role played by public transport in the society is to enable all the member of the society to travel, not only those having driving license and have access to their own automobiles.
Public transport like all other services and facilities in the third word countries is a real dilemma. Elite, which mostly uses their own private automobiles and vehicles, like all other public institutions, organization and facilities, rarely consider improvement in these services. As they never ever use it, so why care about it?
The fact however is, if government gave proper resources and made some improvements, public transit can play a very vital role in generating fair amount of revenue.
Traffic jam which is a real problem in the big cities can be decreased be providing well-designed transport system which is considered more dense then private transport.
I have been using public transport in my beloved country for the last two year, and can say that it has made me mentally sick.
People behave like animals. I am not blaming them for behaving like this, as they are put like animals in buses. They don’t care walking on your feet and pushing with their hands.
Young people specially students stand near entrance, making it hard for the people to get in and out.
Situation become even more deteriorating when a person with his bag selling books, handkerchiefs, toffees, and homeopathic medicines arrived in crowd and start speech explaining benefits of the product he owns.
Beggars also contribute to the noisy environment, trying hard to collect money for no work.
An important role played by public transport in the society is to enable all the member of the society to travel, not only those having driving license and have access to their own automobiles.
Public transport like all other services and facilities in the third word countries is a real dilemma. Elite, which mostly uses their own private automobiles and vehicles, like all other public institutions, organization and facilities, rarely consider improvement in these services. As they never ever use it, so why care about it?
The fact however is, if government gave proper resources and made some improvements, public transit can play a very vital role in generating fair amount of revenue.
Traffic jam which is a real problem in the big cities can be decreased be providing well-designed transport system which is considered more dense then private transport.
I have been using public transport in my beloved country for the last two year, and can say that it has made me mentally sick.
People behave like animals. I am not blaming them for behaving like this, as they are put like animals in buses. They don’t care walking on your feet and pushing with their hands.
Young people specially students stand near entrance, making it hard for the people to get in and out.
Situation become even more deteriorating when a person with his bag selling books, handkerchiefs, toffees, and homeopathic medicines arrived in crowd and start speech explaining benefits of the product he owns.
Beggars also contribute to the noisy environment, trying hard to collect money for no work.
Labels:
Musings
Tuesday, August 11, 2009
Dojo: Creating image using dojo script
Dojo provides numerous functionality like:
1.Easy and smooth creation of different widget such as dojo grid, forms, datapicker, calendar etc.
2.Prolific method of interacting with html elements.
3.Achievement of ajax functionality with far more less code.
In this article I am going to discuss how to create an image element using dojo script and attach that image to certain html element.
In order to achieve functionality on loading the page, you will need to use dojo.addOnLoad() method. This takes the following form.
Now in the next few lines we are going to put the actual functionality.
The most important things here are extending dojo.NodeList and then adding addImage function that initially has nothing, but we are going to add real functionality to it later on. This addImage method will contain the functionality for creating an image.
The question here however is, why we extend NodeList.
Well this is pretty simple. If you want to achieve functionality like;
dojo.query(‘input[id=name]’).addImage().removeClass(‘complusory_image’);
you will need to extend you method from NodeList. Doing so will enable you to access entire NodeList method in the way above.
Don’t worry about dojo.query() method, I will explain it shortly for you.
Now lets put the real script for creating img tag in our addImage method.
In the first line we have created img tag. In the second line we have attached different attributes to the img. You can define as many valid attributes associated with img tag as you wish.
The code in the addImage function looks, however, a bit different. See the following code.
The function for addImage contain args as parameter. This means that the image tag created can be attached to as many html elements as you like. In the forEach loop we create image tag and attach at to the arguments passed to it.
Now in the dojo.addOnLoad function, at the end, write the following script.
The above script states that attach an image to input tag having id equals to name.
It you want to attach element to all input tags on your page, write
The final script on my page look like this.
1.Easy and smooth creation of different widget such as dojo grid, forms, datapicker, calendar etc.
2.Prolific method of interacting with html elements.
3.Achievement of ajax functionality with far more less code.
In this article I am going to discuss how to create an image element using dojo script and attach that image to certain html element.
In order to achieve functionality on loading the page, you will need to use dojo.addOnLoad() method. This takes the following form.
<script>
dojo.addOnLoad(function(){
alert(‘called on load of page’);
});
</script>
Now in the next few lines we are going to put the actual functionality.
<script>
dojo.addOnLoad(function(){
dojo.extend(dojo.NodeList, {
addImage: function() {
return this;
}
});
});
</script>
The most important things here are extending dojo.NodeList and then adding addImage function that initially has nothing, but we are going to add real functionality to it later on. This addImage method will contain the functionality for creating an image.
The question here however is, why we extend NodeList.
Well this is pretty simple. If you want to achieve functionality like;
dojo.query(‘input[id=name]’).addImage().removeClass(‘complusory_image’);
you will need to extend you method from NodeList. Doing so will enable you to access entire NodeList method in the way above.
Don’t worry about dojo.query() method, I will explain it shortly for you.
Now lets put the real script for creating img tag in our addImage method.
var img = dojo.doc.createElement('img');
dojo.attr(img, {
src: "path/to/imges/img.png",
alt: "This is my simple image",
style: {cursor: "pointer"}
});
In the first line we have created img tag. In the second line we have attached different attributes to the img. You can define as many valid attributes associated with img tag as you wish.
The code in the addImage function looks, however, a bit different. See the following code.
<script>
dojo.addOnLoad(function(){
dojo.extend(NodeList, {
addImage: function(args){
this.forEach(function(n){
var img = dojo.doc.createElement('img');
dojo.attr(img, {
src: "path/to/imges/img.png",
alt: "This is my simple image",
style: {cursor: "pointer"}
});
dojo.place(img, n, "after");
});
return this;
}
});
});
</script>
The function for addImage contain args as parameter. This means that the image tag created can be attached to as many html elements as you like. In the forEach loop we create image tag and attach at to the arguments passed to it.
Now in the dojo.addOnLoad function, at the end, write the following script.
dojo.query(‘input[id=name]’).addImage();
The above script states that attach an image to input tag having id equals to name.
It you want to attach element to all input tags on your page, write
dojo.query(‘input’).addImage();
The final script on my page look like this.
<script>
dojo.addOnLoad(function(){
dojo.extend(NodeList, {
addImage: function(args){
this.forEach(function(n){
var img = dojo.doc.createElement('img');
dojo.attr(img, {
src: "path/to/imges/img.png",
alt: "This is my simple image",
style: {cursor: "pointer"}
});
dojo.place(img, n, "after");
});
return this;
}
});
dojo.query("input[id=name]").addImage();
});
</script>
Labels:
Dojo
Friday, July 31, 2009
Creating dojo datepicker with dojo script
Dojo date picker is nice and beautiful widget. The nice thing about any dojo widgets is that they can be easily attached to appropriate html tag. To assign date picker to input box take the following cod.
<html>
<head>
<script src=”path/to/dojo.js”>
require(‘dijit.form.DateTextBox’);
</script>
<style type=text/css>
@import "path/to/dojo/dijit/themes/tundra/tundra.css";
</style>
</head>
<body class= “tundra”>
<input type=”text” dojoType=”dijit.form.DateTextBox” name=”dd” id=”dd”/>
</body>
</html>
If you correctly include dojo.js and tundra.css, you will see a nice
Labels:
Dojo
Monday, July 27, 2009
Zend Framework, dojo and Json
I have already written about json in one, actually some of my articles. Cool functionality can be achieved using json. Thanks to http://www.json.org, http://www.zend.com and http://www.dojotoolkit.org for provide easier solutions.
I'm not gonna talk what these three are all about, but instead share a little secret about these.
Json creation in dojo is as simple as this.
Using Zend to convert array into json took only one line of code.
And decoding- converting json to array, is as simple as this
I'm not gonna talk what these three are all about, but instead share a little secret about these.
Json creation in dojo is as simple as this.
var arr = new Array();
arr[0] = “apple”;
arr[1] = “ball”;
arr[2] = “cat”;
dojo.toJson(arr);
Using Zend to convert array into json took only one line of code.
Zend_Json::encode($arr);
And decoding- converting json to array, is as simple as this
Zend_Json::decode(json_string);
Labels:
Dojo,
Json,
Zend Framewrork
Tuesday, July 14, 2009
Apache: Setting virtual host on localhost
It was up to this task since yesterday. I haven’t done this before, setting sub domain- virtual host on local system. I tried a lot yesterday but in vain, however when I came to office today I configured it successfully.
As I was stuck in the middle and feel lot of pain, so I better write it for those facing the same issue.
Why I was up to this task?
Well, actually my client was facing problem and reported that session is not working properly on domain and sub domain. So I was having no way other than setting virtual host.
However before leaving yesterday, I talked to my client that I am unable to solve this problem. He told me that I shouldn’t be worried about it because he will take care of this issue. The more important thing is that when I arrived today, I found that the problem has already been solved. Thanks to him for giving my favor.
Thought the problem has been solved, but still is worthy to write a small post here because I have successfully solved the problem.
Before going to discuss it, I would like to tell you that the configuration has been taken place on window so the paths may not be same.
Let have a look.
First of all you will need to open.
I assumed that you have install xampp.
And add following lines to httpd-vhosts.conf file.
Here I have defined server localhost pointing to my default htdocs directory and another host mysite.com.localhost pointing to "C:/xampp/htdocs/mysite/".
Another important thing is
Here you would need to specify the port. In my case its 80.
If you don’t specify the port on which apache listen, apache may take you to the same page for both the server. So be careful.
Next go to your Window/system32/dirvers/etc/ and open hosts file.
You will find
At the end of the file. Add following line next to it.
Reboot your system and you are done.
As I was stuck in the middle and feel lot of pain, so I better write it for those facing the same issue.
Why I was up to this task?
Well, actually my client was facing problem and reported that session is not working properly on domain and sub domain. So I was having no way other than setting virtual host.
However before leaving yesterday, I talked to my client that I am unable to solve this problem. He told me that I shouldn’t be worried about it because he will take care of this issue. The more important thing is that when I arrived today, I found that the problem has already been solved. Thanks to him for giving my favor.
Thought the problem has been solved, but still is worthy to write a small post here because I have successfully solved the problem.
Before going to discuss it, I would like to tell you that the configuration has been taken place on window so the paths may not be same.
Let have a look.
First of all you will need to open.
C:\xampp\apache\conf\extra\httpd-vhosts.conf
I assumed that you have install xampp.
And add following lines to httpd-vhosts.conf file.
NameVirtualHost *:80
<VirtualHost *:80>
ServerName localhost
DocumentRoot "C:/xampp/htdocs/"
ServerAdmin admin@localhost
</VirtualHost>
<VirtualHost *:80>
ServerName mysite.com.localhost
DocumentRoot "C:/xampp/htdocs/mysite/"
ServerAdmin admin@mysite.com.localhost
<Directory "C:/xampp/htdocs/mysite/">
Options Indexes FollowSymLinks
AllowOverride FileInfo
Order allow,deny
Allow from all
</Directory>
Here I have defined server localhost pointing to my default htdocs directory and another host mysite.com.localhost pointing to "C:/xampp/htdocs/mysite/".
Another important thing is
Here you would need to specify the port. In my case its 80.
If you don’t specify the port on which apache listen, apache may take you to the same page for both the server. So be careful.
Next go to your Window/system32/dirvers/etc/ and open hosts file.
You will find
127.0.0.1 localhost
At the end of the file. Add following line next to it.
127.0.0.1 mysite.com.localhost
Reboot your system and you are done.
Labels:
Apache
Method chaining in object oriented programming
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.
In object oriented programming it’s always a good practice to define getter and setters. In php you can define __set and __get as setters and getter.
To create an object of the above class and define person properties, we will need to write the following code.
And now If you want to get these values, write
Well, if you want to set values using a single statement, you will need a code similar to this.
To achieve this, you will need to write the following statement in all your setters.
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
for setting all the three properties.
Any suggestion is welcome. Cheers
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;
}
}
In object oriented programming it’s always a good practice to define getter and setters. In php you can define __set and __get as setters and getter.
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.
Any suggestion is welcome. Cheers
Labels:
Php
PHP: Object Oriented Programming
Object oriented programming concepts were introduced in PHP1.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 as well as impossible to represent real world object in computer world, object oriented programming was introduced. Since then dramatic improvements have been made to OOP.
In object oriented programming inheritance, polymorphism, encapsulation, dynamic binding and exception handling has great value, usage and advantages, 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, you will need to modify all your code, if you haven’t written your code following factory design pattern.
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. Switching from database server won’t bother you at all. You just need to make some small changes in your configuration file.
Revolution of MVC design patterns cause dramatic changes in software development life cycle. Prior to MVC, developers were mixing code all around. It was difficult to figure out where the business code resides and where presentation code is written. Intelligent software engineers, though, were trying hard to separate their business logic from presentation logic; this however wasn’t effective enough for new comers to understand their code and to do necessary maintenance. Without the help of the person behind the project, it’d taken more time to understand the directory structure used.
These draw backs were mostly addressed when MVC design patterns were introduced.
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. From glue I mean it takes data from view and give it to the model, model then process the data and produced desired results. The data, thus obtained, is given to the view. Controller can also be compared to event handlers. It responds to certain events such as posting the data back to server by clicking submitted data.
Hopefully I will unveil some other fact about OOP and design pattern later some time.
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 as well as impossible to represent real world object in computer world, object oriented programming was introduced. Since then dramatic improvements have been made to OOP.
In object oriented programming inheritance, polymorphism, encapsulation, dynamic binding and exception handling has great value, usage and advantages, 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, you will need to modify all your code, if you haven’t written your code following factory design pattern.
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. Switching from database server won’t bother you at all. You just need to make some small changes in your configuration file.
Revolution of MVC design patterns cause dramatic changes in software development life cycle. Prior to MVC, developers were mixing code all around. It was difficult to figure out where the business code resides and where presentation code is written. Intelligent software engineers, though, were trying hard to separate their business logic from presentation logic; this however wasn’t effective enough for new comers to understand their code and to do necessary maintenance. Without the help of the person behind the project, it’d taken more time to understand the directory structure used.
These draw backs were mostly addressed when MVC design patterns were introduced.
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. From glue I mean it takes data from view and give it to the model, model then process the data and produced desired results. The data, thus obtained, is given to the view. Controller can also be compared to event handlers. It responds to certain events such as posting the data back to server by clicking submitted data.
Hopefully I will unveil some other fact about OOP and design pattern later some time.
Labels:
Php
Monday, July 13, 2009
Create dojo tab cotainer in Zend Framework
Try online: Tab Container
In my previous posts I discussed how to create accordion container holding accordion panes and border container having content panes.
In this article I am going to show you how easy it is to create tab continer that hold contents panes. Each content pane having different contents. Contents in one tab pane are shown at a time. when use click on the tab pane's title, contents in that tab pane are shown.
Before reading this post, you better read and implement what I have discussed in my article "Zend Framework and Dojo: configuration". Before creating tab continer and panes, you will need to understand and perform necessary configuration.I assume that you have read the post I have mentioned and have done the necessary configuration. Now let's get started.
First of all, you will need to create your controller as
In the code above we have defined our ContainerController extending it from Zend_Controller_Action, and then we have defined our tabAction.
Now, the next step is to create tab.phtml in /application/views/scripts/container/ and place the following code in it.
Here we first call captureStart() method of tabContainer() dojo view helper, giving it an id, and array containing tab container special attributes. Next we define content panes. Each content pane holds the data. The contents panes in the tab container will become tab panes.
each content pane is defined as
Here "home" is the id of the content page, Next "string" is the contents that will appear in the tab pane. Next we have defined the array of the special attributes of the contents. Here title is the most important attribute. This title will appear on the tab. The last array contain css related attributes.
That's it. we have now written all necessary code for creating nice and beautiful Tab container.
Cheers.
In my previous posts I discussed how to create accordion container holding accordion panes and border container having content panes.
In this article I am going to show you how easy it is to create tab continer that hold contents panes. Each content pane having different contents. Contents in one tab pane are shown at a time. when use click on the tab pane's title, contents in that tab pane are shown.
Before reading this post, you better read and implement what I have discussed in my article "Zend Framework and Dojo: configuration". Before creating tab continer and panes, you will need to understand and perform necessary configuration.I assume that you have read the post I have mentioned and have done the necessary configuration. Now let's get started.
First of all, you will need to create your controller as
<?php
class ContainerController extends Zend_Controller_Action
{
public function tabAction()
{
}
}
In the code above we have defined our ContainerController extending it from Zend_Controller_Action, and then we have defined our tabAction.
Now, the next step is to create tab.phtml in /application/views/scripts/container/ and place the following code in it.
<?php
$this->tabContainer()->captureStart('main-container',
array('design' => 'headline'),
array(
'style'=>'height:400px;width:800px'
));
echo $this->contentPane(
'home',
'This is home page',
array('region' => 'top','title'=>'Home'),
array('style' => 'background-color: white;')
);
echo $this->contentPane(
'gallery',
'Contents of gallery here',
array('region' => 'left', 'title'=>'Gallery'),
array('style' => 'width: 200px; background-color: white;')
);
echo $this->contentPane(
'Blog',
'Blog post here',
array('region' => 'center','title'=>'Blog'),
array('style' => 'background-color: white;')
);
echo $this->contentPane(
'about',
'Information about your company etc',
array('region' => 'bottom', 'title'=>'About Us'),
array('style' => 'background-color: white;')
);
echo $this->tabContainer()->captureEnd('main-container');
?>
Here we first call captureStart() method of tabContainer() dojo view helper, giving it an id, and array containing tab container special attributes. Next we define content panes. Each content pane holds the data. The contents panes in the tab container will become tab panes.
each content pane is defined as
echo $this->contentPane(
'home',
'This is home page',
array('region' => 'top','title'=>'Home'),
array('style' => 'background-color: white;')
);
Here "home" is the id of the content page, Next "string" is the contents that will appear in the tab pane. Next we have defined the array of the special attributes of the contents. Here title is the most important attribute. This title will appear on the tab. The last array contain css related attributes.
That's it. we have now written all necessary code for creating nice and beautiful Tab container.
Cheers.
Labels:
Dojo,
Zend Framewrork
Sunday, July 12, 2009
Zend Framework SQL Joins Examples
You may have custom of using advanced queries. It often requires writing complex queries if you are working on enterprise, large scale web application(s).
The use of joins can never be ignored.
Zend Framework developers have done tremendous job by providing simple method for implementing joins.
Lets look some examples of different type of joins.
Before discussing joins lets consider we have two tables, “authors” and “books”.
These are associated with author_id.
1. Inner Join
The simplest query will be
2. Left Join
3. Right Join
4. Full Join
5. Cross Join
Once you write these queries, you can fetch a single row or multiple rows as
The first statement fetch only one row, while the second statement fetch the entire dataset.
The use of joins can never be ignored.
Zend Framework developers have done tremendous job by providing simple method for implementing joins.
Lets look some examples of different type of joins.
Before discussing joins lets consider we have two tables, “authors” and “books”.
These are associated with author_id.
1. Inner Join
The simplest query will be
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinInner('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->order('column name ASC/DESC');
2. Left Join
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinLeft('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->group('group by column name here')
->order('column name ASC/DESC');
3. Right Join
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinRight('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->group('group by column name here')
->order('column name ASC/DESC');
4. Full Join
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinFull('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->group('group by column name here')
->order('column name ASC/DESC');
5. Cross Join
$select = $this->_db->select()
->from('books',array('col1','col2'…..))
->joinFull('authors','books.id=authors.bks_id',array('col1','col3'…))
->where('where condition here')
->group('group by column name here')
->order('column name ASC/DESC');
Once you write these queries, you can fetch a single row or multiple rows as
$result = $this->getAdapter()->fetchRow($select);
$result = $this->getAdapter()->fetchAll($select);
The first statement fetch only one row, while the second statement fetch the entire dataset.
Labels:
Zend Framewrork
Creating Json response in php, a nice example
While working with AJAX, you will need to get data after sending request to the server. You can use three ways to get the data form the server.
1. In xml Format
2. HTML Format
3. Json Format
Though xml has several advantages, however processing data at the client will put extra burden.
HTML, can easily be handle, is however more resource or you can say bandwidth extensive.
So JSON fall in the middle of both.
PHP provide a very easy way to create JSON response. Once you get data at client side you will need much later code to process response than xml document.
Let’s first look at the server side.
For example we have the following array.
To create JSON response, simply write
This will give the following result
Now at the client side to send AJAX request, you will need to create the following code.
Keep in mind that we are using prototype for making AJAX request.
That's it.
1. In xml Format
2. HTML Format
3. Json Format
Though xml has several advantages, however processing data at the client will put extra burden.
HTML, can easily be handle, is however more resource or you can say bandwidth extensive.
So JSON fall in the middle of both.
PHP provide a very easy way to create JSON response. Once you get data at client side you will need much later code to process response than xml document.
Let’s first look at the server side.
For example we have the following array.
$data = array(
'items'=>array(
'firstname'=>'faheem',
'lastname'=>'abbas',
'address'=>'pakistan'
)
);
To create JSON response, simply write
echo json_encode($data);
This will give the following result
{"items":{"firstname":"faheem","lastname":"abbas","address":"pakistan"}}
Now at the client side to send AJAX request, you will need to create the following code.
Keep in mind that we are using prototype for making AJAX request.
<script>
function getData()
{
new Ajax.Request(
“http://localhost/getdata.php", /* this is url of the php file that create JSON response.*/
{
method:'post',
onSuccess: processData
}
);
}
function processData(rsp)
{
var response = eval('(' + rsp.responseText + ')');
var firstname = response.items(0).firstname;
var lastname = response.items(0).lastname;
var address = response.items(0).address;
}
</script>
That's it.
Creating dojo border container in Zend Framework
Try Online : Border Container
In my previous artilce I discuss how to create accordion container and panes. If you wish to create accordion container and panes, read my article "Creating dojo accordion Container in Zend".
If you don't know how to configure dojo and Zend Framework, read here.
In this article, however I am going to discuss how to create border container. Border continer divide our page in different section so that we can display different contents in those sectitons.
To create the border container we first need to create our controller as
Now in your /application/views/scripts/container/border.phtml, place the following code.
Here we have called captureStart() method to start our border container, and then we have placed different content panes.
Each content pane has an "id", "contents" it holds, array containing content panes attributes, and an array containing css attributes.
In my previous artilce I discuss how to create accordion container and panes. If you wish to create accordion container and panes, read my article "Creating dojo accordion Container in Zend".
If you don't know how to configure dojo and Zend Framework, read here.
In this article, however I am going to discuss how to create border container. Border continer divide our page in different section so that we can display different contents in those sectitons.
To create the border container we first need to create our controller as
<?php
class ContainerController extends Zend_Controller_Action
{
public function borderAction()
{
}
}
Now in your /application/views/scripts/container/border.phtml, place the following code.
<?php
$this->borderContainer()->captureStart('main-container',
array('design' => 'headline'),
array(
'style'=>'height:400px;width:800px',
'align' => 'center'
));
echo $this->contentPane(
'menuPane',
'This is the menu pane',
array('region' => 'top'),
array('style' => 'background-color: darkblue;color:white')
);
echo $this->contentPane(
'navPane',
'This is the navigation pane',
array('region' => 'left'),
array('style' => 'width: 200px; background-color: lightblue;')
);
echo $this->contentPane(
'mainPane',
'This is the main content pane area',
array('region' => 'center'),
array('style' => 'background-color: white;')
);
echo $this->contentPane(
'statusPane',
'Status area',
array('region' => 'bottom'),
array('style' => 'background-color: lightgray;')
);
echo $this->borderContainer()->captureEnd('main-container');
?>
Here we have called captureStart() method to start our border container, and then we have placed different content panes.
Each content pane has an "id", "contents" it holds, array containing content panes attributes, and an array containing css attributes.
Labels:
Dojo,
Zend Framewrork
Creating dojo accordion Container/panes in Zend
Try Online : Accordion Container
Dojo provide very easy and nice way of creating different containers such as accordion, tab, border, and stack etc.
These containers hold different type of panes. These different panes in turn use to hold contents. contents can be simple text or it can be complete html.
Zend Framework collaboration with Dojo has made things quite easy. Zend Framework provide view helpers to achieve different type of dojo functionality.
In this article I am going to discuss how to create Accordion Container. accordion Container hold accordion panes. Each accordion pane hold different contents and open in a stylish way when user click on the title of the pane.
In order to enable dojo helpers in you Zend Framework application, you will need to make some initial configuration. read my tutorial "Zend Framework and Dojo: configuration" before reading this tutorial. After successfull configuration create a controller called "ContinerController.php" in your controllers directory and place the following code in it.
We have only defined an action in our controller, putting no code at all. you however can put whatever code you wish.
Now in /application/views/scripts/container/accordion.phtml place the following code.
The code is pretty simple. we first call captureStart() method on accordionContainer(). this will start accordion container for us.
Once the accordion continer is started, we need to put accordion panes in it and at the end we will need to call captureEnd() method to end our accordion container.
The container holding the following accordion pane.
The above code call accordionPane() helper method. This dojo helper method take an "id", "contents" to be displayed in the accordion pane, an array containing the special attributes of the accordion pane, and array of css attributes.
Dojo provide very easy and nice way of creating different containers such as accordion, tab, border, and stack etc.
These containers hold different type of panes. These different panes in turn use to hold contents. contents can be simple text or it can be complete html.
Zend Framework collaboration with Dojo has made things quite easy. Zend Framework provide view helpers to achieve different type of dojo functionality.
In this article I am going to discuss how to create Accordion Container. accordion Container hold accordion panes. Each accordion pane hold different contents and open in a stylish way when user click on the title of the pane.
In order to enable dojo helpers in you Zend Framework application, you will need to make some initial configuration. read my tutorial "Zend Framework and Dojo: configuration" before reading this tutorial. After successfull configuration create a controller called "ContinerController.php" in your controllers directory and place the following code in it.
<?php
class ContainerController extends Zend_Controller_Action
{
public function accordionAction()
{
}
}
We have only defined an action in our controller, putting no code at all. you however can put whatever code you wish.
Now in /application/views/scripts/container/accordion.phtml place the following code.
<?php
$this->accordionContainer()->captureStart('main-container',
array('design' => 'headline'),
array(
'style'=>'height:400px;width:400px'
));
echo $this->accordionPane(
'home',
'This is home page',
array('region' => 'top','title'=>'Home'),
array('style' => 'background-color: white;')
);
echo $this->accordionPane(
'gallery',
'Contents of gallery here',
array('region' => 'left', 'title'=>'Gallery'),
array('style' => 'background-color: white;')
);
echo $this->accordionPane(
'Blog',
'Blog post here',
array('region' => 'center','title'=>'Blog'),
array('style' => 'background-color: white;')
);
echo $this->accordionContainer()->captureEnd('main-container');
?>
The code is pretty simple. we first call captureStart() method on accordionContainer(). this will start accordion container for us.
Once the accordion continer is started, we need to put accordion panes in it and at the end we will need to call captureEnd() method to end our accordion container.
The container holding the following accordion pane.
echo $this->accordionPane(
'home',
'This is home page',
array('region' => 'top','title'=>'Home'),
array('style' => 'background-color: white;')
);
The above code call accordionPane() helper method. This dojo helper method take an "id", "contents" to be displayed in the accordion pane, an array containing the special attributes of the accordion pane, and array of css attributes.
Labels:
Dojo,
Zend Framewrork
Implementing Ajax with Zend Framework and Json
Well, while working with ajax, it better to have an xml as response. Xml, however need more coding and parsing on client side than json.
Zend framework provides very easy way to generate json response.
In this article I’m going to discuss how to create Ajax request using prototype and how to use Zend_Json to generate response.
For generating Ajax request, you will need to write
If response is the form of this
Then to acess the values of the first row, write
and the values of the second row can be accessed as
To create Json response, you will need to write the following in your controller action
Keep in mind that “users” is our model, having the following code.
That's it. cheers.
Zend framework provides very easy way to generate json response.
In this article I’m going to discuss how to create Ajax request using prototype and how to use Zend_Json to generate response.
For generating Ajax request, you will need to write
<script>
new Ajax.Request(
"url",
{
method: 'post',
parameters: {'val1': 1, 'val2': 2},
onComplete: displayResults
}
);
function displayResults(rsp)
{
var results = eval('('+rsp.responseText+')');
}
</script>
If response is the form of this
[
{"firstName":"Faheem","lastName":"Abbas","username":"fahim","email":"faheem.abbas@nxb.com.pk"},
{"firstName":"Shazil","lastName":"Hassan","username":"shazil","email":"shazil.hassan@yahoo.com"}
]
Then to acess the values of the first row, write
var firstName = results[0].firstName;
var lastName = results[0].lastName;
and the values of the second row can be accessed as
var firstName = results[1]. firstName;
var lastName = results[1].lastName;
To create Json response, you will need to write the following in your controller action
$users = new Users();
$username = $this->_getParam('username');
$select = $users->select();
$data = $users->fetchAll($select);
$results = $data->toArray();
echo Zend_Json::encode($results);
Keep in mind that “users” is our model, having the following code.
<?php
class Users extends Zend_Db_Table
{
protected $_name = "users";
}
That's it. cheers.
Labels:
Json,
Zend Framewrork
Thursday, July 9, 2009
Joomla component in Zend Framework example
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.
Here you can see that my component name is com_advertisers.
In this directory I’ve
* admin.advertiser.php file
* application directory
* Joomla directory
The file admin.advertiser.php will serve as the bootstrap file.
Application directory contain specific directory for controllers, models and views.
The most important role is played by our Joomla directory in developing joomla component in Zend Framework.
This directory contain Controllers/Plugins/Router.php file.
This file contains code for calling specific action based on particular task. Before going to discuss code in the Router.php file, I’m going to show the code need in our admin.advertisers.php file.
In the first few lines I have included path to our com_advertisers directory, application directory and models directory.
Next I include Zend Front Controller files and Router.php file. I’ll discuss code in the Router.php file later as it contain the most important code.
Next I initialize front controller, register Router Plugin class which is defined in our Router.php file, set controller directory and call dispatch.
That’s it. We have now defined our bootstrap file.
One important thing is setting path to our library files that contain Zend component.
You can include path using set_include_path or set it in your php.ini file.
If you don’t include this path, your application will not work as you expected.
Now go to controllers directory and create IndexController.php and write the following code in it.
Noting special here. I’ve created only three actions.
Go to your application/views/scripts directory and create directory called index and create three files index.phtml, edit.phtml and save.phtml.
The code above is what you will need to work with Zend Framework MVC. In order to integrate this code with joomla will need one additional files. In my case the file is Router.php
I have create this file in com_advertiser/Joomla/Controllers/Plugins/ directory.
The code contain in this file is
First I’ve include plugin class and then extended my Router class from Zend_Controller_Plugin_Abstract.
This Zend_Controller_Plugin_Abstract class contain a method preDispatch that is called before any controller is called in the routing process.
In the preDispatch method, I get the param “task” and write a switch statement to check this param. If it is edit, I give control to my editAction of the default IndexController. And similarly if it is save, I route request to my saveAction and by default, if no parameter is specified, the request will be dispatched to indexAction of my IndexController.
That’s it.
Now if you write
http://localhost/joomla/administrator/index.php?option=com_advertisers&task=save
It will show what ever you have written in your save.phtml file.
And similarly if you write
http://localhost/joomla/administrator/index.php?option=com_advertisers&task=edit
it will route you to editAction and will display whatever you have define there.
Any question and suggestion are welcomed.
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.
Here you can see that my component name is com_advertisers.
In this directory I’ve
* admin.advertiser.php file
* application directory
* Joomla directory
The file admin.advertiser.php will serve as the bootstrap file.
Application directory contain specific directory for controllers, models and views.
The most important role is played by our Joomla directory in developing joomla component in Zend Framework.
This directory contain Controllers/Plugins/Router.php file.
This file contains code for calling specific action based on particular task. Before going to discuss code in the Router.php file, I’m going to show the code need in our admin.advertisers.php file.
<?php
define('ROOT_DIR', dirname(__FILE__));
set_include_path('.'
. PATH_SEPARATOR . ROOT_DIR . '/'
. PATH_SEPARATOR . ROOT_DIR . '/application'
. PATH_SEPARATOR . ROOT_DIR . '/application/models'
. PATH_SEPARATOR . get_include_path()
);
require_once "Zend/Controller/Front.php";
require_once "Joomla/Controllers/Plugins/Router.php";
$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);
$frontController->registerPlugin(new Joomla_Controllers_Plugins_Router());
$frontController->setControllerDirectory(ROOT_DIR.'/application/controllers');
$frontController->dispatch();
In the first few lines I have included path to our com_advertisers directory, application directory and models directory.
Next I include Zend Front Controller files and Router.php file. I’ll discuss code in the Router.php file later as it contain the most important code.
Next I initialize front controller, register Router Plugin class which is defined in our Router.php file, set controller directory and call dispatch.
That’s it. We have now defined our bootstrap file.
One important thing is setting path to our library files that contain Zend component.
You can include path using set_include_path or set it in your php.ini file.
If you don’t include this path, your application will not work as you expected.
Now go to controllers directory and create IndexController.php and write the following code in it.
<?php
require_once('Zend/Controller/Action.php');
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
}
public function editAction()
{
}
public function saveAction()
{
}
}
Noting special here. I’ve created only three actions.
Go to your application/views/scripts directory and create directory called index and create three files index.phtml, edit.phtml and save.phtml.
The code above is what you will need to work with Zend Framework MVC. In order to integrate this code with joomla will need one additional files. In my case the file is Router.php
I have create this file in com_advertiser/Joomla/Controllers/Plugins/ directory.
The code contain in this file is
<?php
require_once('Zend/Controller/Plugin/Abstract.php');
class Joomla_Controllers_Plugins_Router extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$task = $request->getParam('task')
switch($task) {
case 'edit':
$request->setActionName('edit');
break;
case 'save':
$request->setActionName('save');
break;
default:
$request->setActionName('index');
break;
}
}
}
First I’ve include plugin class and then extended my Router class from Zend_Controller_Plugin_Abstract.
This Zend_Controller_Plugin_Abstract class contain a method preDispatch that is called before any controller is called in the routing process.
In the preDispatch method, I get the param “task” and write a switch statement to check this param. If it is edit, I give control to my editAction of the default IndexController. And similarly if it is save, I route request to my saveAction and by default, if no parameter is specified, the request will be dispatched to indexAction of my IndexController.
That’s it.
Now if you write
http://localhost/joomla/administrator/index.php?option=com_advertisers&task=save
It will show what ever you have written in your save.phtml file.
And similarly if you write
http://localhost/joomla/administrator/index.php?option=com_advertisers&task=edit
it will route you to editAction and will display whatever you have define there.
Any question and suggestion are welcomed.
Labels:
Joomla,
Zend Framewrork
Monday, July 6, 2009
Zend Framework: Zend_Config examples
Zend_Config is used to simply access to, and use of configuration data in Zend Framework application.
Zend_Config currently provide adapters for getting configuration data from xml and ini files. You can also store configuration data in array and pass that array to the Zend_Config constructore, this however is not a recommended way. Configuration data is mostly stored in either xml files or ini files.
In this tutorial I am going to put shad on the usage of Zend_Config and will give you example of how to keep data in array, ini and xml file and then use that using Zend_Config.
So let’s have a look.
To hold configuration data in form of array, you will need to write
You can clearly see that we have defined an associative array containing database information.
Now as you have defined an array having configuration information, next step is to create an object of Zend_Config class passing the above array. The code will look like the following
Now, if you want to make database configuration, simply write
To store the above information in ini file, create config.ini somewhere in your application directory structure, and write the following code in it.
After defining ini file, simply write
in your application.
The database configuration is same as we done earlier.
Similarly if you like to use, xml file for you application configuration, create config.xml somewhere in your application directory structure and write
Now either in your bootstrap file or where you want to initialize configuration, write
$config = new Zend_Config_Xml(‘path/to/xml/config.xml’,’development’);
For database configuration, simply write
That's it. cheers.
Zend_Config currently provide adapters for getting configuration data from xml and ini files. You can also store configuration data in array and pass that array to the Zend_Config constructore, this however is not a recommended way. Configuration data is mostly stored in either xml files or ini files.
In this tutorial I am going to put shad on the usage of Zend_Config and will give you example of how to keep data in array, ini and xml file and then use that using Zend_Config.
So let’s have a look.
To hold configuration data in form of array, you will need to write
$configArray = array(
'database' => array(
'adapter' => 'pdo_mysql',
'params' => array(
'host' => localhost',
'username' => 'user_name',
'password' => 'user_password',
'dbname' => 'database_name'
)
)
);
You can clearly see that we have defined an associative array containing database information.
Now as you have defined an array having configuration information, next step is to create an object of Zend_Config class passing the above array. The code will look like the following
$config = new Zend_Config($configArray);
Now, if you want to make database configuration, simply write
$db= Zend_Db::factory($config->database);
To store the above information in ini file, create config.ini somewhere in your application directory structure, and write the following code in it.
[development]
database.adapter = pdo_mysql
database.params.host = localhost
database.params.username = user_name
database.params.password = user_password
database.params.dbname = database_name
After defining ini file, simply write
$config = new Zend_Config_Ini(‘path/to/ini/config.ini’,’ development’);
in your application.
The database configuration is same as we done earlier.
$db = Zend_Config::factory($config->database);
Similarly if you like to use, xml file for you application configuration, create config.xml somewhere in your application directory structure and write
<?xml version="1.0"?>
< development >
<database>
<adapter>pdo_mysql</adapter>
<params>
<host>db.example.com</host>
<username>dbuser</username>
<password>secret</password>
<dbname>dbname</dbname>
</params>
</databse>
</ development >
Now either in your bootstrap file or where you want to initialize configuration, write
$config = new Zend_Config_Xml(‘path/to/xml/config.xml’,’development’);
For database configuration, simply write
$db = Zend_Db::factory($config->database);
That's it. cheers.
Labels:
Zend Framewrork
Sunday, July 5, 2009
Creating radio button in Zend Framework
Zend Framework Form: working with radio buttons
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
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
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
The only difference in the above two example is that I have placed
With
Both statements give the same result.
For setting different radio button options, you can also use the following method.
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’);
Labels:
Zend Framewrork
Ajax with Json and prototype in Zend Framework
I used JSon for the first time in my application today. Zend provide a very easy way to create JSon response.
In this article I would use Prototype to make ajax call. Hopefully you will now a bit about Prototype. Anyway if not, it would not be a hard job to understand it after reading my article.
So let’s get started.
Consider you have the following form.
The scenario is
When user select name from the dropdown, the entire form is filled with the data from the database for that particular user.
For this purpose you would need to have a controller/Action(s), a model and template file.
In your form attach the following attrib to your name element as
In the lines above we first create a dropdown give it two values. And then attach javascript function “AutoFill” function using setAttrib method.
In your controller initialize your form and assign it to the view template as
Now in your view template file write the following.
Write the following javascript code.
To get response you will need to create an action and write the following code
In the above code getdataAction is called using ajax call. In the first line we have disabled the layout, because we don’t need layout in case of ajax response. Next we create object of our model class(discussed later). Next we tell zend to disable view rendering.
In the next few lines we check for ajax request, get id, call our getData model method.
We then create dojo data object. This object provide a very useful method to convert data retrieved into json format. The method used is toJson().
In our model we have code like the following.
That's it. Cheers.
In this article I would use Prototype to make ajax call. Hopefully you will now a bit about Prototype. Anyway if not, it would not be a hard job to understand it after reading my article.
So let’s get started.
Consider you have the following form.
The scenario is
When user select name from the dropdown, the entire form is filled with the data from the database for that particular user.
For this purpose you would need to have a controller/Action(s), a model and template file.
In your form attach the following attrib to your name element as
<?php
$name = $this->createElement('select','name');
$name->addMultioptions(array(
'select'=>'[select]',
'1' => 'Faheem',
'2' => 'Abbas'
));
$name->setAttrib('onchange','AutoFill()');
In the lines above we first create a dropdown give it two values. And then attach javascript function “AutoFill” function using setAttrib method.
In your controller initialize your form and assign it to the view template as
$form = new MyCustomForm();
$this->view->form = $form;
Now in your view template file write the following.
Write the following javascript code.
<script>
function AutoFill()
{
new Ajax.Request(
"<?=$this->url(array('controller'=>'user','action'=>'getdata'))?>",
{
method:'get',
parameters: {id: value},
onSuccess: FillForm
}
}
function FillForm(rsp)
{
var card = eval('(' + rsp.responseText + ')');
$('address1').value = card.items[0].address1;
$('address2').value = card.items[0].address2;
$('postalcode').value = card.items[0].postalcode;
}
</script>
To get response you will need to create an action and write the following code
<?php
class User extends Zend_Controller_Action
{
public function indexAction()
{
$form = new MyCustomForm();
$this->view->form = $form;
}
public function getdataAction()
{
$this->_helper->layout()->disableLayout();
$users = new Users();
$this->_helper->viewRenderer->setNoRender();
if ($this->getRequest()->isXmlHttpRequest()) {
$id = $this->_getParam('id');
$userData = $ users ->getData($id);
$dojoData= new Zend_Dojo_Data('id',$userData,'id');
echo $dojoData->toJson();
}
}
}
In the above code getdataAction is called using ajax call. In the first line we have disabled the layout, because we don’t need layout in case of ajax response. Next we create object of our model class(discussed later). Next we tell zend to disable view rendering.
In the next few lines we check for ajax request, get id, call our getData model method.
We then create dojo data object. This object provide a very useful method to convert data retrieved into json format. The method used is toJson().
In our model we have code like the following.
<?php
class Users extends Zend_Db_Table
{
protected $_name = 'users';
public function getData($id)
{
$select = $this->_db->select()
->from($this->_name,
array('address1','address2'….))
->where('id = ?', $id);
$result = $this->getAdapter()->fetchAll($select);
return $result;
}
}
That's it. Cheers.
Labels:
Zend Framewrork
select box in Zend framework: code and example
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 it using the following code.
Or can also be created using the following code.
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.
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.
In the above code the only thing changes is
1. I have instantiated model using
$countries = new Countries();
2. Call getCountiresList() method. And assign the list to the instead of assign hard coded values.
You can create it 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 assign the list to the instead of assign hard coded values.
Labels:
Zend Framewrork
Sending Email with attachment in Zend Framework
You may have used Php for sending emails in your application. I haven’t experienced it in plain php, so I don’t know whether its easy or difficult. I, however, know that Zend Framework provide very easy way for sending emails. You can even attach files with your email with single method call.
In this article I am going to discuss how to send email with attachments. Please do tell me whether it helped you or not.
In your controller, write something like this.
This, although, will send email, however it’s not a good approach to create email in your controller as your mail body may contain thousands of words.
The best approach is to create a template, that contain the contents that will act as body of the email. To achieve this, create a file called emailExample.phtml in your /application/views/scripts/templates/ directory. And write the contents you want to put, those contents will serve as body of the email you are going to send.
I am having the following code in my emailExample.phtml
Now in your controller, write
Here we are first creating an instance of Zend_View, call addScriptPath() to add script path- directory path where our template file reside and which serve as body of our email.
We then get the template by calling render() method on that view object, giving it the name of the template. The rest of the process is same, creating Zend_Mail object, setting body and so on.
Another question come to mind is how
to send an attachment?
This is pretty simple too.
First you will need to get the contents of the file, by calling a method file_get_contents(), like this.
And then call a simple method called createAttachment (), as
And set the name of the attachment as
That’s it. Cheers.
In this article I am going to discuss how to send email with attachments. Please do tell me whether it helped you or not.
In your controller, write something like this.
$emial_body = “<table><tr><td>Body of the email</td></tr></table”;
$mail = new Zend_Mail();
$mail->setType(Zend_Mime::MULTIPART_RELATED);
$mail->setBodyHtml($email_body);
$mail->setFrom('support@example.com', 'Example');
$mail->addTo('user@abc.com', 'Username');
$mail->setSubject('Sending email using Zend Framework');
$mail->send();
This, although, will send email, however it’s not a good approach to create email in your controller as your mail body may contain thousands of words.
The best approach is to create a template, that contain the contents that will act as body of the email. To achieve this, create a file called emailExample.phtml in your /application/views/scripts/templates/ directory. And write the contents you want to put, those contents will serve as body of the email you are going to send.
I am having the following code in my emailExample.phtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<table>
<tr>
<td>
all my contents here.
</td>
</tr>
</table>
</body>
</html>
Now in your controller, write
$myView = new Zend_View();
$myView->addScriptPath(ROOT_DIR . '/application/views/scripts/templates/');
$html_body = $ myView ->render(emailExample.phtml');
$mail = new Zend_Mail();
$mail->setType(Zend_Mime::MULTIPART_RELATED);
$mail->setBodyHtml($html_body);
$mail->setFrom('support@example.com', 'Example');
$mail->addTo('user@abc.com', 'Username');
$mail->setSubject('Sending email using Zend Framework');
$mail->send();
Here we are first creating an instance of Zend_View, call addScriptPath() to add script path- directory path where our template file reside and which serve as body of our email.
We then get the template by calling render() method on that view object, giving it the name of the template. The rest of the process is same, creating Zend_Mail object, setting body and so on.
Another question come to mind is how
to send an attachment?
This is pretty simple too.
First you will need to get the contents of the file, by calling a method file_get_contents(), like this.
$fileContents = file_get_contents(‘path/to/file’);
And then call a simple method called createAttachment (), as
$file = $mail->createAttachment($fileContents);
And set the name of the attachment as
$file->filename = "yourfile.doc";
That’s it. Cheers.
Labels:
Zend Framewrork
Saturday, July 4, 2009
Zend Framework building complete application
Well, I have written lots of separate article on Zend Framework. Hopefully most of folk out there searching for valuable help may have gotten some from my articles.
This time my objective is to share everything with you, from basic configuration till to building complete Zend Framework application.
This article will cover
1. How to make initial configuration.
2. How to use Zend_Auth for authentication
3. Using Zend_Session for handling sessions
4. What are models and how to create them
5. Using Zend_Db to handle backend database for storing valuable information.
And much more.
So let’s get started.
1. Creating directory structure and making initial configuration
Zend Framework is based on MVC design patterns. MVC stands for Model, View, Controller. A simple definition of MVC design pattern is to separate business logic from presentation logic.
In order to work with Zend Framework MVC design pattern, you’ll need to make necessary directory structure. There are various ways of making directory structure, I, however will use the most easier to create and understand structure.
The structure I created is.
On the top level we have html_root directory, containing application directory, library, js, css and images. It also contain index.phtml called our bootstrap file. This file contain all our configuration code. Further more application directory contain controller, models forms and views directories. Library directory contains Zend components. Js contain all our js files, css contains css files and images contains all images used in our application.
On the hard drive our directory structure looks like
Keep in mind that controllers directory contain our entire controllers, form directory contain all forms used in our application. Model contains php files contain our business logic. Views/scripts contain template files against each controllers.
Now as we have made necessary directory structure, next step is to make necessary configuration in our bootstrap file.
2. Making necessary configuration in our bootstrap- index.php file.
The most important file, that will get all request and route them to specific controllers. It contain code for setting include path, initializing front controller, set controllers path and call dispatch method.
The code is very simple to explain. The first line define path to our root directory.
The next lines set include path to /library, /application/models and /application/forms.
Next lines are very important
Help in loading all php files we need in our application. If we don’t use this code, we will need to include require_once statement to load php files needed.
In next lines we get instance of the front controller, set controllers directory and call dispatch method.
Front controller is responsible for handling the user request. It takes the request and on specific criteria take appropriate action.
That’s it. Its our configuration file. Simple and easy.
3. Creating controllers and views
In html_root/application/controllers, create IndexController.php and put the following code in it.
Every controller must be extended from Zend_Controller_Action and can contain as many methods as possible. Method defined in controllers is called action. Once you create action in the controller, next step is to create view template. For this purpose, in html_root/application/views/scripts/, create index/index.phtml and put the following code in it.
That’s it.
Now if you browse
http://localhost/html_root/
You will see
Hello World
If you don’t see “Hello world” printed, read the above guide lines again.
As we have now successfully created directory structure and bootstrap file, its time to make other necessary configuration for database.
4. Configuration for working with database
How a web application can be completed without usage of database. Different web application uses different database. Some uses Mysql, other SQLite, SQL server and Oracle. One of the nice thing about Zend Framework is that it support multiple database servers.
Here we are going to making configuration for Mysql server.
For database configuration, first create config.ini in html_root/application/ and write the following code in it.
Now in your bootstrap file make the following changes.
First we load our config.ini file that contain our database configuration. Next we call static factory method of Zend_Db giving it $config->db for database configuration and at the end we set default adapter for our database tables.
That’s it. We have now done all necessary configurations.
Next step is to store and retrieve data from database
5. Working with database data
Now we are going to make an application that will save, display and edit data in the database.
First execute the following query.
This query create a table called users in the database.
Next step is to create model against this table. In your html_root/application/models/ create Users.php and write the following code in it.
The only thing we have done is extend our Zend_Db_Table and define name of the model. This name must be same as the database table name.
Now in your html_root/application/controllers/IndexController.php, write
After making changes in IndexController.php, next step is to make changes in html_root/application/views/scripts/index/index.phtml. write the following code in it.
This will show the list of users.
Next we are going to create a form for adding data to users table.
In your html_root/application/forms/ create CustomForm.php and write the following code in it.
We have successfully created our form, next we are going to write necessary code in our IndexController.php
Write the following code in it
The code in addAction create form, get posted data, check whether password and confirm password match and then insert data in the users table.
Now create add.phtml in html_root/application/views/scripts/index/ and write the following code in it.
Next we are going to create action for editing the users table data. Write the following code in the your IndexController.php
The above code fetch the data and populate the form, and then get the posted data and update the users table based on the id.
Create edit.phtml in html_root/application/views/scripts/index/ and write the following code in it.
6. Create authentication application
As now we have created database application successfully, we are going to create authentication application.
(i). Creating login form
in your html_root/application/forms/ create LoginForm.php and write the following code in it.
In the above form we add two elements, a text box for entering username and password field for entering user password. We also add submit input box.
(ii).Next we create AuthController.php in html_root/application/controllers/ and write the following code
In login action we initialize our login form, check for submitted data. We then instantiate our user model as well as Zend_Auth. Setting table name, identity column and credential column. We then pass values submitted through form to identity column and credential column. After setting these things we call authenticate() method.
This authenticate column perform authentication for us.
We then call isValid() method that return true or false based on the authentication.
If isValid() return true, we get the user specific information by calling getResultRowObject() method.
We then create session and assign username to it.
The last thing we will need to create is view template against login action. In html_root/application/views/scripts create auth/login.phtml and write the following code in it.
That’s it. Our login authentication. For registration, you can use add form I have previously created.
I think its enough for now. I will discuss other things later on hopefully.
This time my objective is to share everything with you, from basic configuration till to building complete Zend Framework application.
This article will cover
1. How to make initial configuration.
2. How to use Zend_Auth for authentication
3. Using Zend_Session for handling sessions
4. What are models and how to create them
5. Using Zend_Db to handle backend database for storing valuable information.
And much more.
So let’s get started.
1. Creating directory structure and making initial configuration
Zend Framework is based on MVC design patterns. MVC stands for Model, View, Controller. A simple definition of MVC design pattern is to separate business logic from presentation logic.
In order to work with Zend Framework MVC design pattern, you’ll need to make necessary directory structure. There are various ways of making directory structure, I, however will use the most easier to create and understand structure.
The structure I created is.
html_root
/application
/controllers
IndexController.php
/models
Users.php
/forms
LoginForm.php
/views
/scripts
/dojo
index.phtml
/libaray
/Zend
/js
/css
/images
/index.phtm
On the top level we have html_root directory, containing application directory, library, js, css and images. It also contain index.phtml called our bootstrap file. This file contain all our configuration code. Further more application directory contain controller, models forms and views directories. Library directory contains Zend components. Js contain all our js files, css contains css files and images contains all images used in our application.
On the hard drive our directory structure looks like
Keep in mind that controllers directory contain our entire controllers, form directory contain all forms used in our application. Model contains php files contain our business logic. Views/scripts contain template files against each controllers.
Now as we have made necessary directory structure, next step is to make necessary configuration in our bootstrap file.
2. Making necessary configuration in our bootstrap- index.php file.
The most important file, that will get all request and route them to specific controllers. It contain code for setting include path, initializing front controller, set controllers path and call dispatch method.
<?php
define('ROOT_DIR', dirname(__FILE__));
set_include_path('.'
. PATH_SEPARATOR . ROOT_DIR . '/library'
. PATH_SEPARATOR . ROOT_DIR . '/application/models'
. PATH_SEPARATOR . ROOT_DIR . '/application/forms'
. PATH_SEPARATOR . get_include_path()
);
require_once "Zend/Loader/Autoloader.php";
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);
$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);
$frontController->setControllerDirectory(ROOT_DIR.'/application/controllers');
$frontController->dispatch();
?>
The code is very simple to explain. The first line define path to our root directory.
The next lines set include path to /library, /application/models and /application/forms.
Next lines are very important
require_once "Zend/Loader.php";
Zend_Loader::registerAutoload();
Help in loading all php files we need in our application. If we don’t use this code, we will need to include require_once statement to load php files needed.
In next lines we get instance of the front controller, set controllers directory and call dispatch method.
Front controller is responsible for handling the user request. It takes the request and on specific criteria take appropriate action.
That’s it. Its our configuration file. Simple and easy.
3. Creating controllers and views
In html_root/application/controllers, create IndexController.php and put the following code in it.
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
}
}
Every controller must be extended from Zend_Controller_Action and can contain as many methods as possible. Method defined in controllers is called action. Once you create action in the controller, next step is to create view template. For this purpose, in html_root/application/views/scripts/, create index/index.phtml and put the following code in it.
Hello world
That’s it.
Now if you browse
http://localhost/html_root/
You will see
Hello World
If you don’t see “Hello world” printed, read the above guide lines again.
As we have now successfully created directory structure and bootstrap file, its time to make other necessary configuration for database.
4. Configuration for working with database
How a web application can be completed without usage of database. Different web application uses different database. Some uses Mysql, other SQLite, SQL server and Oracle. One of the nice thing about Zend Framework is that it support multiple database servers.
Here we are going to making configuration for Mysql server.
For database configuration, first create config.ini in html_root/application/ and write the following code in it.
[general]
db.adapter = PDO_MYSQL
db.params.host = localhost
db.params.username = root
db.params.password =
db.params.dbname = zend
Now in your bootstrap file make the following changes.
<?php
define('ROOT_DIR', dirname(__FILE__));
set_include_path('.'
. PATH_SEPARATOR . ROOT_DIR . '/library'
. PATH_SEPARATOR . ROOT_DIR . '/application/models'
. PATH_SEPARATOR . ROOT_DIR . '/application/forms'
. PATH_SEPARATOR . get_include_path()
);
require_once "Zend/Loader.php";
Zend_Loader::registerAutoload();
$config = new Zend_Config_Ini(ROOT_DIR.'/application/config.ini', 'general');
$db = Zend_Db::factory($config->db);
Zend_Db_Table::setDefaultAdapter($db);
$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);
$frontController->setControllerDirectory(ROOT_DIR.'/application/controllers');
$frontController->dispatch();
?>
First we load our config.ini file that contain our database configuration. Next we call static factory method of Zend_Db giving it $config->db for database configuration and at the end we set default adapter for our database tables.
That’s it. We have now done all necessary configurations.
Next step is to store and retrieve data from database
5. Working with database data
Now we are going to make an application that will save, display and edit data in the database.
First execute the following query.
CREATE TABLE `users` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`firstName` VARCHAR( 50 ) NOT NULL ,
`lastName` VARCHAR( 50 ) NOT NULL ,
`username` VARCHAR( 50 ) NOT NULL ,
`email` VARCHAR( 100 ) NOT NULL ,
`password` VARCHAR( 50 ) NOT NULL
)
This query create a table called users in the database.
Next step is to create model against this table. In your html_root/application/models/ create Users.php and write the following code in it.
<?php
class Users extends Zend_Db_Table
{
protected $_name = "users";
}
The only thing we have done is extend our Zend_Db_Table and define name of the model. This name must be same as the database table name.
Now in your html_root/application/controllers/IndexController.php, write
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$users = new Users();
$data = $users->fetchAll($users->select());
$this->view->data = $data;
}
}
After making changes in IndexController.php, next step is to make changes in html_root/application/views/scripts/index/index.phtml. write the following code in it.
<h4>List of users</h4>
<h5><a href="add" style="color:blue">Add new user</a></h5>
<table border="1">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tboody>
<?php foreach ($this->data as $d) {?>
<tr>
<td><?=$d['firstName']?></td>
<td><?=$d['lastName']?></td>
<td><?=$d['username']?></td>
<td><?=$d['email']?></td>
<td><a href="edit/id/<?=$d['id']?>" style="color:blue">Edit</a></td>
</tr>
<?php }?>
</tbody>
</table>
This will show the list of users.
Next we are going to create a form for adding data to users table.
In your html_root/application/forms/ create CustomForm.php and write the following code in it.
<?php
class CustomForm extends Zend_Form
{
public function init()
{
$this->setMethod('post');
//$this->setAction('add');
$id = $this->createElement('hidden','id');
$firstname = $this->createElement('text','firstname');
$firstname->setLabel('First Name:')
->setAttrib('size',50);
$lastname = $this->createElement('text','lastname');
$lastname->setLabel('Last Name:')
->setAttrib('size',50);
$username = $this->createElement('text','username');
$username->setLabel('Username:')
->setAttrib('size',50);
$email = $this->createElement('text','email');
$email->setLabel('Email:')
->setAttrib('size',50);
$password = $this->createElement('password','password');
$password->setLabel('Password:')
->setAttrib('size',50);
$password2 = $this->createElement('password','password2');
$password2->setLabel('Confirm Password::')
->setAttrib('size',50);
$register = $this->createElement('submit','register');
$register->setLabel("Register")
->setIgnore(true);
$this->addElements(array(
$firstname,
$lastname,
$username,
$email,
$password,
$password2,
$id,
$register
));
}
}
We have successfully created our form, next we are going to write necessary code in our IndexController.php
Write the following code in it
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$users = new Users();
$data = $users->fetchAll($users->select());
$this->view->data = $data->toArray();
}
public function addAction()
{
$users = new Users();
$form = new CustomForm();
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
if ($formData['password'] != $formData['password2']) {
$this->view->errorMsg = "Password and Confirm Password must match.";
$this->render('add');
return;
}
unset($formData['password2']);
unset($formData['register']);
$users->insert($formData);
}
}
}
}
The code in addAction create form, get posted data, check whether password and confirm password match and then insert data in the users table.
Now create add.phtml in html_root/application/views/scripts/index/ and write the following code in it.
<h3>Add User</h3>
<?php
if ($this->errorMsg) {
echo $this->errorMsg;
}
?>
<?php
// for displaying form
echo $this->form;
?>
Next we are going to create action for editing the users table data. Write the following code in the your IndexController.php
<?php
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
//$this->_helper->layout->disableLayout();
$users = new Users();
$data = $users->fetchAll($users->select());
$this->view->data = $data->toArray();
}
public function addAction()
{
$users = new Users();
$form = new CustomForm();
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
if ($formData['password'] != $formData['password2']) {
$this->view->errorMsg = "Password and Confirm Password must match.";
$this->render('add');
return;
}
unset($formData['password2']);
unset($formData['register']);
$users->insert($formData);
}
}
}
public function editAction()
{
$users = new Users();
$form = new CustomForm();
$id = $this->_getParam("id",1);
$select = $users->select()
->where("id = ?",$id);
$data = $users->fetchRow($select);
$form->populate($data->toArray());
if ($this->getRequest()->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
if ($formData['password'] != $formData['password2']) {
$this->view->errorMsg = "Password and Confirm Password must match.";
$this->render('add');
return;
}
unset($formData['password2']);
unset($formData['register']);
$users->update($formData,"id = $id");
}
}
$this->view->form = $form;
}
}
The above code fetch the data and populate the form, and then get the posted data and update the users table based on the id.
Create edit.phtml in html_root/application/views/scripts/index/ and write the following code in it.
<h3>Edit User</h3>
<?php
if ($this->errorMsg) {
echo $this->errorMsg;
}
?>
<?php
// for displaying form
echo $this->form;
?>
6. Create authentication application
As now we have created database application successfully, we are going to create authentication application.
(i). Creating login form
in your html_root/application/forms/ create LoginForm.php and write the following code in it.
<?php
class LoginForm extends Zend_Form
{
public function init()
{
$this->setName('login');
$this->setMethod('post');
$userName = $this->createElement('text', 'userName',array('label' => 'username' ));
$userName->addFilters(array('StringTrim'))
->addValidator('StringLength', false,array(5,50))
->setValue('')
->setRequired(true);
$password = $this->createElement('password','password',array('label' => 'password' ));
$password ->setRequired(true)
->addValidator('StringLength', false,array(5,50))
->setValue('');
$submit = $this->createElement('submit','save',array('label' => 'login'));
$submit->setRequired(false)
->setIgnore(true);
$this->addElements(array(
$userName,
$password,
$submit,
));
}
}
In the above form we add two elements, a text box for entering username and password field for entering user password. We also add submit input box.
(ii).Next we create AuthController.php in html_root/application/controllers/ and write the following code
<?php
class AuthController extends Zend_Controller_Action
{
public function loginAction()
{
$form = new LoginForm();
if ($this->getRequest()->isPost()) {
$values = $this->_request->getPost();
if ($form->isValid($values)) {
$users = new Users();
$auth = Zend_Auth::getInstance();
$authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter());
$authAdapter->setTableName('users');
$authAdapter->setIdentityColumn('userName');
$authAdapter->setCredentialColumn('password');
$authAdapter->setIdentity($values['userName']);
$authAdapter->setCredential($values['password']);
try {
$result = $auth->authenticate($authAdapter);
} catch (Zend_Exception $e) {
$this->view->errorMsg = $e->getMessage() . "<br>";
}
if ($result->isValid()) {
$data = $authAdapter->getResultRowObject();
$sess = new Zend_Session_Namespace();
$sess->username = $data->useruame;
echo "Welcome <b>".$data->username.'</b><br>You successfully logged in.';
} else {
echo "invalid username or password try again.";
}
}
}
$this->view->form = $form;
}
}
In login action we initialize our login form, check for submitted data. We then instantiate our user model as well as Zend_Auth. Setting table name, identity column and credential column. We then pass values submitted through form to identity column and credential column. After setting these things we call authenticate() method.
This authenticate column perform authentication for us.
We then call isValid() method that return true or false based on the authentication.
If isValid() return true, we get the user specific information by calling getResultRowObject() method.
We then create session and assign username to it.
The last thing we will need to create is view template against login action. In html_root/application/views/scripts create auth/login.phtml and write the following code in it.
<fieldset style="width:400px">
<legend>Login</legend>
<?php
echo $this->form;
?>
<div><a href="../index/add" style="color:blue">New user Sign up here</a></div>
</fieldset>
That’s it. Our login authentication. For registration, you can use add form I have previously created.
I think its enough for now. I will discuss other things later on hopefully.
Labels:
Zend Framewrork tutorial
Subscribe to:
Posts (Atom)