没有数据库的 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
Laravel Models without a Database
提问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.
It provides an eloquent-likebase class
that can be used to build custom models in Laravel 4.
它提供了一种eloquent-likebase class
可用于在 Laravel 4 中构建自定义模型。
Jenssegers\Model
like Illuminate\Database\Eloquent\Model
implements 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 文件夹中的类,所以你也不必担心!在您的应用程序中正常使用它!