PHP方法链接:在允许其他方法链接之前调用一个方法

时间:2013-08-30 03:13:25

标签: php oop method-chaining

考虑以下课程

class myClass {

   private $model;

    public function update($input) {
        return $this->model->update($input);
    }

    public function find($id) {
        $this->model = ORMfind($id);
    }
}

如何阻止

$myClass = new myClass;
$myClass->update($input);

问题不是如何使用上面的代码,而是如何使update()方法只能在find()之后调用。

编辑:我改变了我的方法所做的事情,因此我更清楚地知道我需要在另一个方法(update())之前做一个方法(find())

4 个答案:

答案 0 :(得分:2)

您可以为代码添加标记,如下所示:

class myClass {

  private $model;
  private $canUpdate = 0;

  public function update($input) {
    if ($canUpdate === 0) return; // or throw an exception here
    return $this->model->update($input);
  }

  public function find($id) {
    $this->model = ORMfind($id);
    $canUpdate = 1;
  }

}

设置标记$canUpdate会提醒update()方法做出相应的反应。如果调用了update(),如果标志仍为0,则可以抛出异常或退出方法。

答案 1 :(得分:1)

通过get:

防止返回null值
public function get() {
    if (isset($this->value)) return $this->value;
    else echo "please give me a value ";

 }

您还可以创建一个构造:

 function __construct($val){
    $this->value=$val;  
 } 

然后在不使用$value方法的情况下为set()提供值:

 $myClass=new myClass(10);  

答案 2 :(得分:0)

输出文字,返回无效,我认为所有这些都是错误的。当你不希望发生某些事情时,你应该抛出异常:

class MyClass {
    private $canUpdate = false;

    public function find($id) {
        // some code...
        $this->canUpdate = true;
    }

    public function canUpdate() {
        return $this->canUpdate;
    }

    private function testCanUpdate() {
        if (!$this->canUpdate()) {
            throw new Exception('You cannot update');
        }
    }

    public function update($inpjut) {
        $this->testCanUpdate();

        // ... some code
    }
}

现在你可以做到:

$obj = new MyClass();

try {
    $obj->update($input);
} catch (Exception $e) {
    $obj->find($id);
    $obj->update($input);
}

答案 3 :(得分:0)

确保->update()只能在模型初始化时调用的正确方法是将其转换为依赖项:

class myClass 
{
    private $model;

    public function __construct($id)
    {
        $this->model = ORMfind($id);
    }

    public function update($input) {
        return $this->model->update($input);
    }
}

$x = new myClass('123');

或者,如果您有多个查找操作,则可以将它们作为静态构造函数方法引入:

class myClass 
{
    private $model;

    private function __construct($model)
    {
        $this->model = $model;
    }

    public function update($input) {
        return $this->model->update($input);
    }

    public static function find($id)
    {
        return new self(ORMfind($id));
    }
}

$x = myClass::find('123');

<强>更新

通过简单的检查可以解决您的紧急问题:

    public function update($input) {
        return $this->model ? $this->model->update($input) : null;
    }