RSS

Yii Framework For PHP Developers.

0 Comments | This entry was posted on Apr 06 2011

I had been trying many different PHP frameworks looking for one that just made sense and met my most basic requirements of MVC, PHP5 only, form pre-population and validation, ORM/Active Record and scaffolding. I eventually found Yii and have used in it several personal projects. However I had not learnt enough to be comfortable using it in some agencies I work in because of the pace the work is done. If I find that Yii doesn’t do something important then I’d be in a little trouble.

Then late last year the first Yii publication was released, titled ‘Agile Web Application Development with Yii 1.1 and PHP5’ by Jeffrey Winesett. The book is incredibly easy to follow and a pleasure to read. Each chapter made me appreciate Yii more and more for its simplicity and the rapid development that can be achieved.

After using frameworks that use scaffolding I find it a pain to use others that don’t. Nothing is more satisfying than designing your database and then using scaffolding to automatically build the model, views and controller for each database table. As of Yii version 1.1.2, scaffolding is best done using the browser based Gii interface. Gii allows you to build the model, views and controller  with a few quick steps and then you are immediately able to create, read, update and delete records from the table. It’s that easy.

Yii is very modular in every area. It provides all the functionality that you expect, but if you don’t like the way Yii does something, simply create a module to replace it to do it you own way. The book describes methods of doing that for logging, authentication and caching.

What this book also taught me was something that I have neglected up until now, Test Driven Development (TDD). Yii has tightly integrated unit testing (PHPUnit) into the framework and the book clearly states step by step instructions on how to include TDD in your project.

The book contained very few errors. I found in the last two chapters that there were misprints that were easily noticeable, probably due to not proof reading through the end of the book.

I can’t recommend this framework and the book enough. Give it a try and you won’t be disappointed.

Basic MVC Web Site Developed In PHP

0 Comments | This entry was posted on Dec 13 2010

Last week a front-end developer friend emailed me asking if I had a simple MVC type website template that he could use to build basic static websites, similar to one that I developed for a job that we worked on together at an agency. The answer was not yet but I’ll make one.

Sometimes I work on small sites myself but always tend to build basic sites from scratch each time for such cases that don’t require an established PHP framework. However this time I thought I would use this as an excuse to build something that I can re-use and share with others.

I gave myself an hour to build something that would be easy for others to understand and use but also be clean and extensible. There is no functionality to allow user input, a database abstraction layer (or any database functionality) or other things commonly seen in frameworks. About the only dynamic code that non PHP developers could take advantage of is the active state for the navigation menu.

The would be MVC at its most basic:

Model:

I guess as there is no database in a static site so there is no reason for a real model to be included at this time.

View:

The views can be found and added in the /views folder. The views are really just the content for a particular page and does not include the page layout. The layout (or templates as most CMSs call them) exist in the /templates directory. The idea is to separate page content from page layout. The layout file will load the content file via an include.

Controller:

The controller is very basic and currently is just used to load the layout which in turn loads the content. This main controller file is where most functionality should be added.

Conclusion:

The idea is very basic but I hope people can make use of it. I can see that new features will be added as people make requests. In return I wouldn’t mind if someone changed the default style sheet to make it more appealing and send it back to me.

The website template can be downloaded from GitHub at: https://github.com/doublehops/Basic-MVC-site

The website template ended up taking two hours to complete but my friend has been using it and is happy with it.

OSDC 2010

0 Comments | This entry was posted on Nov 29 2010

This week I attended the Open Source Developers Conference in Melbourne. OSDC is a three day event that is aimed at sharing skills and thoughts on software development using open source technologies and is attended by many developers passionate about open source software. This year I believe there were about 150 attendees from all around Australia and around 60 talks in total.

The talks covered everything from best practices in version control, Perl 6, PHP frameworks and CMSs, mobile application development and much more.

It was great to see what others are doing with and getting out of open source software. I was most amazed by Ben Martin’s talk about his project called Libferris. Libferris is a virtual file system which can mount vastly different things that can then be accessed from the shell. The types of things that can be mounted are LDAP, Evolution, images, Flicker, Youtube, PostgreSQL, RDP documents, the DOM in Firefox and MP3 files. This allows the extraction of data available to the shell or custom applications.

