Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5993835
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T23:43:55+00:00 2026-05-22T23:43:55+00:00

I’m busy parsing xml documents (google docs api) and putting individual documents into objects.

  • 0

I’m busy parsing xml documents (google docs api) and putting individual documents into objects.

There are different types of documents (documents, spreadsheets, presentations). Most information about these documents is the same, but some is different.

The idea was to create a base document class which holds all the shared information, while using subclasses for each specific document type.

The problem is creating the right classes for the different types. There are two ways to differentiate the type of the document. Each entry has a category element where I can find the type. Another method that will be used is by the resourceId, in the form of type:id.

The most naive option will be to create an if-statement (or switch-statement) checking the type of the entry, and create the corresponding object for it. But that would require to edit the code if a new type would be added.

Now i’m not really sure if there is another way to solve this, so that’s the reason I’m asking it here. I could encapsulate the creation of the right type of object in a factory method, so the amount of change needed is minimal.

Right now, I have something like this:

public static function factory(SimpleXMLElement $element)
{
    $element->registerXPathNamespace("d", "http://www.w3.org/2005/Atom");
    $category = $element->xpath("d:category[@scheme='http://schemas.google.com/g/2005#kind']");

    if($category[0]['label'] == "spreadsheet")
    {
        return new Model_Google_Spreadsheet($element);
    }
    else
    {
        return new Model_Google_Base($element);
    }
}

So my question is, is there another method I’m not seeing to handle this situation?

Edit:
Added example code

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T23:43:56+00:00Added an answer on May 22, 2026 at 11:43 pm

    Updated answer with your code example

    Here is your new factory :

    public static function factory(SimpleXMLElement $element)
    {
        $element->registerXPathNamespace("d", "http://www.w3.org/2005/Atom");
        $category = $element->xpath("d:category[@scheme='http://schemas.google.com/g/2005#kind']");
        $className = 'Model_Google_ '.$category[0]['label'];
        if (class_exists($className)){
           return new $className($element);
        } else {
            throw new Exception('Cannot handle '.$category[0]['label']);
        }
    }
    

    I’m not sure that I got exactly your point… To rephrase the question, I understood “how can I create the right object without hardcoding the selection in my client code”

    With autoload

    So let’s start with the base client code

    class BaseFactory
    {
        public function createForType($pInformations)
        {
           switch ($pInformations['TypeOrWhatsoEver']) {
               case 'Type1': return $this->_createType1($pInformations);
               case 'Type2': return $this->_createType2($pInformations);
               default : throw new Exception('Cannot handle this !');
           }
        }
    }
    

    Now, let’s see if we can change this to avoid the if / switch statments (not always necessary, but can be)

    We’re here gonna use PHP Autoload capabilities.

    First, consider the autoload is in place, here is our new Factory

    class BaseFactory
    {
        public function createForType($pInformations)
        {
           $handlerClassName = 'GoogleDocHandler'.$pInformations['TypeOrWhatsoEver'];
           if (class_exists($handlerClassName)){
               //class_exists will trigger the _autoload
               $handler = new $handlerClassName();
               if ($handler instanceof InterfaceForHandlers){
                   $handler->configure($pInformations);
                   return $handler;
               } else {
                   throw new Exception('Handlers should implements InterfaceForHandlers');
               }
           }  else {
               throw new Exception('No Handlers for '.$pInformations['TypeOrWhatsoEver']);
           }
       }
    }
    

    Now we have to add the autoload capability

    class BaseFactory
    {
        public static function autoload($className)
        {
            $path = self::BASEPATH.
                    $className.'.php'; 
    
            if (file_exists($path){
                include($path); 
            }
        }
    }
    

    And you just have to register your autoloader like

    spl_autoload_register(array('BaseFactory', 'autoload'));
    

    Now, everytime you’ll have to write a new handler for Types, it will be automatically added.

    With chain of responsability

    You may wan’t to write something more “dynamic” in your factory, with a subclass that handles more than one Type.

    eg

    class BaseClass
    {
        public function handles($type);
    }
    class TypeAClass extends BaseClass
    {
        public function handles($type){
            return $type === 'Type1';
        }
    }
    //....
    

    In the BaseFactory code, you could load all your handlers and do something like

    class BaseFactory
    { 
        public function create($pInformations)
        {
            $directories = new \RegexIterator(
                new \RecursiveIteratorIterator(
                    new \RecursiveDirectoryIterator(self::BasePath)
                ), '/^.*\.php$/i'
            );
    
            foreach ($directories as $file){
                require_once($fileName->getPathName());
                $handler = $this->_createHandler($file);//gets the classname and create it
                if ($handler->handles($pInformations['type'])){
                    return $handler;
                }
            }
            throw new Exception('No Handlers for '.$pInformations['TypeOrWhatsoEver']);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm making a simple page using Google Maps API 3. My first. One marker
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I'm parsing an XML file, the creators of it stuck in a bunch social
I am trying to loop through a bunch of documents I have to put
this is what i have right now Drawing an RSS feed into the php,
I have a French site that I want to parse, but am running into
I am currently running into a problem where an element is coming back from
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.