4

我正忙于解析 xml 文档(google docs api)并将单个文档放入对象中。

有不同类型的文档(文档、电子表格、演示文稿)。关于这些文件的大部分信息是相同的,但有些是不同的。

这个想法是创建一个包含所有共享信息的基本文档类,同时为每个特定的文档类型使用子类。

问题是为不同类型创建正确的类。有两种方法可以区分文档的类型。每个条目都有一个类别元素,我可以在其中找到类型。将使用的另一种方法是由 resourceId 使用,格式为type:id.

最天真的选择是创建一个 if 语句(或 switch 语句)检查条目的类型,并为其创建相应的对象。但是,如果要添加新类型,则需要编辑代码。

现在我不确定是否有另一种方法来解决这个问题,所以这就是我在这里问它的原因。我可以将创建正确类型的对象封装在工厂方法中,因此所需的更改量很小。

现在,我有这样的事情:

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);
    }
}

所以我的问题是,是否有另一种我看不到的方法来处理这种情况?

编辑: 添加示例代码

4

3 回答 3

4

使用您的代码示例更新答案

这是你的新工厂:

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']);
    }
}

我不确定我是否完全理解您的意思......为了重新表述这个问题,我理解“如何在不硬编码客户端代码中的选择的情况下创建正确的对象”

带自动加载

所以让我们从基本客户端代码开始

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 !');
       }
    }
}

现在,让我们看看我们是否可以更改它以避免 if / switch 语句(并非总是必要的,但可以)

我们在这里将使用 PHP 自动加载功能。

首先,考虑自动加载已经到位,这是我们的新工厂

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']);
       }
   }
}

现在我们必须添加自动加载功能

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

        if (file_exists($path){
            include($path); 
        }
    }
}

你只需要注册你的自动加载器

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

现在,每次您必须为类型编写新的处理程序时,它都会自动添加。

责任链

您可能不想在您的工厂中编写更“动态”的东西,并使用处理多个类型的子类。

例如

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

在 BaseFactory 代码中,您可以加载所有处理程序并执行类似的操作

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']);
    }
}
于 2011-06-09T09:05:44.887 回答
1

我同意 Oktopus 的观点,一般有两种无需硬编码的方法;第一种是通过动态附加字符串来查找类名,并确保您的类正确命名,第二种方法是加载所有处理程序类,并使用表示它可以处理该类型的类。我会去第一个。使用您的示例代码,这将类似于以下内容:

<?php
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 = sprintf( 'Model_Google_%s', ucfirst( strtolower( (string) $category[0]['label'] ) ) );

    if( class_exists( $classname, true /* true means, do autoloading here */ ) ) {
        return new $classname( $element );
    }
    return new Model_Google_Base($element);
}

关于责任链:虽然这是一个如何编写它的漂亮示例,但我发现责任链意味着必须加载所有可能的处理程序并询问它们是否可以处理该类型。从我的角度来看,生成的代码更清晰、更明确,但同时会降低性能并增加复杂性。这就是我选择动态类名解析的原因。

于 2011-06-09T09:33:31.037 回答
0

也许您可以对输入文件应用 xsl 转换(在工厂方法中)。转换的结果应该是一个统一的 xml 文件,提供关于使用什么类的输入?

我知道这并不比很多if's 更好,但是这样,您至少可以避免重写代码。

于 2011-06-09T08:55:38.443 回答