phpWebApp article
Upcoming SlideShare
Loading in...5

Like this? Share it with your network


phpWebApp article






Total Views
Views on SlideShare
Embed Views



1 Embed 2 2



Upload Details

Uploaded via as Adobe PDF

Usage Rights

CC Attribution-ShareAlike LicenseCC Attribution-ShareAlike License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

phpWebApp article Document Transcript

  • 1. The phpWebApp Framework and the SEE-GRID Resources Web Application Dashamir Hoxha1 and Elda Nallbani1 Institute for Informatics and Applied Mathematics (INIMA) Lek Dukagjini, 3 Tirana, Albania {dhoxha,enal} Abstract. This paper presents the phpWebApp framework, which is a framework based on PHP, used to facilitate the construction of web applications. It explains its features and advantages over other methods of building web applications, and then makes an overview of its main components. It also presents a concrete web application which is built using this framework. . . .1 IntroductionThe SEE-GRID resources map1 is a dynamic web page which provides informa-tion about the grid resources of each country participating in the SEE-GRIDproject. This information is stored in a database and is displayed dynamicallyin a weather-map. The information in the database needs to be updated period-ically by the GRID administrators of each country and cluster. In order to enable the administrators to access this database easily and tomodify the relevant information, we built a web application which acts as webinterface to this database. This application, to which we will refer to as gridrc(SEE-GRID Resources), allows every participant of SEE-GRID to see all theinformation about SEE-GRID resources, and allows only the administrators tomodify the information about the cluster/country that they administrate. Allthis is done from a user-friendly web interface. The tool that we used to build gridrc is the phpWebApp framework. Thisframework is based on PHP and allows the web application developer to work ata higher level than PHP, making the development of the web application easier.It is template based and works like an engine that fills the templates of theapplication with data that are retrieved from the database or that are computedby the PHP code. It then generates (creates) an HTML page, which is sent tothe browser by the web server.1
  • 2. 2 Dashamir Hoxha et al.2 SEE-GRID Resources (gridrc) Web ApplicationThis web application displays the grid resources for the countries that partici-pate in the SEE-GRID project 2 . For each country it displays the list of clustersthat are available in this country. For each cluster it displays derails such as ad-ministrator contacts (name, email, phone), security contacts, summary resources(total number of nodes, type of cluster, storage type, etc.), grid applications thatare installed, and a list of nodes with details for each node. It also displays somesummary tables (reports) about clusters and applications, which are generatedby processing the data in the database. Besides displaying these data, the web application has also an edit mode 3which allows the authorized persons (admins of the countries and clusters) tomodify the data in the database. When the application is in edit mode, therewill be an Edit button at the pages that can be modified. However, it will askfor a password before allowing any modifications. The idea is that each countryhas an admin and each cluster has an admin, and only the admins can modifythe data. Who is considered to be admin? Whoever knows the edit password(there is a different password for each country and each cluster). The admin of the country can add/delete clusters, can set/reset the passwordof the cluster admins, can modify some general info about the cluster, and ofcourse can change his own password. The admin of the cluster can modify thedetails of the cluster, can change the cluster admin password (his password),etc. After the country admin logins, he can change his own password and canchange/set/reset the password of the cluster admins. Once the database of the resources is filled with data, the SEE-GRID re-sources map can read these data, and using a javascript library (overLIB), canproduce the map. overLIB is a JavaScript library created to enhance websiteswith small popup information boxes (like tooltips) to help visitors around a web-site. It can be used to provide the user with information about what will happenwhen they click on a link as well as during the movement of the mouse. We are going to talk first about the phpWebApp framework, and then wewill illustrate its features with examples by the gridrc web application.3 Why We Didn’t Use Plain PHP?Constructing a web application with PHP or any similar scripting language isusually much more difficult than constructing a desktop application (e.g. usingVB, VC++, KDevelopper, etc.). It is because it has inherently some bad sidesand weak points which can be observed in most of the web applications. Someof these problems and difficulties are discussed below.2
  • 3. phpWebApp and SEE-GRID Resources 33.1 Mixing HTML, CSS, JavaScript, PHP, SQL codesSuppose that we have constructed a web application with PHP. If we inspectthe code inside one of the files of the application, what we usually see is HTMLcode, JavaScript code, CSS code, PHP code, SQL code etc. all jammed together.This kind of mixing many languages inside the same file is a really bad thing,for these reasons:It makes the editing of the application very difficult. Most of the editors have code colorizing features, automatic indentation features, etc. for many languages, in order to simplify editing and to make it easy. But when they are faced with such a mix of languages, very often they get confused. As a result, such features become useless, and even they become harmful, because they may colorize wrongly or indent wrongly.It makes the maintenance of the application very difficult. It is very dif- ficult for somebody else to try to read, to understand and to modify such a code, and even for the author of the code himself (after some time has passed).Makes difficult the team work. Suppose that a web application is constructed by a team that is composed of PHP programmers, who construct the server side logic of the application, web designers (HTML+CSS) who create the look and feel of the application, JavaScript programmers who construct the client side logic of the application, and DB specialists who construct the database and the queries. In this case it is very difficult for any one of them to make modifications in a big file that has lots of unfamiliar code to them, without making any mistake. Take for example the web designer, it is very difficult for him to change the look and layout of a web page that is tightly interwoven with PHP code.Increases the complexity of web applications. Different from the previous example, suppose now that a web application is constructed by one or more programmers and each of them is responsible for a certain part of the ap- plication. In this case each of them has to have good skills in all of them: PHP, HTML, CSS, JavaScript, database, etc. This is difficult to be achieved and it increases the complexity and the difficulties of constructing a web application. It is clear that such a mix of codes is a bad thing and a bad practice and itmust be avoided as much as possible. The HTML syntax offers a possibility to take out the JavaScript code andthe CSS code in separate files. It is like this:<script language="javascript" src="file.js"></script><link rel="stylesheet" href="file.css" type="text/css" /> However there is no standard way to clearly separate the HTML, PHP andSQL codes. You can try to keep the degree of mixing of HTML and PHP codeat a minimum level by carefully designing the application. E.g. you can place all
  • 4. 4 Dashamir Hoxha et al.the PHP code unrelated to the HTML generation (the code that contains thelogic of the application) in a separate file and keep the file that generates theHTML page as lean as possible. A better solution to separate the HTML and PHP codes is to use a templateengine. It uses templates for generating the final HTML page. Each template is apure HTML file, which also has some slots or variables in it. The values of thesevariables are calculated by the PHP code and they are passed to the engine.Then the engine reads the templates, replaces the variables by their values andthus generates an HTML page which is sent to the browser.3.2 From one page to the next, global variables are lost.Different from the desktop applications, web applications are discrete. Thismeans that one view (page) of the application has almost no connection tothe next one. This is because global variables are lost and each page has to beconstructed from the scratch. Each web application can be thought as a state machine. Each time you see inthe browser the application at a certain state. When you click something insidethe page, then the application goes to another state and it sends to the browseranother page. However, oddly, web applications cannot keep their state in theirglobal variables because from one request of the browser to the other they arelost. This is inherent in all web applications because the HTTP protocol is astateless protocol [2]. Usually, web applications try to overcome this problem by using session vari-ables, cookies, parameters in the CGI query, etc. However there is no easy andstandard way and this often results in overhead (because you have to write spe-cial code for storing and retrieving these variables), increased complexity, etc.3.3 Lack of modularity.Big web applications are usually huge and monolithic, not only in code but alsoin the programing logic. So they have all the problems that are caused by the lackof modularity: they have high complexity, it is difficult to maintain or improvethem, the code cannot be reused easily in other applications, etc. By careful design and implementation, a web application can be made moremodular, and usually big web applications do it (otherwise it would be toodifficult to build and maintain them). However this modularization is differentfrom one application to the other, it is specific to the web application itself andcannot be reused or applied to another web application, because it is not enoughgeneral4 .4 If it is somehow general, so that it can be applied for a certain domain of web applications, then it would be a framework or engine, and the application would not be considered to be built on plain PHP.
  • 5. phpWebApp and SEE-GRID Resources 54 Why Not Another Framework?From the above section it is clear that using a framework or engine or templatesystem is usually better than using plain PHP, for building a web application. Tomake a comparison with desktop applications, you can build a windows applica-tion even using the C Win32 API, but it is much more easy and convenient to useVB or VC++ (which are in fact just frameworks, based on C API, for buildingwindows applications). To build a windows application using the C API wouldbe just like using Assembly for writing a program. Similarly, using a frameworkfor building a web application usually is more convenient then using plain PHP.Of course it has some overhead, because you will have to learn how to use theframework first, before starting to build the application. There are a lot of frameworks or template systems that can be used forbuilding a web application. Just make a search at sourceforge.net5 for “webapplication framework” or for “template system” and you will discover a lot ofthem. Some of them are ColdFusion6 , Smarty7 , etc. However we chose phpWebApp because: – It is free (licensed with GNU GPL). – In our opinion, it is more flexible, powerful, user-friendly and better than the others. – We have experience with it and know it better than the others.5 The PHP Web Application Framework (phpWebApp)5.1 What is phpWebAppphpWebApp is an application framework for building PHP web applicationsbased on relational databases. It separates the graphical design and layout ofthe application from the logic of the application by using templates. It also pro-vides a kind of event-based programing model (similar to that used in VisualBasic and other visual languages), object-oriented structure of the application,easy interface to database, code re-usability, etc. It can be used to construct eas-ily and efficiently eCommerce applications, eGovernment applications, eContentapplications and any kind of web applications.5.2 phpWebApp FeaturesSome of the features of the phpWebApp framework, and the advantages andbenefits of using it for building web applications, are these:5
  • 6. 6 Dashamir Hoxha et al. – The framework uses a kind of template system which separates the layout from the logic of the application, so a graphical designer can easily improve the layout of the application without getting messed with the logic and with- out having to understand it. It makes easier the work of both the graphical designer and the programmer. The framework also separates the JavaScript code and the CSS code from the HTML code and the DB queries from the PHP code. – The framework gives the possibility to divide a page into several parts which can be used in other pages as well. This makes the user interface of the application (the layout, the graphical part) more structured and easier to understand and maintain and makes easier the work of the graphical de- signer. – For the framework, a web application is like a state machine, which can be represented and described by one or more state chart diagrams. Each page of the application that is displayed represents the application in a certain state. Clicking to a link causes a transition to another state of the application. The state of the application is kept in the so-called state variables, which are similar to session variables. This simplifies the design and the implementation of web applications. – The framework supports an event-based programming model. When a tran- sition from one state of the application to another happens, it may trigger an event as well, which is handled by a function (event handler). It is imple- mented by building on top of CGI another level of communication between browser and server. The event-based programming model makes the logic of the application easy to build, understand and maintain, and makes easy the work of the web programmer. – The framework gives to the web programmers the possibility to create web components (called WebBox-es). They have their own user interface (HTML+CSS code), client side behavior (JavaScript code), server side behavior (PHP code), state variables, events, event handlers, etc. Each component can be made almost 100% self contained and independent from the other parts of the application, and it can be a state machine on its own.The big state machine of the application is a composition of the state machines of its components. This can reduce dramatically the complexity of a web application; instead of having to build a huge monolithic state machine for the whole application, we can build several small state sub-machines and compose them. – Since the components are independent from the rest of the application, they can be very easily reused in other web applications. So, the framework pro- vides code re-usability, which means that if you have constructed something once, you don’t have to re-construct it again when you need it another time, but reuse the existing one. – The framework brings closer the client-side and the server-side logic of a web application. E.g. the state variables are available and can be accessed both on the client side (JS code) and on the server side (PHP code). – The framework simplifies the interaction of the application with the database. It also makes it almost database independent. This means that in case that
  • 7. phpWebApp and SEE-GRID Resources 7 you decide to change the database on which your application is based (e.g. switching from MySQL to Oracle), then the application itself doesn’t need to be changed at all, it will work all the same. – An application based on the framework is easy to maintain (debug, improve, extend, etc.). So, the framework also facilitates an iterative and incremental development approach for web application projects. – The framework supports internationalization (i18n) and localization (l10n), based on standard GNU gettext tools. This means that a web application can be translated easily in other languages. – Another thing is that phpwebapp offers good debugging features, which makes easier the development. Without debugging, software development would be a nightmare, isn’t it.6 The phpWebApp Components6.1 TemplatesTemplates are normal XHTML files which can contain some additional tags andsome variables. These tags and variables are processed by the framework and arereplaced with XHTML code when the web page is created. These templates allowthe web page designer to work almost independently from the database designerand from the PHP programmer that implements the logic of the application.Some of the extra tags that can be used in templates are:Include : It is used to include a template inside another template. It provides modularity (breaking a large page into smaller templates) <include src="{{./}}edit/cluster_edit.html" />Repeat : This element is connected with a recordset by the attribute ”rs”. Its body is processed for each row of the recordset. Before processing the content for a certain row, all the fields of the recordset are declared as variables with values taken from the current record. <table> <repeat rs="clusters"> <tr><td>{{cluster_name}}</td></tr> </repeat> </table>If : The content of this element is processed conditionally: if the value of the attribute “condition” is true, then it is processed, otherwise it is not pro- cessed. The value of the condition is calculated as a PHP expression (after the template variables have been replaced).
  • 8. 8 Dashamir Hoxha et al. <if condition="!{{admin}}"> <a class="button" href="javascript:edit()">Edit</a> </if>Recordset : Each recordset has a unique id. <recordset id="country"> <query> SELECT country_name, description FROM countries WHERE country_id = ’{{country->id}}’ </query> </recordset> Some other elements that can be used are: <var>, <webbox>, <!--# comments #-->, etc.6.2 Template VariablesVariables are used in templates to insert a dynamic string in it. Its value is notknown at the time that the template is designed, it is given by the php partof the application or by the framework (e.g. by getting it from the DB or bycalculating it according to a certain logic). Their value is always a string, whichreplaces the variable when the template is processed by the framework. Template variables are denoted like this: {{var_name}}. var name insidethe curly braces may contain any character, and it is case sensitive. Doublecurly braces is chosen because single curly braces sometimes may occur inside atemplate, e.g. in JavaScript code. A template variable is declared in the php code of the application, in thephp code of the weboxes, in the <var> template tag, in the <repeat> templateelement (implicitly), or gets its value from a state variable, from a global phpvariable or from a php constant that has the same name as the {{variable}}. In the php code, the variables are declared using these functions: WebApp::addVar(var_name, var_value); WebApp::addVars(assoc_array); The framework finds the value of a {{variable}} like this: 1. First the current scope is searched for it. 2. If it is not found, then the scope above it is searched, and so on until it is found. 3. If it is not found in any scope, then session variables are searched for it. 4. If it not found among session variables, then global variables of PHP are searched for it. 5. If it is not found there, then constants of PHP are searched. 6. If it still is not found then its name is taken as its value (e.g. {{var1}} is replaced by {var1}).
  • 9. phpWebApp and SEE-GRID Resources 96.3 State VariablesState (session) variables are persistent variables (don’t loose their value fromone page to another. They can belong to webbox-es or they can be global to theapplication. They correspond to the global variables of the desktop applications(e.g. VB applications). The framework keeps the state variables inside the web-page itself. They arepassed from PHP (server) to HTML (client) and from HTML to PHP continu-ously. If you view the source of a page of an application, you will notice themin the end; they are appended automatically to the end of each page by theframework itself. Also, whenever you make a transition to another page of theapplication, using the function GoTo(), all the state variables are sent to theserver as well, and this is taken care by the function GoTo() itself.6.4 TransitionsA transition is the move of the application from one state to another (usuallyfrom one page to another). A state of the application is composed of a templatefile and some state variables. A transition is usually triggered by a client-sideevent in the browser, such as: clicking a link, pressing a button, submitting aform, timeout of a javascript timer, etc. In phpWebApp a transition is done by calling the function GoTo() whichis declared by the framework itself, e.g. GoTo(’page1.html’). In this case, theGoTo() function sends a request to the web-server for another page. This requestis processed by the framework, which loads the template ’page1.html’ processesit and sends it to the browser.6.5 EventsUsually, during a transition, an event is sent as well to the next page. Thisevent is handled by the PHP code of the application, which may do some inputvalidation, save data to database or get data from database, change the state ofthe application, etc. An event can be sent to a webbox using this function (which calls GoTo() tomake a transition): SendEvent(’targetBox’, ’eventName’, ’arg1=val1;arg2=val2’);When the framework gets an event, it sends it to the webbox targetBox by callingthe function targetBox::on_eventName($event_args$). The variable that ispassed to this function is an associative array which contains the arguments ofthe event.6.6 WebBox-esA WebBox is a template which has also some PHP code associated with it. It isa self-contained and independent template which can be easily included in other
  • 10. 10 Dashamir Hoxha et al.pages or in other applications. In fact, it may also have some JavaScript code,CSS stylesheets, SQL queries etc., associated with it. It is denoted by the tag <WebBox> and it has an ID attribute: <webbox id="box_id"> <!-- content of WebBox --> </webbox>The identifier must be different for each WebBox used in the application. The PHP code (as well as JS code, CSS styles etc.) are associated to theWebBox by means of box id, the identifier of the WebBox. When the frameworkparses a <WebBox> tag, it looks for a file named box id.php in the same folderwhere the WebBox template is. If it finds such a file, it includes it. The box id.php file must contain the definition of a PHP class that extendsthe class WebObject, like this: <?php class box_id extends WebObject { . . . } ?>The class WebObject is defined by the framework. It contains the member func-tions WebObject::init(), WebObject::onParse() and WebObject::onRender(). The function onRender() of the class WebObject is called by the frame-work at the time of the HTML page construction (the page that is sent to thebrowser), just before the template of the WebBox is output-ed (rendered). Ac-tually WebObject::onRender() is an abstract (empty) function, and the frame-work expects the class box id to override it, in order to do something useful forthe WebBox. What is usually done in box_id::onRender() is assigning valuesto the variables used in the template of the WebBox box id, so that the templateis rendered properly. Besides the file that contains the template of the WebBox and the box id.phpthat contains its PHP class, there may be other files as well that belong to theWebBox. These are: box id.js that contains the JavaScript code of the WebBox,box id.css that contains the stylesheet of the WebBox, box id.db that containsthe recordsets of the WebBox, etc. If the framework finds such files, it automat-ically integrates them in the generated HTML page. For example, it includesbox id.js and box id.css in the head of the page. Of these files, the template isthe most important. There can be a WebBox without JS code or without PHPcode, but there cannot be a WebBox without template code.6.7 DatabaseThe database component of the application is very important, because most ofthe web applications are based on relational databases. It allows an application
  • 11. phpWebApp and SEE-GRID Resources 11to interact with a database, to get and display data from it, to save, updateand delete data in it, etc. The framework tries to make this interaction as easyand as convenient as possible for the application developer, without loosing theflexibility. It also tries to ensure that the database is used in an abstract way,so that it doesn’t matter for the programmers whether the database is MySQL,Oracle, etc. To enable the DB component, open the file ’config/const.Settings.php’ andset the constant ’USES DB’ as ’true’. After this, create the file ’config/const.DB.php’and define in it the constants DBHOST, DBUSER, DBPASS and DBNAME,which will be used to open a connection with the database. Inside a template, we can get and display data directly from the DB usingthe tags <Recordset> and <Repeat>.6.8 WebClass-es and WebObject-sThe element <WebClass> defines a web class, but it by itself does not produceany HTML output. The element <WebObject> declares an object of the classand the content (the template) of the <WebClass> is used for this object. Thesetwo elements can be used for small components which can be used more thanonce in an application (WebBox-es are not suitable for this, because their IDmust be unique in the application). Some of the WebClass-es that are defined by the framework are these:tabs : displays a horizontal tab-like menu.datebox : can be used to select the date from a popup calendar.listbox : can be used to display a list of values which are taken from a recordset.dbTable : can be used to display and edit the content of a database table.formWebObj : makes easy the handling of big forms (which have many inputs).7 The Structure of GRIDRCSince gridrc is based on phpWebApp, it follows some conventions that are re-quired by the framework. It has the files ’index.php’ and ’webapp.php’ whichare the same for all the phpWebApp-based applications. These files include theframework classes, which then read the configuration and the templates of theapplication and create an HTML page which is sent to the browser. The configuration of the application is required by the framework to be inthe folder ’config/’ and it has these files, which define some constants:const.Options.php : constants that modify the behavior of the framework.const.Paths.php : constants about the paths of the application.const.Debug.php : constants that enable/disable debugging features.const.DB.php : constants about the database connection. The templates and webbox-es of the application are placed in the folder’templates/’. They are organized so that there is one folder for each webbox and
  • 12. 12 Dashamir Hoxha et al.the included webbox-es are placed in sub-folders of this folder. Each webbox hasan HTML file (which is required), and it usually has also a PHP class. It mayalso have a JavaScript file (.js) and a CSS file (.css), which are included by theframework at the head of the page. If it interacts with the database, it can alsohave a .db file that contains the queries.8 Future WorkThe future work includes improvement of the documentation of the framework:writing a manual for the developers and tutorials for getting them started. Itincludes also improvements that can be done to the framework itself. In generalthese are small improvements and they will be done as the need for them arises(when the applications that use the framework need them). Another thing that can be done is to improve the tools for working with theframework. E.g. an Emacs mode can be created that helps when working withthe framework. Or maybe a plug-in can be developed for Quanta for buildingphpWebApp applications. We may try as well to do automatic code generationof web applications from UML models (e.g. from UML state chart diagrams,since each webbox is like a state machine), and reverse engineering (buildingautomatically a UML model from an existing application). Another useful thing that can be done in the future is to build reusableWebBox-es or WebObject-s, which can facilitate the construction of new appli-cations. These reusable components/objects can be even organized in a higherlevel framework (based on phpWebApp) for building web applications of a certainkind.References1. The phpWebApp documentation: Roy T. Fielding and Richard N. Taylor. “Principled design of the modern Web architecture”. ACM Transactions on Internet Technology (TOIT), 2(2), May 2002, pp. 115-150. This document is available at field- ing/pubs/webarch icse2000.pdf.