如何避免在方法内验证传递的参数?适当的OOD

时间:2013-12-04 14:49:50

标签: php oop xml-parsing

编写依赖于一个抽象类的解析器组,该抽象类实现共享方法并要求实现包含每个解析器逻辑的加法方法。

抽象解析器代码:

    <?
abstract class AbstractParser {
    /*
     * The only abstract method to implement. It contains unique logic of each feed passed to the function
     */
    public abstract function parse($xmlObject);

    /**
     * @param $feed string
     * @return SimpleXMLElement
     * @throws Exception
     */
    public function getFeedXml($feed) {
        $xml = simplexml_load_file($feed);

        return $xml;
    }

    /**
     * @return array
     */
    public function getParsedData() {
        return $this->data;
    }

    /**
     * @param SimpleXMLElement
     * @return Array
     */
    public function getAttributes($object) {
        // implementation here
    }
}

Concrete Parser类:

    <?php
class FormulaDrivers extends AbstractParser {
    private $data;

    /**
     * @param SimpleXMLElement object
     * @return void
     */
    public function parse($xmlObject) {
        if (!$xmlObject) {
            throw new \Exception('Unable to load remote XML feed');
        }

        foreach($xmlObject->drivers as $driver) {
            $driverDetails = $this->getAttributes($driver);

            var_dump($driver);
        }
    }
} 

实例化:

$parser = new FormulaDrivers();
$parser->parse( $parser->getFeedXml('http://api.xmlfeeds.com/formula_drivers.xml') );

正如您所看到的,我将getFeedXml方法的结果传递给parse方法,基本上将getFeedXml的结果验证委托给parse方法。 我怎样才能避免它,确保它在将它传递给parse方法之前返回正确的XML对象? 增加实例化过程和调用方法的数量导致需要一些工厂方法......

无论如何,你会如何解决这个小问题?

谢谢!

1 个答案:

答案 0 :(得分:1)

使parse受到保护,只有parse_xml_file才会调用它:

abstract class AbstractParser {
    /*
     * The only abstract method to implement. It contains unique logic of each feed passed to the function
     */
    protected abstract function parse($xmlObject);

    /**
     * @param $feed string
     * @return [whatever .parse returns]
     * @throws Exception
     */
    public function parseFile($feed) {
        $xml = simplexml_load_file($feed);
        if (!$xml) {
            throw new \Exception('Unable to load remote XML feed');
        }
        return $this->parse($xml);
    }

    /**
     * @return array
     */
    public function getParsedData() {
        return $this->data;
    }

    /**
     * @param SimpleXMLElement
     * @return Array
     */
    public function getAttributes($object) {
        // implementation here
    }
}
$parser->parseFile('http://api.xmlfeeds.com/formula_drivers.xml');