ThomasRedstone
ThomasRedstone

Reputation: 378

Laravel Models without a Database

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?

Upvotes: 5

Views: 11421

Answers (2)

menjaraz
menjaraz

Reputation: 7575

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"}

Upvotes: 8

Igor R.
Igor R.

Reputation: 897

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!

Upvotes: 7

Related Questions