Wednesday, 30 October 2013

Javascript snippet to HTML encode foreign characters

This Javascript snippet is useful for converting characters in a language like Arabic to HTML Encoding for putting on web pages.

var a = "السلام عليكم"; //Arabic for Peace Be Upon You (Hello)
var h = a.replace(/(.)/g, function($1){
   return ($1 == " ") ? $1 : "&#" + $1.charCodeAt() + ";";
});

The variable h now holds السلام عليكم
a.replace(/(.)/g, function($1){
  if ($1 == " ")
    return " ";
  else
    return "&#" + $1.charCodeAt() + ";";
})
"السلام عليكم"
"السلام عليكم"
"السلام عليكم"
"السلام عليكم"
console.log("السلام عليكم".replace(/(.)/g, function($1){
  if ($1 == " ")
    return " ";
  else
    return "&#" + $1.charCodeAt() + ";";
}));

Monday, 28 October 2013

Drupal 7: Referencing Views from inside Panel Pages

Example Scenario: I have created a Panel Page (e.g. Cars) and I want to display a View list of Parts associated with any Car loaded through that Panel page. Each Car node contains a reference (Entity Reference) field (field_parts_ref) to all the parts associated with it.

First, create your View, choose which fields to display, and add a context - select Content: Nid of the Car and on the next page you select Provide default value from the drop down list, select PHP Code from the drop down list, and add the following code:

//get node id of parent passed from the panel and load the node into memory
$nid = $argument->view->args[1];
$node = node_load($nid);
//read the field which has references to the node id's of the child items and add them to $refs
$refs = array();
foreach((array)$node->field_parts_ref['und'] as $t){
     if ( ! empty($t['target_id']))
         $refs[] = $t['target_id'];
}
//return the array of child item references to the view in a comma-seperated list so it displays only those items
return implode(',', $refs);


Now scroll to the bottom and expand More and check Allow multiple values. 
Now you can create your Panel Page. Add your view as a content, but when it shows the interface to configure the View you need to select the Cars ID field in the Node Being Viewed section of the drop down, and make sure the Send arguments check box is checked.

That's it. It was a little tricky to figure this stuff out but I got there in the end, so I hope this gives some clue to anyone trying to get something working.

Tuesday, 1 October 2013

Things that annoy me about OOP in PHP

I've been doing quite a bit of "proper" OOP coding in PHP lately and made a note of common pitfalls I came across. This list is not a complete run-down of what's wrong with OOP PHP. To be honest, save for these pitfalls, proper coding of PHP is actually fun.

1. Having to import every single class you use manually

In Java you say import java.util.*; where the asterisk means everything in that module is available for use in this namespace. Easy to see what's going on and a real timesaver. While using standard PSR-0 autoloading conventions, PHP doesn't have library importing so for every class you use you have to import it or give the full classpath everytime you need to use it. You will often see PHP code with long lists of 'use' statements at the beginning of the file like so:

use mylib\app\util\LoremIpsumGenerator,
    mylib\app\config\ConfigLoader,
    anotherlib\tastyphp\orm\TastyORM,
    randomlib\randomhouse\RealRandom;

2. SPL classes have to be referenced with a preceding backslash

Instead of the PHP engine doing a simple search to find a class, first in the namespace of the file, then in the Standard PHP Library namespace, you have to delimit an SPL class with a backslash every time you use it. Why can't I just say "new Exception()" instead of "new \Exception()"? Why do I have to use a backslash everywhere I use an SPL class? It's totally unnecessary and becomes annoying to code and irritating to debug

/**
* Yes, yes, I know I should use instanceof
* but I'm showing another SPL class being used
* @throws \Exception
* @param \Exception|mylib\app\exceptions\MyBaseException
* $exception
*/
public function captureMyExceptionThrowPHPException(\Exception $exception)
{
    $rc = new \ReflectionClass($exception);
    if ($rc->isSubclassOf('mylib\app\exceptions\MyBaseException')) throw new \Exception('My Exception: ' . $exception->getMessage());
    else throw $exception;
}

3. Lack of object casting

Seriously, why can't I cast one type of object into another, even when the subject is a subclass of the object? I wish it was possible to do this: $e = (\Exception) new mylib\app\exceptions\MyBaseException('My exception'); That would save me a bit of typing and potential buggy code.

Java allows you to upcast an object, meaning a subclass can be easily converted into a parent class, but it is not possible to downcast a parent item into a subclass type. Ideally it should be able to do that but at least it is able to upcast. PHP can't cast anything except it's primitives and two complex types (int|string|float|bool|array|object).

4. Lack of proper documentation for SPL Classes on the PHP.net site

Common SPL Functions are well documented with community supplied code snippets for everything you can imagine so it's easy to copy and paste and you're done. PHP5 SPL Classes are poorly documented, which is a real shame because some crap and procedural code from the PHP4 days has now been re-implemented in a much cleaner, better and faster object oriented way. But you wouldn't know that because of the lack of information in the manual. More work needs to be put into this. More comments with usage examples are necessary. These are provided by the community so please contribute to the project with a comment or an example if you have anything helpful.