【问题标题】:Propel peer static classes: how to avoid to write duplicated code?推动对等静态类:如何避免编写重复代码?
【发布时间】:2013-06-25 09:38:40
【问题描述】:

我在 Propel 中配置了一些表,并生成了 Peer 静态类。

我的问题是我需要对不同但相似的表执行相同的搜索操作。这些表有不同的 Peer 类,因为它是 Propel 的工作方式。这种情况会导致与在这些表上执行的查询相关的重复代码。

我想知道在这种情况下是否有一些结构(避免使用函数eval)可能对我有所帮助;我真的很想避免编写重复的代码,这些代码只对不同的静态 Peer 类执行完全相同的调用。

我正在编写的类的(非常长的)方法的示例代码 sn-p:

$criteria = new Criteria();
$criteria->add(FoobarPeer::CONTRACTNR,$data['contractnr']);
$result = FoobarPeer::doSelect($criteria);
if(count($result) > 1){
  throw new FoobarException("status: more than one row with the specified contractnr.");
}
if(count($result) == 0){
  // no object with given contractnr. Create new one.
  $obj = $this->factory->createORM("foobar");
  $obj->setCreatedAt(time());
} else {
  // use and update existing object.
  $obj = $result[0];
}

如您所见,我设法为行对象编写了一个工厂方法,但我找不到对静态类执行相同操作的方法。换句话说,我希望能够动态访问静态类,而不是以一种丑陋的解决方法。

有什么想法吗?

谢谢:)

【问题讨论】:

    标签: php static-methods factory propel anti-patterns


    【解决方案1】:

    我不确定我是否完全理解您的要求,但以下是我认为您所要求的解决方案:

    function orm_for($type) {
        return strtolower($type);
    }
    
    function peer_for($type) {
        return ucfirst($type)."Peer";
    }
    
    function exception_for($type) {
        return ucfirst($type)."Exception";
    }
    
    function query($type, $data) {
        $peer = $peer_for($type);
        $exception = $exception_for($type);
        $obj = null;
        $criteria = new Criteria();
        $criteria->add($peer::CONTRACTNR, $data["contractnr"]);
        $result = $peer::doSelect($criteria);
        if(count($result) > 1) {
            throw new $exception("status: more than one row with the specified contractnr.");
        } else if(count($result) == 0) {
            $obj = $this->factory->createORM(orm_for($type));
            $obj->setCreatedAt(time());
        } else {
            $obj = $result[0];
        }
    }
    

    我认为代码是不言自明的。让我知道我是否正确解释了您的问题。

    一个活生生的例子(只是一个 POC)可以是 found here

    【讨论】:

    • 谢谢你的回答,我还有一个问题:如果peer_for是一个对象中定义的方法,我该怎么称呼呢?也许像这样?:$peer = $($obj->peer_for($type))
    【解决方案2】:

    您应该能够使用behaviors 来实现您想要做的事情。您可以使用行为将自定义代码添加到生成的对等对象。见here

    除其他外,您的行为可以实现以下方法:

    staticAttributes()   // add static attributes to the peer class
    staticMethods()      // add static methods to the peer class
    

    您应该能够使用这些将您想要的代码添加到对等点。您只需要担心编写一次代码。 Propel 将在代码生成过程中复制代码,但这不应该太担心,因为很多生成的代码无论如何都是重复的。至少复制只是由自动化过程引入的。

    【讨论】:

      猜你喜欢
      • 2012-05-02
      • 1970-01-01
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 2011-08-29
      相关资源
      最近更新 更多