Generate PHP Docs using Netbeans

August 8th, 2011 by Usha Informatique Team No comments »

In any project development life cycle, documentation plays a key role. The advantages for the same are quite obvious.

In a big team it plays a crucial role. The reason for the same is if a developer has spent many days in creating a piece of code which has to be reused by other team members. If the documentation for the code is done in a proper way, other team members can simply refer to it and doesn’t have to seek much help from the developer who has developed it. Hence it is the responsibility of the developer to provide good documentation for it.

In java the above is achieved using Javadoc. PHP also has come up with a command line tool called PHP Documentor on the same line of Java doc.

Netbeans has provided a plugin to PHPDocumentor in there latest release Netbeans 7.0.

Installation of PHPDocumentor and integration with Netbeans

Prerequisite

- Netbeans 7.0 should be installed

- PEAR should be installed

Install PHPDocumentor

  • Run the command PEAR install –alldeps phpdocumentor
  • The above command will install PHP Documentor along with all the dependencies

Integration with Netbeans

  • Open Netbeans
  • Go to Tools->Options->Phpdoc and verify that it is identifying the PHPDocumentor installation. Please refer to the image given below
PHP Documentor Set Up

PHP Documentor Set Up

  • Right click on the project, select Generate PhpDoc
  • Enter the target directory where you would like to store the documentation and click Ok
  • Verify the output window
  • Once documentation generation is done, default browser would open with the index page for the documentation

Thanks,

Ushainformatique Development Team

Access file in restricted folder in PHP with cURL

January 29th, 2011 by Usha Informatique Team No comments »

Requirement

Many times, in a software project, a developer is required to access a file in a restricted folder as an HTTP request with allow_url_open in php.ini set to OFF. This is for Windows Environment.

Solution

The viable solution here is to use cURL, a command line tool for transferring date with URL syntax.

How to make a folder restricted with .htaccess and .htpasswd?

- In Project Folder, create a folder and call it Private

- In an editor, create a new file called .htaccess with following lines of code and save it inside Private folder

AuthName “Restricted Area”
AuthType Basic
AuthUserFile D:/wamp/www/TryPhp/private/.htpasswd
require valid-user

- Go to the following URL http://www.htaccesstools.com/htpasswd-generator-windows/

- Enter  a username and password and it would generate a string. Copy the string

- Create a new file and paste the string generated from above step and save it as .htpasswd in Private folder

- Try to access the folder with the weburl and it would prompt for a username and password

Access the folder with cURL

- Create a file in the root of the project and put the following code in it to access the content of any file within Private folder

<?php
$curlObj = curl_init();
$username = “{chosen username}”;
$password = “{chosen encrypted password}”;
curl_setopt($curlObj, CURLOPT_URL, “http://localhost/{Project Name}/private/{PHP File}”);
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlObj, CURLOPT_USERPWD, “$username:$password”);
curl_setopt($curlObj, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$output = curl_exec($curlObj);
$transferInfo = curl_getinfo($curlObj);
curl_close($curlObj);
print_r( $transferInfo );
?>

Note: Replace the following variables in the above code

- {chosen username}

- {chosen encrypted password}

- {Project Name}

- {PHP File}

The line curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, true); enables to retrieve the data in a variable from a remote file.

Thus in this way, you are able to successfully access a remote file using cURL.

PHPUnit on Windows with WAMP and Netbeans

January 29th, 2011 by Usha Informatique Team No comments »

In any software development project, the key to success is the creation of unit test cases and thorough usage of them during development and post development.

On the same line of Java, which provides JUnit as the Unit Testing Framework, PHPUnit can be used. I have gone through many resources on Internet and collated the information in this blog.

Steps to follow

- On successful installation of WAMP, open up the command prompt and go to your php directory in WAMP

- D:\>cd wamp\bin\php\php5.2.5

Pear Set Up

- Execute go-pear.bat file to install PEAR

- Accept the defaults for the questions asked by PEAR

- On installation of PEAR,  run PEAR_ENV.reg. It would create the environment variables to make pear globally available in command line

- D:\wamp\bin\php\php5.2.5>PEAR_ENV.reg

Register PHPUnit with PEAR

- Once you have PEAR setup, then you must register the PHPUnit channel with PEAR

