Categories
PHP Programming

PHP instanceof to determine what kind of object we are dealing with

Example:

class ShopProductWriter {
    public function write( $shopProduct ) {
        if ( ! ( $shopProduct instanceof CdProduct )  &&
             ! ( $shopProduct instanceof BookProduct ) ) {
            die( "wrong type supplied" );
        }
         $str  = "{$shopProduct->title}: " .
                $shopProduct->getProducer() .
                " ({$shopProduct->price})n";
        print $str;
    }
}
Categories
PHP Programming

PHP Object type hinting

Introduced with PHP 5.1, it basically looks like this:

function setWriter( ObjectWriter $objwriter=null ) {
    $this->writer = $objwriter;
}

Where the $objwriter has to be either null or of the type ObjectWriter, or it will produce a runtime error. The =null part is optional.

Advantages:

Forces to pass the right kind of object to a method, saving us the trouble of testing before passing. It also makes the code clearer regarding method signature.

Disadvantage:

Since it only runs at runtime, if it is buried within conditional statements that only run on xmas, you may get a call on your holiday to get your budd to the office and fix it.

Not that you can’t use type hinting with primitives.

Categories
Contracting

Contracting best practices

  1. Backup the client’s data before you touch their database or any other component that can be backed up.
  2. Save a working copy of their current code as well so you can easyily revert back in case of problems.
Categories
JavaScript

Javascript Performance and best practices

The following tips can be used to improve sluggish javascript code:

  • Avoid using the eval() function.
  • Avoid the with construction.
  • Minimize repetitive expression evaluation.
  • Use simulated hash tables for lookups in large arrays of objects.
  • Avoid excessive string concatenation.
  • Investigate download performance.
  • Avoid multiple document.write() method calls.
  • Use global namespace variables to encapsulate your variables, to avoid colisions with other JavaScripts
  • Recursion, as elegant as it is, is heavy in js, and it takes longer to execute than regular for or while loops. It can produce stack overflows. Use it lightly.

Source (for more details on why): http://www.devarticles.com/c/a/JavaScript/More-on-Variables-Functions-and-Flow-Control/3/

To check your JavaScript code for best practices you can use jlint:

http://www.jslint.com/

More lessons learned in the trenches:

  • When you user JS to switch classes, the DOM has to redraw and recalculate all the CSS associated with that and the children tags. Try to do it lightly, or try to stick to switching styles as inline inserts, Jquery animations style
  • When you need to use setTimeOut, use requestAnimationFrame instead. In a nutshell, it is a way for browsers to give you access to the frames when they refresh stuff, so your updates to the UI will be coordinated with other animations and things going on the UI. Here is an easy to digest example of this usage (or more complicated at the original source https://gist.github.com/1579671 ):
 window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       || 
              window.webkitRequestAnimationFrame || 
              window.mozRequestAnimationFrame    || 
              window.oRequestAnimationFrame      || 
              window.msRequestAnimationFrame     || 
              function( callback ){
                window.setTimeout(callback, 1000 / 60);
              };
    })();
Categories
JavaScript

JavaScript error messages, error handling and try catch

To avoid errors being presented to the end user:

function doNothing() {return true;}
 window.onerror = doNothing;

But of course, the best way to handle this (after IE 5), is by using try{ } catch { } structures:

<script type=”text/javascript” language=”JavaScript1.5″>
  function myFunc() {
      try {
          // statement(s) that could throw an error if various conditions aren’t right
      }
      catch(e) {
          // statements that handle the exception (error object passed to e variable)
      }
  }
  </script>

Note how the script has to be set as javascript1.5 to avoid old browsers to run into problems with try catch.

The following table indicates what’s available from the “e” error object passed to the catch statement, and what browsers support it:

Property IE/Windows Mozilla Safari Opera Description      
description 5 n/a n/a n/a Plain-language description of error  
fileName n/a all n/a n/a URI of the file containing the script throwing the error 
lineNumber n/a all n/a n/a Source code line number of error  
message 5.5 all all 7 Plain-language description of error (ECMA)  
name 5.5 all all 7 Error type (ECMA)      
number 5 n/a n/a n/a Microsoft proprietary error number  
stack n/a 1.0.1 n/a n/a Multi-line string of function references leading to error
 From inside a try statement, you can throw errors yourself:
throw err;
Categories
Programming

Array sorting

