Quantcast
Channel: LampJunkie.com - Everything related to Linux, PHP, MySQL, Apache, AJAX, Symfony and more
Viewing all articles
Browse latest Browse all 10

Introducing Hitch (the JAXB Equivalent for PHP)

$
0
0

Let’s face it… parsing XML is boring and usually a pain in the butt, especially when you need to translate it to a hierarchy of PHP objects.

This is why I have decided to create Hitch which is based on Java’s JAXB annotations. Hitch is build on top of doctrine-common which provides easy to use annotation parsing from PHP docblocks.

Let’s say you have the following XML document structure:

  1.  
  2. <catalog>
  3.   <products>
  4.     <product id="1" name="Product 1">
  5.       <description>Product Description</description>
  6.       <price>$100</price>
  7.     </product>
  8.   </products>
  9. </catalog>

You would map this to a Calalog class like this:

  1.  
  2. /**
  3.   * @xml:XmlObject
  4.   */
  5. class Catalog
  6. {
  7.   /**
  8.    * @xml:XmlList(name="product", wrapper="products", type="Hitch\Demo\Entity\Product")
  9.    */
  10.   protected $products;
  11.  
  12.   // ... getters/setters ...
  13. }
  14.  
  15. /**
  16.  * @xml:XmlObject
  17.  */
  18. class Product
  19. {
  20.   /**
  21.     * @xml:XmlAttribute
  22.     */
  23.   protected $id;
  24.  
  25.   /**
  26.    * @xml:XmlAttribute
  27.    */
  28.   protected $name;
  29.  
  30.   /**
  31.    * @xml:XmlElement
  32.    */
  33.   protected $description;
  34.  
  35.   /**
  36.    * @xml:XmlElement
  37.    */
  38.   protected $price;
  39.  
  40.   // ... getters/setters ...
  41.  
  42. }

Now you can simply parse the XML to an object graph like this:

  1.  
  2. // create our new HitchManager
  3. $hitch = new HitchManager();  
  4. $hitch->setClassMetaDataFactory(new ClassMetadataFactory(
  5.                                         new AnnotationLoader(new AnnotationReader()),
  6.                                         new ArrayCache()));
  7.  
  8. // get xml from somewhere
  9. $xml = file_get_contents('myxml.xml');
  10.  
  11. // unmarshall xml to a Catalog object
  12. $catalog = $hitch->unmarshall($xml, "My\Namespace\Catalog");
  13.  
  14. // do something with the object
  15. foreach($catalog->getProducts() as $product){
  16.   echo $product->getName();
  17. }

Hitch contains a full demo showing all the possible mappings, so check out the whole project here:

https://github.com/lampjunkie/xml-hitch


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles





Latest Images