- D:\wamp\bin\php\php5.2.5>pear upgrade pear

- D:\wamp\bin\php\php5.2.5>pear install alldeps force phpunit/phpunit

- You should now find the PHPUnit source files under the PHP directory with phpunit.bat in php main folder

- Restart wamp

XDebug Set Up

- Netbeans version should be 6.8 ( It will not work with version 6.5 )

- Install xdebug using the guidelines from http://xdebug.org/download.php and http://xdebug.org/install.php

- In php.ini ( Apache one ) copy the following lines

a.  zend_extension_ts = “D:/wamp/bin/php/php5.2.9-1/ext/php_xdebug-2.1.0-5.2-vc6.dll”
b.  xdebug.remote_enable=on
c.  xdebug.remote_handler=dbgp
d.  xdebug.remote_host=localhost
e.  xdebug.remote_port=9000

- Restart wamp

- Go to Tools->Options->PHP->general tab

- In general tab there is debugging option: Debugging port:=9000 session ID= netbean xdebug

- Remove net beans and write session ID = xdebug

- Restart IDE.

- Right click on file in the project and go to Tool->create PHPUnit tests . It will ask select the directory with project test file. Create a folder let’s say called “tests” in the project

- Test files would be created inside the folder

- For e.g. if we are writing test case for search.php, searchtest.php in the test folder would be created.

- Right click on the project folder and click on Test which would run all the test cases in the project against all the classes

- Also you can run the code completion by right clicking on the project folder and select code completion which would show you the results as how many functions in the project are there with test cases written for them.

You are all set to test your PHP classes with PHPUnit with debugging enabled.

EJB 3.1 Application with Stateless Session Bean on Glassfish 3.0 and NetBeans

June 18th, 2010 by Usha Informatique Team 14 comments »

Enterprise Java Beans (EJB) is a bit complex topic before the release of EJB 3.0 specification. In the EJB 3.0 specification the things are much simplified now from many perspectives

- Development of application using EJB

- Maintaining application having EJB

- Understanding of EJB for a new beginner

We have developed a sample application (with both local and remote interface) which illustrates creation of EJB and using it in a servlet. The infrastructure parts of the application are as follows

- NetBeans 6.8

- Glassfish Application Server (v 3.0)

The steps that needs to be followed are as follows

- Create a New Java EE Project SampleEJBApplication in Netbeans. Just follow the instruction provided by Netbeans.

- There would be three folders created ( SampleEJBApplication, SampleEJBApplication-ejb, SampleEJBApplication-war )

EJB Application

- In the SampleEJBApplication-ejb, create a package called com.sample.service

- Create a Local Interface called Calculator.java as follows

package com.sample.service;

import javax.ejb.Local;

/**
*
* @author Shashank
*/
@Local
public interface Calculator
{

public int calculate (int start, int end);

}

- Look out for @Local annotation which declare the interface to be local

- Create a class called CalculatorBean.java as follows which implements the local interface

package com.sample.service;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

/**
*
* @author Shashank
*/
@Stateless

@EJB(name=”java:global/MyCalculatorBean”, beanInterface=Calculator.class)
public class CalculatorBean implements Calculator {

public String getServerInfo () {
return “This is glass fish server using EE6 version”;
}

public int calculate(int start, int end) {
return start+end;

}

public int remoteCalculate(int start, int end) {
return start+end;
}

}

Notice few things in the above class

- @Stateless annotation which declares the bean to be stateless

- @EJB(name=”java:global/MyCalculatorBean”, beanInterface=Calculator.class), it says that when referring to this bean using JNDI it could be called using  java:global/MyCalculatorBean

Front End Application (SampleEJBApplication-war)

- Inside the Source folder, create a package called servlets

- Now there are two approach using which you can refer to local EJB

Approach 1

- Use @EJB annotation inside the servlet to call the local EJB ( Available with Glassfish and not JBoss :) )

Approach 2

- Use JNDI lookup inside the servlet to call the local EJB

- Create a servlet called TestServlet.java using Netbeans

