簡體   English   中英

php中的方法鏈

[英]Method chaining in php

我有以下課程

class FormValidator{

    public function __construct() {}

    public function __destruct(){}

    private $value;

    public function Value($value){
        $this->value = trim($value);
        return $this;
    }

    public function Required(){
        if(empty($this->value)){
           return false;
        }
        else{
            return $this;
        }
    }

    public function MinLength($length){
        $len = strlen($this->value);
        if($len < $length){
           return false;
        }
        else{
            return $this;
        }
    }
}

在我的 php 代碼中,我正在調用 -

 $validator = new FormValidator();
 $result = $validator->Value("")->Required()->MinLength(5)->SomeOtherMethod();

上面的行給出了錯誤Call to a member function MinLength() on a non-object ...

更新:如果Required() 返回false,我需要停止調用MinLength()。

我怎樣才能使我的陳述有效?

您應該改用異常,它會處理錯誤,而方法本身將始終返回當前實例。

這變成:

<?php
class FormValidationException extends \Exception 
{
}

class FormValidator
{
  private $value;

  public function Value($value): self
  {
    $this->value = trim($value);
    return $this;
  }

  /**
   * @return $this
   * @throws FormValidationException
   */
  public function Required(): self
  {
    if (empty($this->value)) {
      throw new \FormValidationException('Value is required.');
    }
    return $this;
  }

  /**
   * @param int $length
   * @return $this
   * @throws FormValidationException
   */
  public function MinLength(int $length): self
  {
    $len = strlen($this->value);
    if ($len < $length) {
      throw new \FormValidationException("Value should be at least {$length} characters long.");
    }
    return $this;
  }
}

用法:

$validator = new FormValidator();
try {
  $result = $validator->Value("lodddl")->Required()->MinLength(5);
} catch (\FormValidationException $e) {
  echo 'Error: ', $e->getMessage();
}

演示: https : //3v4l.org/OFcPV

編輯:由於 OP 使用的是 PHP 5.2(遺憾的是),這是它的一個版本,在根命名空間之前刪除\\ s,返回類型聲明和參數類型。

PHP 5.2 演示: https : //3v4l.org/cagWS

原因方法Required()返回false而不是Class object

    if(empty($this->value)){
        return false;
    }

您必須將代碼更改為。

$result = $validator->Value("");
if($result->Required()){ // if is not false do 
   $result->MinLength(5)->SomeOtherMethod();
}else{
    // do anything if value is empty.
}

除了使用異常(@Jeto 的解決方案),您還可以使用包含所有錯誤的數組。 此解決方案的一個好處是您將在一次運行中遇到多個錯誤,而不是在第一個錯誤時中斷。

<?php
class FormValidator
{
  private $value;

  private $_errors = array();

  public function Value($value)
  {
    $this->value = trim($value);
    return $this;
  }

  /**
   * @return $this
   */
  public function Required()
  {
    if (empty($this->value)) {
      $this->_errors[] = 'Value is required';
    }
    return $this;
  }

  /**
   * @param int $length
   * @return $this
   */
  public function MinLength($length)
  {
    $len = strlen($this->value);
    if ($len < $length) {
      $this->_errors[] = "Value should be at least {$length} characters long.";
    }
    return $this;
  }

  public function hasErrors(){
    return (count($this->_errors) > 0);
  }

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

$validator = new FormValidator();
$validator->Value("1234")->Required()->MinLength(5);
if($validator->hasErrors()){
    echo implode('<br>',$validator->getErrors());
}

示例在這里

在以下方法中,您將調用布爾值的方法。

Required();

MinLength();

為了在MinLength方法中解決這個問題:

if($len < $length){

    // As a flag
    $this->failed = true;

    return $this;
}

和 SomeOtherMethod():

public function SomeOtherMethod() {
    if (! $this->failed) {
        // do something...
    } else {
        // do nothing...
    }
}

Requied()方法執行相同操作

我有以下課程

class FormValidator{

    public function __construct() {}

    public function __destruct(){}

    private $value;

    public function Value($value){
        $this->value = trim($value);
        return $this;
    }

    public function Required(){
        if(empty($this->value)){
           return false;
        }
        else{
            return $this;
        }
    }

    public function MinLength($length){
        $len = strlen($this->value);
        if($len < $length){
           return false;
        }
        else{
            return $this;
        }
    }
}

在我的php代碼中,我正在打電話-

 $validator = new FormValidator();
 $result = $validator->Value("")->Required()->MinLength(5)->SomeOtherMethod();

上一行Call to a member function MinLength() on a non-object ...給出了錯誤Call to a member function MinLength() on a non-object ...

更新:如果Required()返回false,我需要停止調用MinLength()。

如何使我的陳述發揮作用?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM