jwallace.us

tech, tunes, and other stuff

PHP Namespaces

Much like directories in a file system, namespaces are a way to group items in an orderly manner.  In this way they are used to avoid collisions.  In addition, namespaces can be used to shorten long names in order to increase a code’s readability.  For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
   namespace my\own\namespace2;
   use my\own\namespace2 as n2;

   function myfunction ($a) {
      echo "this is my function $a\n";
   }

   \my\own\namespace2\myfunction(1);
   n2\myfunction(2);

   # you need the \ in front of Exception to
   # access the global (built in) class
   $a = new \Exception();
?>

Will print out:

this is my function 1
this is my function 2

Note that without the starting slash \ in the first call to myfunction() would have failed because PHP would have considered the function to be undefined.

Namespaces in XML

Namespaces can be used in XML documents with the same purposes in mind:  to eliminate naming collisions and to shorten names for readability.  For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0"?>
   <fleet xmlns="http://cars.org/fleet"
      xmlns:mk="http://cars.org/make"
      xmlns:mo="http://cars.org/model"
      xmlns:vn="http://cars.org/vin">
      <car vn:id="8888">
         <mk:x>ford</mk:x>
         <mo:x>taurus</mo:x>
      </car>
      <car vn:id="5555">
         <mk:x>honda</mk:x>
         <mo:x>civic</mo:x>
      </car>
   </fleet>

SimpleXML and Namespaces

SimpleXML knows how to use namespaces.  For example, given the following code:

1
2
3
4
5
6
7
<?php
   $xml = new SimpleXMLElement ('cars.xml', NULL, true);
   $namespaces = $xml->getDocNamespaces();
   foreach ($namespaces as $key => $value) {
      echo "$key => $value\n";
   }
?>

Prints the following output:

=> http://cars.org/fleet
mk => http://cars.org/make
mo => http://cars.org/model
vn => http://cars.org/vin

DOM and Namespaces

Alone, DOM’s namespace functionality is limited.  Its real power comes into its own when used with XPath.  For example:

1
2
3
4
5
6
7
8
9
10
11
<?php
   $dom = new DomDocument();
   $dom->load('cars.xml');
   $xpath = new DOMXPath ($dom);
   $xpath->registerNamespace('mycars', $dom->documentElement->baseURI);
   echo $dom->documentElement->baseURI . "\n";
   $context = $dom->documentElement;
   foreach( $xpath->query('namespace::*', $context) as $node ) {
      echo $node->nodeValue, "\n";
   }
?>

Prints the following output:

/Users/john/src/php/cars.xml

http://www.w3.org/XML/1998/namespace


http://cars.org/vin


http://cars.org/model


http://cars.org/make


http://cars.org/fleet