- For Approach 1 the code will go as follows

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(”text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();

Calculator calculatorBean;
try {

Context context = new InitialContext();
calculatorBean = (Calculator) context.lookup(”java:global/MyCalculatorBean”);
out.println(”<html>”);
out.println(”<head>”);
out.println(”<title>Servlet TestServlet</title>”);
out.println(”</head>”);
out.println(”<body>”);
out.println(”<h1>Servlet TestServlet at ” + request.getContextPath() + “</h1>”);
out.println(calculatorBean.calculate(100, 200));
out.println(”</body>”);
out.println(”</html>”);

} catch (NamingException nex) {
nex.printStackTrace();
} finally {
out.close();
}
}

- Please notice as how the bean is referred using the JNDI name defined in bean class

- The same bean can be retrieved by using

a) (Calculator) context.lookup(”com.sample.service.Calculator”) (Non Portable JNDI lookup)

b) java:global/SampleEJBApplication/SampleEJBApplication-ejb/CalculatorBean!com.sample.service.Calculator (Portable JNDI lookup)

- For Approach 2, the code would go as follows

@EJB
private Calculator calculatorBean;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(”text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();

try {

out.println(”<html>”);
out.println(”<head>”);
out.println(”<title>Servlet TestServlet</title>”);
out.println(”</head>”);
out.println(”<body>”);
out.println(”<h1>Servlet TestServlet at ” + request.getContextPath () + “</h1>”);
out.println(calculatorBean.calculate(100, 200));
out.println(”</body>”);
out.println(”</html>”);

} finally {
out.close();
}
}

- Notice the usage of @EJB annotation with no issues regarding JNDI

- Run the code in both cases and should return 300 as the result

The implemtation for the remote interface would be given in next post.

Enjoy EJB 3.0 !!

Ushainformatique Development Team

Usage of Data Access Object (DAO) pattern in PHP

May 31st, 2010 by Usha Informatique Team 6 comments »

Data Access Object pattern is a heavily used design pattern used in J2EE, but good thing is that it could be used in a very efficient manner in PHP.

What is DAO pattern?

The very first thing we need to understand is what is DAO pattern. In our last blog on DTO, it is emphasized that Data Object is an exact replica of a database table with getter and setter methods for the fields.

Let’s assume that a database connection is created in the controller or in the managed bean of JSF and dataobject is populated with the results. Now i need to execute the same query in another controller or managed bean than i need to again write the same query. Thus in this way our database layer is tightly coupled to the web part.

Thus to abstract the database layer, if a new layer is introduced in between web and database which provides an interface to access the database, it would decouple the database from the web layer. Also, the same query hasn’t need to be rewritten. This is what is called Data Access Object Layer.

Usage of DAO pattern

Option 1
- Create a class called EmployerDAO.php

- Let’s say i want to display the list of employers, than my function would go like in the EmployerDAO.php

public function getEmployerDetails($id)
{
$employerQuery = “select * from tbl_employer where employerid=’$id’”;
$tempEmployerVO = new EmployerVO();

$employerResult = mysql_query($employerQuery);
$row = mysql_fetch_array($employerResult) ;

$tempEmployerVO-> setId() = $row-> id;

$tempEmployerVO-> setFirstname() = $row->firstname;

$tempEmployerVO-> setLastname() = $row->lastname;

return $tempEmployerVO;
}

Thus in the controller, you would instantiate the DAO class and call this method to retrieve the dataobject of employer.

In this way wherever you want to have the enployer details, just instantiate the DAO and call the result.

The key point to note here is that if the same table is used in another php project, you can use the same DAO layer. Thus it improves the efficiency and maintenance of the code to a large extent.

Option 2

Another way you can use the same DAO layer is as the interface and different classes can implement the interface as per the requirement. This is one more level of abstraction.

It would be helpful in cases where you have different logic to be implemented before populating the dataobject.

Give it a try !!

Ushainformatique Development Team

Dynamic JSF application with MySQL on Glassfish with Toplink

May 8th, 2010 by Usha Informatique Team 68 comments »

In my last post, i talked about developing a Dynamic JSF application with MySQL on JBoss with simple JDBC connection.

In this post, i am going to talk about a sample application with

- JSF

- Netbeans 6.8

- Glassfish Application Server

- MySQL Database

- Persistence API (Provider Toplink)

About the application

This would be a simple application which performs the following

- Insert Person Data into the database

- Fetch the person list from the database