First an explanation about big O notation. If you have f(x) = 6x4 − 2x3 + 5. Then to simplify the equation, as x approaches infinity, the only number that seems to matter is x4 as all other parts of the equation become more and more insignificant as x grows.

This means we can say f(x) is almost equal to  x4 or f(x) = O(x4).

 In sorting, For typical sorting algorithms good behavior is mathcal{O}left( n log nright) and bad behavior is mathcal{O}left( n^2 right). The ideal is Ideal behavior for a sort is mathcal{O}left( n right), but since comparison is needed in programming algorithms, we have to settle for at least O(n log n).

 Popular sorting algoriths:

  • Bubble sort: Starts at the beginning of the data set, compares the first two elements and swaps (if neccesary) the lowest element first. Repeats the same comparison until the end of the list, and then starts again in element 2. Highly unefficient. A 100 elements array will need about 1ooo comparison tasks.  Bubble sort average case and worst case are both O(n²). Here’s an example:

    function myBubbleSort(arrayName,length) {
    for (var i=0; i<(length-1); i++){ for (var j=i+1; j
  • Insertion sort: Efficient in small lists, but expensive, because it creates a new array to accomodate all elements of the unsorted array there in order as the insertion happens.
  • Shell sort: one of the fastest algorithms to sort data, but very unefficient in large data sets. It arrange the data sequence in a two dimensional array, and then in the vertical columns of the array it uses intersion sort to the columns. The you decrease the number of columns and do it again.
  • Merge sort. Divides the data set into lists of two elements (1 and 2, 3 and 4, etc), sort the lists, and then create new lists of 4 with the resulting lists, sort them again and create lists of 8, etc, until all list is sorted. Scales well with large lists because its worse case scenario is O(n log n).
  • Heap sort. It puts the data set in a data structure called heap, which is a binary tree where the smallest (or largest) element is the root, and childen of each node are also smaller than their parent. When a node is removed, the heap updates itself again to reflect that rule.  Heaps run on O(n log n).
  •  Quicksort: Based on a mid number, partition the list and moves all elements lower than the number to one side of the list and the elements bigger than that number to the other part. Then recursively repeats the same algorithm until finish. One of the fastest sorting algorithms, but depends on choosing the right pivoting point as the median, if so we get O(n log n) performance, if not we may get closer to O(n²), yet we need to O(n) operation to determine the median, so that also adds up to the execution time.
Categories
Programming

MVC architecture

It is a design pattern that helps separate business logic from input and presentation, making it easier to maintain each one of those components independenly from each other.

Model: it is the representation of data according to the application’s function or domain. It includes data access but it is not exclusively the retrieval or records.

View: renders the model so it can interact with users. It is the UI. It can have several manifestations for a given Model.

Controller: receives input and coordinates actions between the Model and the View. In the case of web servers translates HTTP requests into calls to backend and ultimately HTML pages.

Categories
JavaScript

JQuery and Ajax

$('#headlines').load('todays_news.html'); // Loads the html page into the headlines DOM element

The limitation of the method above is that  the page loaded has to be from the same server / domain.

If you want to load only an specific part of the requested page, you can access only that part by id (say id is ‘news’):

$('#headlines').load('todays_news.html #news');

In JQuery, the way to specify GET and POST commands is as follows:

$.get(url, data, callback);  // or  $.get(‘rateMovie.php’,’rating=5′);

$.post(url, data, callback); // or $.post('rateMovie.php','rating=5&user=Bob');

Just remember that when preparing the data,  you have to url encode some of the arguments:

encodeURIComponent(‘Mac & Cheese’);

If you want to include all the elements of a form at once when you send your request, you can use the serialize() function to do so (say your form id is #login):

var formData = $('#login').serialize();
$.get('login.php',formData,loginResults);

This is a typical callback function:

function processResponse(data, status) {
     var newHTML;
     if (status==’success’) {
       newHTML = ‘<h2>Your vote is counted</h2>’;
       newHTML += ‘<p>The average rating for this movie is ‘;
       newHTML += data + ‘.</p>’;
     } else {
       newHTML='<h2>There has been an error.</h2>’;
       newHTML+='<p>Please try again later.</p>’;
     }
     $(‘#message’).html(newHTML);
   }

The callback function could also be specified as an anonymous function:

.get('file.php', data, function(data,status) {
   // callback function programming goes here
});

If you received XML content back from the server, you can parse it this way:

$.get(‘xml.php’,’id=234′,processXML);
function processXML(data) {
  var messageContent=$(data).find(‘content’).text();
}

In this example, the actual XML received may look like:

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<message id=”234″>
  <from>Bob</from>
  <to>Janette</to>
  <subject>Hi Janette</subject>
  <content>Janette, let’s grab lunch today.</content>
</message>

In order to convert the response to a JSON object usable by JavaScript directly, you can use the following:

$.getJSON(‘contacts.php’,’contact=123′,processContacts); // same as $.get(), but the ‘data’ variable is a JSON object instead of text

If you need to loop through a JSON object, you can use the JQuery $.each() function.

Say that you have the following object coming back from the server:

var data = {
  contact1: {
    firstName: 'Frank',
    lastName: 'Smith',
    phone: '503-555-1212'
  },
  contact2: {
    firstName: 'Peggy',
    lastName: 'Jones',
    phone: '415-555-5235'
  }
};

The following callback function can be used to parse it:

   $.getJSON(‘contacts.php’,’limit=2′,processContacts);
   function processContacts(data) {
     // create variable with empty string
     var infoHTML=”;

     //loop through each object in the JSON data
     $.each(data,function(contact, contactInfo) {
         infoHTML+='<p>Contact: ‘ + contactInfo.firstName;
         infoHTML+=’ ‘ + contactInfo.lastName + ‘<br>’;
         infoHTML+=’Phone: ‘ + contactInfo.phone + ‘</p>’;
     }); // end of each()

     // add finished HTML to page
     $(‘#info’).html(infoHTML);
   }

In that case, the argument ‘contact’ will point to ‘contact1’ and ‘contact2’, and the contactInfo to the information on each of those sub-objects

Categories
JavaScript

Ajax

XMLHttpRequest object: is a browser object that allows you to communicate to the server. To create one of these objects you use the following JavaScript code:

var newXHR = new XMLHttpRequest(); // Doesn’t work in IE 6 though

In order to send a GET request using the object above, you do something like:

newXHR.open(‘GET’, ‘shop.php?productID=34’);

To indicate the callback function that will process the request received back from the server:

newXHR.onreadystatechange = myCallbackFunction;

Up to this point, everything has been setup, now to send the data to the server you use:

newXHR.send(null);

If you want to send additional parameters, instead of null you specify:

newXHR.send('q=javascript');

The XHR object receives up to three pieces of information back from the server:

  • status: like 404, 500, 200, etc
  • responseText property: it is part of the XHR object, and stores the server response, could be HTML, plain text, or a JSON object
  • responseXML property: also part of the XHR object. Loaded if the server responds with XML
Categories
JavaScript

Forms manipulation in JQuery

var fieldValue = $(‘#user’).val(); // Get the value of the form field with id ‘user’

var fieldValue = $(‘#user’).val(‘Value to set’); // Set the value of the form field with id ‘user’

var fields = document.getElementsByTagName(‘input’); // Select all form fields

$(‘:input’).attr(‘disabled’,true); // Disable input fields

To select all form fields of a given type in JQuery:

$(‘:input’) Selects all input, textarea, select, and button elements. In other words, it selects all form elements.
$(‘:text’) Selects all text fields.
$(‘:password’) Selects all password fields.
$(‘:radio’) Selects all radio buttons.
$(‘:checkbox’) Selects all checkboxes.
$(‘:submit’) Selects all submit buttons.
$(‘:image’) Selects all image buttons.
$(‘:reset’) Selects all reset buttons.
$(‘:button’) Selects all fields with type button.
$(‘:file’) Selects all file fields (used for uploading a file).
$(‘:hidden’) Selects all hidden fields.

You can combine form selectors as follows: $(‘#signup :text’) // Select ‘signup’ element but only text input fields from those selected

$(‘:checked’) Select all checkboxes that have been checked

if ($('#news').attr('checked')) {
  // the box is checked
} else {
  // the box is not checked
}
var selectedState=$('#state :selected').val(); // Gets the value of the selected fields of 'states'
Example of submit event:
$(document).ready(function() {
      $('#signup').submit(function() {
         if ($('#username').val() == '') {
            alert('Please supply a name in the Name field.');
            return false;
         }
      }); // end submit()
}); // end ready()
Example of focus event:
$('#username').focus(function() {
     var field = $(this);
     if (field.val()==field.attr('defaultValue')) {
       field.val('');
     }});
Example of change event:
$('#country').change(function() {
  if ($(this).val()=='Please choose a country') {
    alert('Please select a country from this menu.');
  }
}