没有数据库的 Laravel 模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23771655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:32:59  来源:igfitidea点击:

Laravel Models without a Database

phplaravel

提问by ThomasRedstone

I have an application which uses APIs as its data sources.

我有一个使用 API 作为其数据源的应用程序。

I'm considering trying out Laravel, but I can't really find any reference that discusses how models that don't use a database should be handled.

我正在考虑试用 Laravel,但我真的找不到任何讨论如何处理不使用数据库的模型的参考资料。

So, any suggestions?

那么,有什么建议吗?

回答by menjaraz

Give a try to Jens Segers's laravel-model.

试试Jens Segerslaravel-model

It provides an eloquent-likebase classthat can be used to build custom models in Laravel 4.

它提供了一种eloquent-likebase class可用于在 Laravel 4 中构建自定义模型。

Jenssegers\Modellike Illuminate\Database\Eloquent\Modelimplements ArrayAccess, ArrayableInterface, JsonableInterface.

Jenssegers\Model比如Illuminate\Database\Eloquent\Model实现 ArrayAccess、ArrayableInterface、JsonableInterface。

Features:

特征:

  • Accessors and mutators
  • Model to Array and JSON conversion
  • Hidden attributes in Array/JSON conversion
  • Appending accessors and mutators to Array/JSON conversion
  • 访问器和修改器
  • 模型到数组和 JSON 的转换
  • 数组/JSON 转换中的隐藏属性
  • 将访问器和修改器附加到数组/JSON 转换

Excerpt from Github repo:

摘自 Github 仓库:

class User extends Model {

    protected $hidden = array('password');

    public function save() 
    {
        return API::post('/items', $this->attributes);
    }

    public function setBirthdayAttribute($value)
    {
        $this->attributes['birthday'] = strtotime($value);
    }

    public function getBirthdayAttribute($value)
    {
        return date('Y-m-d', $value);
    }

    public function getAgeAttribute($value)
    {
        $date = DateTime::createFromFormat('U', $this->attributes['birthday']);
        return $date->diff(new DateTime('now'))->y;
    }
}

$item = new User(array('name' => 'john'));
$item->password = 'bar';

echo $item; // {"name":"john"}

回答by Igor R.

Create a class (a model) and implement required features. Just leave the "extends Eloquent" out of the class signature. Laravel can auto load classes in Models folders so you don't have to worry about that either! Use it normally within your application!

创建一个类(一个模型)并实现所需的功能。只需将“extends Eloquent”从类签名中删除即可。Laravel 可以自动加载 Models 文件夹中的类,所以你也不必担心!在您的应用程序中正常使用它!