You are on page 1of 35

SIP PHP Posibilities

Advantages of using PHP in a web project like SIP (and others) and considerations about AJAX projects and web projects in general.

The usual structure of a PHP web application is a 3 tier one; this means the high level structure of the SIP application is very similar.

Data layer

This would be a database server; the most common ones used with PHP are MySql, Postgres, but any database server can be used: Oracle, MsSql etc. If the database server is Mysql then the operating system is recommended to be Linux, and not Windows, since the performance of Mysql on Linux is significantly better.

Mysql technical specifications and advantages


Pluggable Storage-Engine Achitecture (InnoDB , MyISAM, Merge, Memory, Archive) ANSI SQL (SubQueries, Joins, Cursors; Prepared Statements; Views; Triggers;Stored Procedures; User-Defined Functions); ACID Transactions, Commit, Rollback , Foreign Keys, Referential Integrity Easy Install and Setup; Built-in Replication Engine, Master/Slave,; MySQL Cluster (99.999% Availability, Distributed architecture, Synchronous replication) 99.999% Availability, Distributed architecture, Synchronous replication Hot Backup for InnoDB, Full, Incremental, Partial Backups, AutoRestart/Recovery SSL Support, Built-in Data Encryption/Decryption Graphical Tools: MySQL Workbench

MySQL Workbench

Business layer This usually is a web server with support for PHP. The most common webservers used with PHP are Apache, Lighthttpd, Nginx but also IIS is suported The Apache webserver has a lot of configuration options and is very well documented and documentation can be found in many places on the web (by using Google) . The Code architecture is recommended to be MVC as it is a flexible and week coupled . This means, that , if it it is implemented correctly, and depending on the application, changes can be done in any of the 3 main parts of MVC, without having to change something also in other part. There is no conflict between the 3 tier architecture and MVC; The Model is the MVC component which would contain the the business layer. The View need not access directly the Model, since it is the Controller which makes the connection between the Model and the View

The Presentation (Client) Layer

This would be standard HTML (+CSS, JS,Flash), generated by PHP . PHP appeared as a web scripting language which can be integrated into web pages. It has evolved into a full language with strong object oriented capabilities. At the same time it kept it real ease of use, simplicity and conciseness, so it is recommended that the language used in the presentation pages themselves should also be PHP. Alternatives to using PHP in the presentation layer exist, like Smarty, but they are not recommended, since you cannot really get more chort and concise than PHP is, and also for performance reasons.

A) classical web application the flow

1. the browser sends an HTTP request to the web server; 2. the server receives the request and sends it to the PHP component; 3. this loads and executes the controller 4. the controller can do:
a. security checks (like authentication and authorization) ; b. loads and executes one or more models; c. the models (which should implement the business logic) access the necessary resources (like database, web services, or others), and return data (or populate some internal Model state); d. load the View ; the view is composed of HTML ((+CSS, JS,Flash) with place holders for dynamic data, and basic operations over presentation data(iterate, conditions); e. render the view by merging the data from the Model with the View; f. send the result to the client browser.

5. each time the client clicks on a link the new page is loaded by going the full process starting from point 1.

B) A massively AJAX web application (like SIP) flow :

1. 2. 3. 4.

the browser sends an HTTP request to the web server; the server receives the request and sends it to the PHP component; this loads and executes the controller the controller can do:
a. b. c. d. security checks (like authentication and authorization); loads and executes a minimum number of models; loads a View which is very basic and is only the skeleton for the full html page; the view contains special javascript which will execute once the browser receives fully the basic html page; renders and view and sends it to the client

5. 6. 7. 8.

The client (browser) receives the basic html page , and after it is fully loaded it executes the javascript set to execute on DOM load. This script makes many AJAX calls to the server for the content of each block in the page. Each of these requests goes through the full process described at point A, but the result is only the content of a block in the page . the page is now fully loaded in the client browser each time the client clicks on a link one of 2 things can happen:
a. b. if the page which the client wants is different enough then the current page the client is on, then the whole process from the B 1 starts again; if the page which the client wants is similar enough to the current page the client is on, then process from point 6 executes, but not for all the blocks in page but only for the blocks which need to be updated (depending on the business logic and application) .

Advantages and disadvantages of a massively AJAX web applications


Advantages

If the pages do not vary much between them (from a layout point of view), then the responsiveness of the application for the end user is increased.

Disadvantages