The key difference over here is that we are going to use Java Persistence API over here to make the transactions.

First of all we need to understand as what is Java Persistence API.  As per the sun here is a very good definition for JPA.

The Java Persistence API is a POJO persistence API for object/relational mapping. It contains a full object/relational mapping specification supporting the use of Java language metadata annotations and/or XML descriptors to define the mapping between Java objects and a relational database. It supports a rich, SQL-like query language (which is a significant extension upon EJB QL) for both static and dynamic queries. It also supports the use of pluggable persistence providers.

Thus with the evolution of Java Persistence API, a standard of persistence framework has been set and many vendors are providing the implementation of the API and toplink is the open-source community edition of Oracle’s TopLink product.

Implementation

- In Netbeans, Create a Java Web project called TestPersonApplication and select the JSF framework while creating it. The folder structure would be created.

- After that create a mysql database,  in my case i call it jsfperson with table as person. The person table would have id (int), firstname (varchar) and lastname (varchar) as the fields

- Run the Glassfish Application Server and from services tab, against the server click “View Admin Console

Connection Pool Creation and JDBC resource creation

- After the admin console is loaded, click on JDBC and JDBC resources would be displayed

- Under Connection Pool, Click on Add a New Pool

- Enter Name, Resource Type as javax.sql.Datasource and Vendor as MySql and click on Next

- On the next screen, add the properties User, portnumber (3306), databaseName (jsfperson), Password, driverClass (com.mysql.jdbc.Driver), URL (jdbc:mysql://localhost:3306/jsfperson) and serverName(localhost) and click on Finish

- After Finish, click on Ping to check the connection, if the ping is successfully, your pool is created perfectly

- Now under JDBC resources, Click on “New”

- Enter the JNDI name and select the pool you created above (By default, when you again run the server, it creates a pool like mysql_jsfperson_rootPool, check that :) ) and click on Save

- After the save check sun-resources.xml under Server Resources and you will see the configuration

Creation of Entity Class

- Coming to Netbeans again, under Source Packages folder, create a package called com.domain

- Right click on the folder and select New – >Entity class from Database

- Select the datasource as jsfperson (Which you added earlier) and it will retrieve the database schema

- Select the table and Click on Add and than click on Next

- On next screen, it would show you the details for Person Entity and click on Finish

- The object would be created with Annotations for the mapping between Entity fields and Database field. The generated code would go like this

@Id
@Basic(optional = false)
@Column(name = “id”)
private Integer id;
@Column(name = “firstname”)
private String firstname;
@Column(name = “lastname”)
private String lastname;

The class would implement Serializable interface with getter, setter methods for the fields, equals method and toString Method. In addition, the queries would be generated as follows

@Entity
@Table(name = “person”)
@NamedQueries({
@NamedQuery(name = “Person.findAll”, query = “SELECT p FROM Person p”),
@NamedQuery(name = “Person.findById”, query = “SELECT p FROM Person p WHERE p.id = :id”),
@NamedQuery(name = “Person.findByFirstname”, query = “SELECT p FROM Person p WHERE p.firstname = :firstname”),
@NamedQuery(name = “Person.findByLastname”, query = “SELECT p FROM Person p WHERE p.lastname = :lastname”)
})

Check the @Entity and @Table annotation (Here the mapping starts) !!

Creation of Persistence Unit

- Right click on the project and select New -> Other -> Persistence ->Persistence Unit

- Enter Name, persistence provider which is Toplink and datasource created (jsfperson)

- Click on Finish and a file called persistence.xml would be created under configuration with transaction type as JTA

- Enter the class for which this PU would be used.  The xml would go like

<?xml version=”1.0″ encoding=”UTF-8″?>
<persistence version=”1.0″ xmlns=”http://java.sun.com/xml/ns/persistence” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd”>
<persistence-unit name=”TestJSFApplicationPU” transaction-type=”JTA”>
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<jta-data-source>jsfperson</jta-data-source>
<class>com.domain.Person</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties/>
</persistence-unit>

</persistence>

Creation of JSF Managed Bean

- Create a folder called com.testjsf under Sources Folder

- Right click on it and select New Jsf Managed Bean called PersonBean with configuration file as faces-config.xml under WEB-INF

- Declare two variables named Person (Entity Object ) and personList

