Currently, I am writing a laravel application with a part for sending messages between the staff at the company and the clients.
So, I have a field named "status" in the database. In this field, a value of one indicates that the message is waiting for an answer, a value of two indicates that it has been answered, and a value of three indicates that the message has been closed. There is a problem here, however. It's not clear what these numbers do when someone looks at my code.
Would there be any way for me to define this number or any other way to make my code more readable?
(I'm using laravel eloquent ORM) The code below is for the method that closes a conversation:

    public function close(Request $request)
    {
        $message = Message::find($request->message_id);
//        Status one indicates that a conversation has been closed
        $message->status = 1;
        $message->save();
        return \response($message, 200);
    }

推荐答案

在消息模型中使用常量

class Message
{
    const STATUS_PENDING = 1;
    const STATUS_ANSWERED = 2;
    const STATUS_CLOSED = 3;
//...
}

那么你的代码就可读了

public function close(Request $request)
{
    $message = Message::find($request->message_id);
    $message->status = Message::STATUS_CLOSED;
    $message->save();
    return \response($message, 200);
}

或者更好的方法是,在常量值的基础上,将其作为模型中的一个方法

public function close(Request $request)
{
    $message = Message::find($request->message_id);
    $message->close();
    return \response($message, 200);
}

例如,通过这种方式,您可以在将来升级该方法

class Message
{
    public function close()
    {
        if ($this->status != self::STATUS_ANSWERED) {
            //log message closed without client answer
        }
        $this->status = STATUS_CLOSED;
        $this->save();
    }
}

Php相关问答推荐

未找到laravel cascadeOnEdit

Laravel迁移返回SQL错误,但SQL有效且工作正常

WooCommerce HPOS管理订单列表中带有订单元数据的定制列

在PHP中循环访问多维数组,并按组显示内容

在Laravel中修改JSON输出

Laravel:如何展平多维Eager 加载的集合

在PHP中处理Linux输入事件(/dev/input/Event*)

如果所有请求都通过index.php路由,如何使用htaccess文件强制使用HTTPS?

在具有Angular 的 Laravel 应用程序中,不显示图像

主机中未检索用户表数据

如何从 URL 核心 PHP 中的 API 获取 JSON?

提交仅包含活动详细信息选项卡表单的主表单

在 Botiga 主题模板中添加复选框到政策行.Woocommerce

保留 .htaccess 中的符号登录 URL

适当的时区处理 Laravel / Carbon

Laravel 查询关系是否为 bool

Laravel Factory - 在单列中生成具有随机迭代量的假 json 数组数据

Eloquent 的模型更新了它应该 laravel php 的更多行

Symfony 自定义注销

Laravel 响应 html 默认页面忽略控制器