如何使用驼峰式大小写访问属性? [英] How can I access attributes using camel case?

查看:73
本文介绍了如何使用驼峰式大小写访问属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为使编码风格保持一致,我想使用camelCase而不是snake_case来访问属性.在不修改核心框架的情况下,在Laravel中这是否可能?如果可以,怎么办?

To be consistent over my coding style, I'd like to use camelCase to access attributes instead of snake_case. Is this possible in Laravel without modifying the core framework? If so, how?

示例:

// Database column: first_name

echo $user->first_name; // Default Laravel behavior
echo $user->firstName; // Wanted behavior

推荐答案

创建您自己的BaseModel类,并覆盖以下方法.确保所有其他型号extend您的BaseModel.

Create your own BaseModel class and override the following methods. Make sure all your other models extend your BaseModel.

class BaseModel extends Eloquent {

    // Allow for camelCased attribute access

    public function getAttribute($key)
    {
        return parent::getAttribute(snake_case($key));
    }

    public function setAttribute($key, $value)
    {
        return parent::setAttribute(snake_case($key), $value);
    }

}

然后使用:

// Database column: first_name

echo $user->first_name; // Still works
echo $user->firstName; // Works too!

此技巧围绕着通过覆盖Model中使用的魔术方法来迫使密钥变成蛇形.

This trick revolves around forcing the key to snake case by overriding the magic method used in Model.

这篇关于如何使用驼峰式大小写访问属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