- Create the getter and setter method for the variables

Creation of Data Access Object

Now we will make the connection class using DAO (data access object) design pattern

- Create a package called com.dao and create a class called PersonDAO

- The class would look like the following

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.dao;

import com.domain.Person;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
*
* @author Shashank
*/
public class PersonDAO {

public void insertData(Person p){

EntityManagerFactory emf = Persistence.createEntityManagerFactory(”TestJSFApplicationPU”);
EntityManager em= emf.createEntityManager();

try
{
em.getTransaction().begin();
em.persist(p);
em.getTransaction().commit();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
em.close();
}
}

public List getPersonList() {
List empList=null;
EntityManagerFactory emf = Persistence.createEntityManagerFactory(”TestJSFApplicationPU”);
EntityManager em= emf.createEntityManager();

try
{
Query q= em.createNamedQuery(”Person.findAll”);
empList= q.getResultList();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
em.close();
}
return empList;
}
}

In the above class there are few things to note

- JPA provides a class called EntityManagerFactory identified by persistence unit created above which manages all the transaction handling

- For example, to insert the data assuming Person object is there

a) Create a EntityManagerFactory

b) Create a Entity Manager

c) Begin transaction with em.getTransaction().begin()

d) call the persist function with person object as the argument. This statement would insert the data into the database

e) Finally commit is called

After creating the class, come back to PersonBean class and in the constructor for it, instantiate Person and Personlist (by calling PersonDAO getPersonList method). The constructor would go like

public PersonBean() {
person= new Person();

PersonDAO pDao= new PersonDAO();
personList = pDao.getPersonList();
}

Add two methods to it for adding a person and listing all persons which are as follows

public String addPerson()
{
PersonDAO pDao= new PersonDAO();
pDao.insertData(this.person);
this.setPersonList(pDao.getPersonList());
return “greeting“;
}

public String getAllPersonList()
{
PersonDAO pDao= new PersonDAO();
this.setPersonList(pDao.getPersonList());

return “go_person_list“;
}

Ok, now you are done with back end part. Keep the last two return statement in mind. I would discuss about them in the post below.

Front End with JSF

In the front end, add a file addPerson.jsp with firstname and lastname. The JSF part of it would go like

<f:view>
<h1>
<h:outputText value=”#{msg.inputname_header}”/>
</h1>
<h:form id=”helloForm”>
<h:outputText value=”#{msg.prompt}”/>
<h:inputText value=”#{personBean.person.firstname}” />
<h:inputText value=”#{personBean.person.lastname}” />
<h:commandButton action=”#{personBean.addPerson}” value=”#{msg.button_text}” />
<h:commandLink action=”go_person_list” value=”Show all persons”/>
</h:form>
</f:view>

Note that against the button action is mapped to addPerson method in the bean class.  The “h” and “f” tags are html and core tag libraries for JSF.

faces-config.xml

- Person bean is already added

- Add person as the managed property for it as

<managed-bean>
<managed-bean-name>personBean</managed-bean-name>
<managed-bean-class>com.testjsf.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>person</property-name>
<property-class>com.domain.Person</property-class>
<value>#{person}</value>
</managed-property>
</managed-bean>

This is how the person object is accessed under personbean in the jsf.

Handling Navigation

- Add the navigation rule as follows

<navigation-rule>
<from-view-id>/welcomeJSF.jsp</from-view-id>
<navigation-case>
<from-outcome>greeting</from-outcome>
<to-view-id>/personlist.jsp</to-view-id>
</navigation-case>
<from-view-id>/welcomeJSF.jsp</from-view-id>
<navigation-case>
<from-outcome>go_person_list</from-outcome>
<to-view-id>/personlist.jsp</to-view-id>
</navigation-case>
</navigation-rule>

- On submission of form, addMethod is called. If you see the last statement given above, on return “greeting” , the flow would go to first navigation rule with from view as welcomeJSF.jsp and action as greeting thus personlist.jsp would be called and loaded.

- The person list file would go like

