如何处理对象的状态

时间:2018-12-31 03:36:05

标签: php oop

处理对象在应用程序中可能具有的状态类型的正确方法是什么?

例如,如果我有一个AcceptanceCriteria类,则需要验证它是否被接受,拒绝或未决。

我通常通过返回代表状态的数字来做到这一点,但这似乎不是一个好的形式,它可能会造成混淆。

例如:

class AcceptanceCriteria
{

const PENDING = 0;
const ACCEPTED = 1;
const REJECTED = 2;

protected $state = self::PENDING;

public function accept():void
{
    $this->state = self::ACCEPTED;
}

public function reject():void
{
    $this->state = self::REJECTED;
}

public function state():int
{
    return $this->state;
}
}

我需要经常检查状态并将其显示在前面,有什么更好的方法?我不想在前面检查是否和接受标准状态是0、1或2以做某事。

2 个答案:

答案 0 :(得分:1)

一些返回布尔值而不是整数的访问器怎么样,以便您的算法被完全封装?

class AcceptanceCriteria
{

const PENDING = 0;
const ACCEPTED = 1;
const REJECTED = 2;

protected $state = self::PENDING;

public function accept():void
{
    $this->state = self::ACCEPTED;
}

public function reject():void
{
    $this->state = self::REJECTED;
}

// Accessors

public function is_rejected():bool
{
    return self::PENDING == $this->state;
}

public function is_accepted():bool
{
    return self::ACCEPTED == $this->state;
}

public function is_rejected():bool
{
    return self::REJECTED == $this->state;
}

}

答案 1 :(得分:0)

使用强类型enums的好方法。您可以使用splEnumMy C-Labs中的智能实现。

首先将您的状态移至单独的枚举类

<?php
use MyCLabs\Enum\Enum;

class AcceptanceCriteriaStateEnum extends Enum
{
    private const PENDING = 0;
    private const ACCEPTED = 1;
    private const REJECTED = 2;
}

然后您可以像下面这样修改您的课程

class AcceptanceCriteria
{
    protected $state = AcceptanceCriteriaStateEnum::PENDING;

    public function setState(AcceptanceCriteriaStateEnum $state):void
    {
        $this->state = $state;
    }

    public function getState():int
    {
        return $this->state;
    }

    public function isInState(AcceptanceCriteriaStateEnum $checkState):bool
    {
        return $this->state == $checkState;
    }
}

要检查状态,可以使用返回布尔值的方法isInState

$obj = new AcceptanceCriteria();
$obj->setState(AcceptanceCriteriaStateEnum::ACCEPTED);

// check status
echo $obj->isInState(AcceptanceCriteriaStateEnum::ACCEPTED);