繁体   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