<f:view>
<h:form>
<h:dataTable value=”#{personBean.personList}” var=”item”>
<h:column>
<f:facet name=”header”>
<h:outputText value=”Id”/>
</f:facet>
<h:outputText value=”#{item.id}”/>
</h:column>
<h:column>
<f:facet name=”header” >
<h:outputText value=”First Name”/>
</f:facet>
<h:outputText value=”#{item.firstname}”/>
</h:column>
<h:column>
<f:facet name=”header” >
<h:outputText value=”Last Name”/>
</f:facet>
<h:outputText value=”#{item.lastname}”/>
</h:column>

</h:dataTable>
</h:form>
</f:view>

In the file above, when {personBean.personList} is called, personBean is invoked and in the constructor, the latest person list is set. Thus on calling getter for personList, it returns the latest list after addition.

Thus you can develop the sample application using JPA with JSF in netbeans.

Thanks,

Ushainformatique Development Team

Implement Yahoo weather API along with Google map integration

May 2nd, 2010 by Usha Informatique Team 54 comments »

Requirements

We got a requirement to display weather for a city along with google map for the city.

Approach

There can be two approach that can be used

1) Implement yahoo weather API and Google map separately thus each is working independently

2) Implement google map using the information derived from yahoo weather API

Here i am going to talk about the second approach

To access weather for any city using Yahoo weather API, you have to use the following code

<?php

<span>XML</span> document into memory first.

$doc = new DOMDocument();

