Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Models without a Database

Tags:

php

laravel

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

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.

So, any suggestions?

like image 459
ThomasRedstone Avatar asked Dec 07 '22 01:12

ThomasRedstone


1 Answers

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

It provides an eloquent-like base class that can be used to build custom models in Laravel 4.

Jenssegers\Model like Illuminate\Database\Eloquent\Model implements 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

Excerpt from Github repo:

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"}
like image 68
menjaraz Avatar answered Dec 15 '22 05:12

menjaraz