The design has to be made by the designer with great care , to support missing, appearing and disappearing blocks from the page without the layout breaking in any browser; The pages should not vary much between them because this would mean many ajax request to the server, slow load times for the pages and losing the AJAX responsiveness advantage . The caching strategy is more difficult to do, because:
data cannot be easily cached for all the blocks necessary in one page; blocks can have interdependencies which makes cache harder, and cache expiration, simultaneous for all dependent blocks, a problem to handle;

The framework should be adapted to make the many AJAX requests lighter from load point of view; otherwise, a first loading a a new page from a massively AJAX site, would produce a load significantly higher than a classical webpage; the business logic has to be divided in 2 places: on the server and in the client browser in Javascript.

Object Relational Mapping (ORM) An ORM is a framework that allows to avoid the mismatch, the difference in how they work) between the Relational Model and the Object Model, which are both present in most web applications . The SIP project uses an ORM framework which is Entity Data Model (EDM) . In PHP, a good ORM framework is Doctrine (http://www.doctrineproject.org/). Doctrine 2 is divided into three main packages.
Common DBAL (includes Common) ORM (includes DBAL+Common)

The Doctrine code base is split in to these packages for a few reasons and they are to... ...make things more maintainable and decoupled ...allow you to use the code in Doctrine Common without the ORM or DBAL ...allow you to use the DBAL without the ORM

Doctrine framework
The Common Package

The Common package contains highly reusable components that have no dependencies beyond the package itself (and PHP, of course).
The DBAL Package

The DBAL package contains an enhanced database abstraction layer on top of. The purpose of this layer is to provide a single API that bridges most of the differences between the different RDBMS vendors.

The ORM Package


The ORM package contains the object-relational mapping toolkit that provides transparent relational persistence for plain PHP objects. Doctrine uses the Data Mapper pattern at the heart of this project, aiming for a complete separation of the domain/business logic from the persistence in a relational database management system. The benefit of Doctrine for the programmer is the ability to focus solely on the object-oriented business logic and worry about persistence only as a secondary task. This doesn t mean persistence is not important to Doctrine 2, however there are considerable benefits for object-oriented programming if persistence and entities are kept perfectly separated.

Doctrine supports Inheritance Mapping . An mapped superclass is an abstract or concrete class that provides persistent entity state and mapping information for its subclasses, but which is not itself an entity. Typically, the purpose of such a mapped superclass is to define state and mapping information that is common to multiple entity classes. Doctrine introduces DQL which is best described as object-query-language and is a dialect of OQL and similar to HQL or JPQL. It does not know the concept of columns and tables, but only those of Entity-Class and property. Using Metadata it allows for very short distinctive and powerful queries.

Example:
The following query in standard SQL SELECT sp.FirstName, sp.LastName, sp.HireDate FROM SalesPerson sp INNER JOIN Employee e ON sp.SalesPersonID = e.EmployeeID INNER JOIN Contact c ON e.EmployeeID = c.ContactID WHERE e.SalariedFlag = 1 AND e.HireDate >= '2008-01-01' could be written in DQL like this (considering all the entity classes and Metadata is defined), if we had a class inheritance and inheritance mapping: SalesPerson extends Employee and Employee extends Contact SELECT sp.FirstName, sp.LastName, sp.HireDate FROM Contacts\Employees\SalesPerson AS sp WHERE e.HireDate >= '2008-01-01'

Debugging An AJAX application is inherently more difficult to debug, because: it has business logic in 2 separate places: in the server and in the client browser; the very flexible and no private members javascript nature; However, to debug an Ajax application in PHP one ca use: simple debug logs messages, directly to output or to log files; step by step debugging in PHP, by using the Xdebug extension; Firebug to debug in the browser Javascript and Ajax calls .

Deployment The deployment of a PHP web project is generally a simple thing. It includes more steps some of which must be done only first time, and some of which can be skipped depending on the project:
Deployment related tasks
One time only deployment tasks

install operating system, for example Linux Ubuntu Server or Redhat; install Apache, Php and Mysql;
this can be done easily in linux using packages which can be installed using just one command for each program;

install the necessary extensions for PHP, depending on the project;


this can be done easily in linux using packages which can be installed using just one command for each program;

configure virtual host in Apache

Regular deployments tasks

put the code and resources files on the server; this can be done in more ways;
using FTP or SFTP; this is not recommended because of the dificulty to track changes and the exact version present on production; using SVN updates; this is the recommended version because:
easy to track changes; ability to know what version is in production; ability to revert to a previous code version easily;

run database updates; this can be done in more ways:


manually in the database; not recommended, because it is hard to know which updates were run and which not using an automated script; we have such an automated sql deployment script which works quite well and allows:
to view the sql queries which need to be run; to log all the updates done to the db to automatilcally run only the not run updates; to update the log separately from running the queries, in case of unsinchronised log, due to database dumps moving;

copy config files, separate for each application instance;


for the RTLINFO older version application we were using a PHP script which was doing this in an easy way;

Tools and features which make PHP development easier


XDEBUG

Xdebug is a PHP extension which allows: more useful error messages; step by step debugging, together with Eclipse IDE; full stack trace log in non error conditions, which combined with a few tools to view those logs in a graphical manner (for Linux and Windows), make it useful for performance tuning;

Phing
A PHP project build system or build tool based on Apache Ant. An easy-to-use and highly flexible build framework.
Simple XML buildfiles Rich set of provided tasks Easily extendable via PHP classes Platform-independent: works on UNIX, Windows, MacOSX No required external dependencies Built & optimized for ZendEngine2/PHP5

JSON handling

To work with JSON in PHP is very easy. To convert to from PHP object or array to a JSON object or array you need just 2 functions: json_encode and json_decode .

Security in PHP web applications Security in PHP web applications does not really depend on the programming language. It is a matter of business logic to write secure applications.
Authentication

Authentication means requesting and verifying the identity of the current user. Authentication is done usually using a simple form;
the user submits the account details to the server the server check a persistent storage to see if the account is valid and logs in the user; the fact that the user is logged in is kept in the Session; the session is a common feature of web applications; it is a storage of small amount of data, usually available automatically to any instance of web page for any user, logged in or not. The correspondence between a session on the server and a user currently browsing the site is done by using a HTTP cookie which contains the session identifier for each user, in his own browser.

Authorization

Authorization means to check if a subject has the right to do a certain action on a certain object. This can be done in more ways:
Using access lists Using custom code generally custom code is the preferred way for very custom requests of the business logic, and a small number of operations of objects, in which case the overhead of using ACLs would be to much;

Encrypted connections, SSL

Web applications using PHP can use encrypted communication between the browser and the server. This is done by using Public Key encryption and Certificates. Protocols: SSL, TLS The Apache server supports SSL using OPENSSL. In general only some parts of the application may require encrypted communications, like
logging in; online payments using credit card and other payment information.

Example of the flow a simple request and response The code examples will be non fully working ones, since we do not have ready made project where to copy them from and the lack of time to implement an example; Let s say we need in our application a way to present the cities using some criteria. This will be a method of a REST Webservice; in the PHP applications REST webservices are much more common than SOAP webservices; also they are much more easier to use . this method will receive parameters using simple HTTP GET and return the information as a JSON string . Let us suppose that the application is written in CakePHP . The AJAX request from the browser would be something like http://example.com/regions/getCities/parentRegionId:10/minPop ulation:5000 Obs: errors are not treated for brevity and clarity;

CONTROLLER

part 1

In a controller class called regions we will have a public method called getCities public function getCities($parentRegionId = null, $minPopulation = null) { }

this would contain among others


The call to the model to get the cities

$cities = $this->City->getCities($parentRegionId, $minPopulation); The City property member is automatically instantiated by CakePhp according to a list of models we need for each controller.

MODEL In the model class City we would have the method:


public function getCities($parentRegionId, $minPopulation) { return $this->find( 'all', array( 'fields' => array('name , 'population', 'surface_area', 'lat', 'long ), 'conditions' => array( 'City.parent_region_id' => $parentRegionId, 'City.population >= ' . $minPopulation, ), 'order' => array('City.name ASC'), 'recursive' => 0, 'contain' => array('Country') ) ); } This method would return all the cities from the region with id equal to $parentRegionId and which have a minimum population of $minPopulation; It will also return information about the country the city belongs to.

CONTROLLER part 2 In the controller we will also have the encoding of the cities to json string:
$citiesJson = json_encode($cities); $this->set( citiesJson , $ citiesJson);

This will encode the cities informtaion into a JSON string and make it available to the view.

VIEW The view will be a file like cities_list.ctp; it will display a grid with the cities; in the example below the grid contains other information, but it is similar. We will use a javascript library called ExtJs very useful to draw controls, which are very flexible; see mode about it on: http://www.sencha.com/products/extjs/

View template content <script type="text/javascript" src="array-grid.js"></script> <div id="grid-example"></div> This is what the server sends to the client as reponse to the request to view a block with AJAX. The rest of the view logic is inside the javascript file arraygrid.js

View output

You might also like