Another highlight was the closing keynote by Damian Conroy. This was a talk that lasted an hour and was exhausting to listen to as it was complex and fast, yet extremely compelling. Damian effectively used the general theory of relativity, quantum mechanics and perl to find prime numbers. The idea and implementation is completely amazing and I suggest everyone watches the video to see for yourself (shown at the bottom of this post.

All in all everyone was very impressed with the event and took a lot away from it. Sharing a beer at the end of each day was a great way to meet other like minded people and discuss what we learnt throughout the day. I am already looking forward to next years event which will be held in Canberra.

Damien Conway’s closing keynote speech – Temporally Quaquaversal Virtual Nanomachine Programming In Multiple Topologically…

Web Development Warehouse In Melbourne

0 Comments | This entry was posted on Aug 27 2010

Last night I attended the opening of a new workplace created primarily for freelance web developers. It’s a warehouse in Brunswick East that has been converted to office space to cater for 15+ developers who would like to work away from home.

The rates are very reasonable and the work area is a very relaxed atmosphere with a table tennis table. I think it’s a great idea to have a common work area for like minded people who could also possibly help with a development issue you’re stuck on.

The person behind this idea is Shaun. Shaun is a PHP developer that works mostly with Drupal. He also intends to host workshops in web development technologies.

For more information visit the website webdevwarehouse.com.

WebSockets In HTML5

0 Comments | This entry was posted on Aug 18 2010

Over the weekend I participated in the GTUG (Google Technology User Group) campout hackathon. The focus of the event was to learn what new things HTML5 introduces to the web and to build something using this new technology.

Along with new HTML elements such as <nav>, <footer>, <video> and <audio>, HTML5 includes a new set of APIs to drag-and-drop elements around the page, free-hand drawing on a canvas, storing data in the browser and geolocation. However my favourite new API is WebSockets.

WebSockets is a standard that intends to significantly simplify two way communication between the browser and the web server. The idea is that with a little Javascript you can open a connection to the server just by supplying the URL and port number of the service. Some server side service needs to be running on this port. For example, if the back-end technology is PHP then you would write a script (to be started from the shell) that would open a port using PHP sockets and then handle any data to be passed back and forth.

Of course the server side code will be as complicated as the application requires. The purpose of WebSockets is to have a standard that all web browsers can follow and to make the front-end development as simple as possible. To achieve this type of communication in today’s browsers requires some Javascript that polls the server for any new messages. With WebSockets, the server side service can send messages to the browsers without the browser polling at all.

The project we decided to build with WebSockets was to re-create the old game of Battleships. I thought this was an interesting idea as it breaks away from the traditional instant message module that would be a likely use of the new technology.

Although we put together some of the fundamentals of the comms I was unable to attend day two of the hackathon. I am anticipating Websockets to become available in all browsers so I can implement some ideas into a real use application.

Four Ways To Ease Facebook Application Development

0 Comments | This entry was posted on Mar 24 2010

For the last two months I have been developing a couple of Facebook applications for clients. Developing new apps for Facebook can be difficult and very time consuming in the fact that the applications need to be hosted on a publicly available server rather than in your standard dev environment. This is a pain for serveral reasons including the need to upload files each time a change is made and that you don’t want php or debugging messages being displayed.

Therefore you will want to send the debug and error messages elsewhere that you can easily watch. These tips are not complicated and I would hope that they are used by most developers at least some of the time for all projects.

1. Custom logger

Rather than printing debug messages to the screen I suggest that you send them to a custom log file which you can watch as new entries are added. Create a function similar to the following:

function logger( $msg )
{
   file_put_contents( 'log.txt', date( 'Y-m-d H:i:s' ) ." $msg\n", FILE_APPEND );
}

Once this function has been defined, you can easily send debugging messages to the log like:

logger( 'name is set: '. $name );

The new string and the set variable will be appended to the end of the log.

2. PHP error logs

When working in your own dev environment it is a must that you have errors sent directly into the browser. This way any warnings or fatal errors are immediately shown to you and you can fix and move on. This is undesirable (for several reasons) for a publicly available site so you need to log these to a file which you should also watch.

There are several methods to set PHP logging:

Enabling PHP error logging through Apache config

This in itself can be added in two places. The first option should only be available if you have root privileges to the server. Find the Apache virtualhost record (apache2ctl -S is handy for this) and set add the following:

php_value error_reporting 6143
php_flag log_errors on
php_value error_log /var/log/apache2/vhosts/yourdomain-php_error.log

The second option is to create a file named .htaccess in the web root directory and add the same options. This may require AllowOverride to be set to All in the virtual host record for this to work.

Enabling PHP error logging with PHP

The same options can be added directly into your scripts with like this:

ini_set( 'error_reporting', 6143 );
ini_set( 'log_errors', 'on' );
ini_set( 'error_log', '/var/log/apache2/vhosts/yourdomain-php_error.log' );

If you plan to develop for a long period it would be best to set the log file to go into the /tmp directory so it doesn’t cause hard disk issues on your server.

3. Apache logs

Apache logs are also very useful in developing Facebook applications. By watching these files you can see when and what Facebook is downloading from your server. I found this extremely useful when making Ajax calls to the server to see what $_GET variables were being sent.

These log files can usually be found somewhere in /var/log/apache2 but it may be easier again to check with apache2ctl -S to see exactly where the log is being saved.

Watching the logs

The best way to watch these log files is to SSH into the server and follow the logs with the tail command with it’s -f follow parameter.

tail -f /var/log/apache2/vhosts/yourdomain-php_error.log

By following the file you don’t need to keep closing and re-opening the file to see new entries.

4. Rsync

The best tool to upload any files that hae been changed is to use the rysnc command. This tool will compare your local files with the remote ones and upload any changes found. This beats the hell out of using FTP. I usually create a script which I run with looks like this:

rsync -r --verbose ./public_html/* username@hostname:/var/www/yourdomain.com/public_html

This will continually prompt for a password but this can be overcome by setting ssh keys. Follow this tutorial on how to set-up ssh keys.

Conclusion

I hope this helps others develop and debug Facebook applications. If you have further hints or ideas, I would love to hear them.

Website Build With Flash/HTML Integration

0 Comments | This entry was posted on Dec 15 2009

Last week, we at Sputnik Agency pushed live the site we had been building for our parent company Kit Digital. What I like most about this website is that it required us to include dynamic Flash navigation that had little overhead and to have the flash headers and html update seamlessly without reloading the page.

Project platform

We decided to go with WordPress as the project required a good CMS that was easy for the client to use and was quick and easy to develop.

Flash navigation with little overhead

There are two main flash headers that include navigation. This navigation needed to be dynamic in the way that if new pages were created in WordPress, the flash navigation needed to include these also. Having the navigation work dynamically this way can create an undesirable overhead as generally this would require mulitple calls to the database.

I overcame this by creating WordPress plugins that used hooks to create XML files when pages were added, updated or removed. These XML files included hierarchical page information required by the navigation. Therefore when a page is loaded in the front-end, the Flash would just read the XML file rather than force PHP to make database query requests. This resulted in the pages loading faster and reducing server overhead.

One other benefit of using SWFAddress is that although page loading does not occur, you can still click back through the pages of content you have loaded. The browser will not behave this way with standard content replacement using AJAX.

Seamlessly update flash header and update content

The next task was to allow links (whether clicked from the Flash navigation or HTML navigation) to update the Flash navigation and HTML without reloading the page. This seemed like a very difficult task and something I had not seen before but we managed this using SWFAddress.

Using the SWFAddress Javascript library we could update the URL in the address bar which would trigger both the HTML and Flash to change their behaviour. Once the the change was caught I used jQuery to make a request to another custom WordPress plugin that would pull page content from the database and then update the HTML without needing to reload the page. Clicking on the Flash links did the same.

The end result is a very sleek and fast loading website where the content is completely CMS driven.

To see these pages in action, visit these links: VX Platform, Global.

Yii PHP Framework Presentation.

0 Comments | This entry was posted on Nov 19 2009

Each month someone from the PHP Melbourne user group will present a PHP framework to the rest of the group. The November meeting gave me an opportunity to present the Yii PHP framework and why I think it’s a great platform to build PHP projects from.

During the presentation I described the main qualities I like about the framework and demonstrated how quick and easy it is to begin a new project.

I recommend for anyone looking for a new php framework to give Yii a try. It’s a great framework that allows rapid application development. The best qualities I find in the framework include:

  • Componenet based
  • MVC
  • DOA/Active record
  • Scaffolding
  • Form validation/re-population
  • Theming
  • Authentication and role-based access control
  • Strict OOP (PHP5 only to make full use of PHP object functionality)
  • Great documentation
  • Active community
  • Example project

As with learning anything new there is always a learning curve. I suggest when starting out to try the Yii blog tutorial which takes you through installing a new project, building controllers and models from the database structure to extending Yii.

Quick Tutorial On Getting Started With SOAP In PHP.

2 Comments | This entry was posted on Jul 07 2009

Understanding what SOAP is and learning how to use it can be very confusing. There is much talk of SOAP on the Internet but finding an easy to understand tutorial on how to get started with it are hard to find. Therefore I have written this article for those new to SOAP.

This article assumes you have a good understanding of PHP and XML.

You use SOAP just the same way that you would any PHP class. However, in this case the class does not exist in the local applications file system, but at a remote site accessed over http.

A SOAP service is expressed as a URL. For this example I am using one I found with Google: terraservice.net/TerraService.asmx?WSDL. If we think of using a SOAP service as just another PHP class then the WSDL document is a list of all the available class methods and properties. If you open that URL in your browser you will see an XML document that lists these methods (also known as operations) and properties. If you load the page without the WSDL in the URL you will generally just get a list of the available methods: terraservice.net/TerraService.asmx. Clicking one of the operations will show the XML the service expects and the response a successful response will return. This is a typical example of how I would learn about how to use the SOAP service.

For this example I will use the GetPlaceFacts operation.This can be down by the following code:

$wsdl = 'http://terraservice.net/TerraService.asmx?WSDL';

$trace = true;
$exceptions = true;

$client = new SoapClient($wsdl, array('trace' => $trace, 'exceptions' => $exceptions));

The new object is created with the PHP5 function SoapClient(). When first testing a service it’s best to set trace and exceptions to true so that any errors can be discovered more easily. We should now have created an object of the service and are ready to send a request. For this example we will use the GetPlaceList operation. In this case we need to send data along with the request.

$xml_array['placeName'] = 'Pomona';
$xml_array['MaxItems'] = 3;
$xml_array['imagePresence'] = true;

The data here is supplied in an array rather than XML like the service expects. This is automatically converted by SoapClient.

To better understand where how to determine how these values should be entered into the array, we should check with the request format:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <GetPlaceList xmlns="http://terraserver-usa.com/terraserver/">
      <placeName>string</placeName>
      <MaxItems>int</MaxItems>
      <imagePresence>boolean</imagePresence>
    </GetPlaceList>
  </soap:Body>
</soap:Envelope>

You can see the first element after the body element is the operation that we want to use. Following is the data that we need to send. If there were nested elements then we would need to use nested arrays to match.

Now that we have set the data we can make our request which follows:

$wsdl = 'http://terraservice.net/TerraService.asmx?WSDL';

$trace = true;
$exceptions = false;

$xml_array['placeName'] = 'Pomona';
$xml_array['MaxItems'] = 3;
$xml_array['imagePresence'] = true;

try
{
   $client = new SoapClient($wsdl, array('trace' => $trace, 'exceptions' => $exceptions));
   $response = $client->GetPlaceList($xml_array);
}

catch (Exception $e)
{
   echo "Error!";
   echo $e -> getMessage ();
   echo 'Last response: '. $client->__getLastResponse();
}

var_dump($response);

I also wrap the request in a try/catch pair to prevent any fatal errors. Also, from habit I dump the response with var_dump() so I can inspect the response in detail.

Sometimes you will find that the response values are quite nested. In this case I can trim back the response like this:

$response = $response->GetPlaceListResult->PlaceFacts;

Then we can loop through the results:

foreach($response as $key => $value)
{
   echo '<br />Place: '. $key .'<br />';
   echo 'City: '. $value->Place->City .'<br />';
   echo 'State: '. $value->Place->State .'<br />';
   echo 'Country: '. $value->Place->Country .'<br />';
}

This is a basic example of how to get started using SOAP. There is much more to it. By looking closely at the WSDL you will find which data must be supplied. This is shown by an attribute of minOccurs where equal to at least one.

For a definitive guide on SOAP I suggest going to www.w3schools.com/soap/default.asp.

Setting Up Your Own Virtual Server With Slicehost

0 Comments | This entry was posted on Apr 16 2009

I have been working with Linux and web development for over seven years and in this time I have used several hosting companies as well as set-up some development servers at home in order to host and develop my websites. I had recently decided to take the plunge into getting my own virtual server account so I would have a live environment where I would have full control.

I chose Slicehost as my provider as I have used them in the past at work and found them to be reliable and the control panel and service to be exceptional. As with this type of virtual host you are given a completely new install with bare services running. This means that as a web server you need to manually install everything from Apache, MySQL and PHP manually. Also you will probably need to install a mail service.

The tough part for me was installing and configuring the mail. This is not something I do with my dev boxes at home. This was a bigger learning curve than I imagined but very rewarding. The greatest part with virtual hosts is that if you completely screw up, you can easily choose to rebuild your slice and start again from scratch.

Also through the slice manager you can easily configure DNS for any domains and subdomains hosted on the server.

Anyway, some of the best things I have learnt from the experience are:

  • Setting up a mail server with encryption and smtp authentication for imap accounts using mysql.
  • Setting up the firewall using iptables.
  • Learning how to login over ssh without passwords.
  • Setting up a Subversion server with SSL encryption.

It has been very satisfying to step away from the traditional hosting companies and have full control over my hosting. I recommend anyone else with Linux experience who is thinking of getting a virtual host with full root access to give it a go. There are some good ones about and the experience gained are better than I would have hoped.