php - 创建对象时如何应用开闭原则

标签 php open-closed-principle

我正忙于解析 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);
    }
}

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

编辑: 添加示例代码

最佳答案

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

这是你的新工厂:

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

关于php - 创建对象时如何应用开闭原则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6290161/

相关文章:

php - MySQLi INSERT 不工作

JavaScript 多选框不发布所有项目

php - 通过 parse_str 将多个值分配给数组

php - 使用数字作为关联数组键

class - 由于开闭原则处理继承层次结构

php - 在mysql上用foreach显示数据数组

design-patterns - 如果我们有良好的测试覆盖率,是否需要遵守开放封闭原则?

java - 理解开闭原则

.net - 在 Bootstrapper 中配置 Automapper 违反了开闭原则?