$doc->load(’http://weather.yahooapis.com/forecastrss?w=’.$weatherlocation.’&u=c‘);

//now I get all elements inside this document with the following name “channel”, this is the ‘root’

$channel = $doc->getElementsByTagName(”channel”);

//now I go through each item withing $channel

foreach($channel as $chnl)
{

$item = $chnl->getElementsByTagName(”item”);

foreach($item as $itemgotten)
{

echo “<b>”.$itemgotten->getElementsByTagName(”title”)->item(0)->nodeValue.”</b><br/>”;

//now I search within ‘$item’ for the element “description”

$describe = $itemgotten->getElementsByTagName(”description”);

//once I find it I create a variable named “$description” and assign the value of the Element to it

$description = $describe->item(0)->nodeValue;

//and display it on-screen

echo $description;

$latitude=$itemgotten->getElementsByTagName(”lat”)->item(0)->nodeValue;

$longitude=$itemgotten->getElementsByTagName(”long”)->item(0)->nodeValue;

}

}
?>

In the above code, the yahoo weather url is called with arguments w and u (Unit of temperature). “w” is the location of the city you want the get the weather for. This you will get from yahoo weather page http://weather.yahoo.com.

Simply enter the city and from the url retrieve the value for e.g in http://weather.yahoo.com/united-states/california/bombay-2366506/, 2366506 is the value of “w”.

The last two lines in the code above are the tricky one’s. From the last two lines, you can retrieve the latitude and longitude of the place, thus think you are saving so much database space by not storing latitude and longitude of places.

After getting the latitude and longitude for the place just pass to it google map API code which in my case is like the following

<script type=”text/javascript” src=”http://www.google.com/jsapi?key=ABQIAAAAQg2VLDfgi8yxVrFlqjXF7xTQHiNlpCS1vy260As8BGMS2rl5kBTvFuKiyHlh1z2mfCbd6sJqj9WfIw”></script>
<script type=”text/javascript”>
google.load(”maps”, “2.x”);
</script>
<script type=”text/javascript” charset=”utf-8″>
$(document).ready(function(){
var map = new GMap2($(”#mapdiv”).get(0));

var delhi = new GLatLng(<?php echo $latitude; ?>,<?php echo $longitude; ?>);
map.setCenter(delhi,8);
marker = new GMarker(delhi);
map.addOverlay(marker);
});
</script>
<style type=”text/css” media=”screen”>
#mapdiv { float:left; width:213px; height:144px;padding:0px 0px 0px 0px;margin:0px 0px 0px 0px;overflow:hidden;border:1px solid #CCCCCC;}

</style>
<div id=”mapdiv”></div>

Thus i would have both weather and google map for the place by just storing one value in the database  i.e. “w” factor.

Thanks !! Ushainformatique Development Team

Usage of Data Transfer Object (DTO) Pattern in PHP

April 27th, 2010 by Usha Informatique Team 57 comments »

Data Transfer Object is a heavily used design pattern used in the development of web applications requiring database interaction in J2EE. It makes the life of a developer highly easy in managing the data that is being transferred and provides a secured way of transferring the data between layers.

When i switch from J2EE to PHP and with the release of PHP5, it suddenly comes to my mind to use this concept along with Data Access Object pattern (which i will explain in my next post) from J2EE in PHP  and it worked wonderfully for me to meet any level of complex applications.

What is a Data object?

First of all, we need to understand as what is a data object. A data object is a class representing a table in the database with the field names exactly same as database column names. It contains the getter and setter methods for these fields.

Let’s say i have a table called tbl_employee having columns as

- id (int 10)

- name ( varchar(50))

Now, the dataobject would typically look like

public class Employee()

{

var $id;

var $name;

public function getId()

{

return $this->id;

}

public function setId($tempId)

{

$this->id=$tempId;

return $this->id;

}

public function getName()
{
return $this->name;
}
public function setName($tempName)
{
$this->name=$tempName;
return $this->name;
}

Now the next point is about using it and see how helpful it would turn out to be. The following function interacts with the database thus assuming database connection is available.

public function getEmployeeList()

{

$employeeList = array();

$query = “select * from tbl_employee order by name”;

$result = mysql_query($query);

while ($row=mysql_fetch_array($result))

{

$tempEmployeeDO = new EmployeeDO();

$tempEmployeeDO->setId($row['id']);

$tempEmployeeDO->setName($row['name']);

$employeeList[count($employeeList)] = $tempEmployeeDO;

}

return $employeeList;

}

Thus the above function returns the list of employees containing data objects. On the front end you need to iterate through the list where each element is a DO and than use getter method to retrieve the values.

Start using it and you will realize that it makes your life pretty easy during development.

Enjoy!!

Ushainformatique Development Team

Database modeling with Microsoft Visio for an Existing MySQL Database

April 18th, 2010 by Usha Informatique Team 89 comments »

In a SDLC, creating a database model diagram is an important step that needs to be taken to achieve the following

- Create a clear visualization of the Database for the system which makes the database understanding pretty easier

- It helps in derive out the classes required to be created by just looking into the database modeling diagram in depth

If you are not able to buy the paid tool for UML modeling such as rational rose etc., it’s still achievable through Microsoft Visio. Following are the steps that need to be performed to create a model diagram from an existing MySQL database in Microsoft Visio which is called as Reverse Engineering

- First of all, download the ODBC driver for MySQL from the location http://dev.mysql.com/downloads/connector/odbc/5.1.html. Download the installable by selecting the appropriate one based on  your machine configuration (32 bit or 64 bit)

- Install the mysql connector

- After installation, open visio

- Go to File->New->Database->Database Model

- From Database Menu, select Reverse Engineer

- On the Create New Datasource screen displayed, click on User Data Source

- Provide a datasource name

- Select the mysql connector driver, click on Next

- Click Finish and your new datasource would be added and would come as selected

- Click on Next

- Enter the valid username and password to create the connection using the datasource

- Select Object Type to reverse engineers

- You would be asked to select the database

- On selecting database, tables would be displayed

- Select the tables you want to create the datamodel for

- On selecting the tables, you would be asked to create the model with shape or without shape

- I select the shaped one and the model is generated

It’s really a helpful tool for the beginner to start creating the Database Modeling Diagram from an existing Database

Code Formatting in Netbeans 6.8

April 17th, 2010 by Usha Informatique Team 21 comments »

In any project in web world, code formatting plays a key role during the development of the project as it makes the code review process very simple at least from readability point of view.

The more readable your code is the more easy it is to review it. Now, how to format the code in Netbeans 6.8.

There are two levels at which formatting can be performed in Netbeans 6.8.

1) At a global level – It’s applicable across all the projects for which netbeans would be used

2) At a project level – It is specific to a particular project

For the first option

a) Go to Tools->Options->Editor-> Formatting

b) Please select the language for which you want to apply the formatting, for me it is PHP

c) Select the category, which could be Tabs and Indent or Braces

d) Put your option for Tabs and Indent in terms of tabs or if you choose to go with spaces

e) For braces, you can select new line, same line or preserve existing

This is pretty useful as if you are aware of it, it saves lot of effort from your end.

Enjoy working with Netbeans 6.8 !!