Package Data | |
---|---|
Maintainer Username: | ngmy |
Maintainer Contact: | y.nagamiya@gmail.com (ngmy) |
Package Create Date: | 2014-03-30 |
Package Last Update: | 2014-03-30 |
Language: | PHP |
License: | MIT |
Last Refreshed: | 2024-11-14 15:13:33 |
Package Statistics | |
---|---|
Total Downloads: | 15 |
Monthly Downloads: | 0 |
Daily Downloads: | 0 |
Total Stars: | 1 |
Total Watchers: | 2 |
Total Forks: | 0 |
Total Open Issues: | 1 |
A caching scheme for an object for Laravel 4, inspired by Enterprise Rails.
The Cached Object has the following requirements:
PHP 5.3+
Laravel 4.0+
Add the package to your composer.json
and run composer update
:
{
"require": {
"ngmy/cached-object": "dev-master"
}
}
Add the following to the list of service providers in app/config/app.php
:
'Ngmy\CachedObject\CachedObjectServiceProvider',
Add the following to the list of class aliases in app/config/app.php
:
'CachedObject' => 'Ngmy\CachedObject\CachedObject',
namespace App\Models\Physical;
use Illuminate\Database\Eloquent\Model as Eloquent;
class Movie extends Eloquent {}
namespace App\Models\Logical;
use CachedObject;
class Movie extends CachedObject {
public static $VERSION = 1;
public $id;
public $name;
public $lengthMinutes;
public function __construct($id, $name, $lengthMinutes)
{
$this->id = $id;
$this->name = $name;
$this->lengthMinutes = $lengthMinutes;
}
}
You need to define $VERSION
. This property is used to create a unique cache key for a requested object. Please increments this number when you change a structure of a class.
namespace App\Models\Logical;
class UncachedMovie {
public static function get($id)
{
$m = \App\Models\Physical\Movie::find($id);
if (is_null($m)) {
return null;
} else {
$movie = new Movie(
$m->id,
$m->name,
$m->length_minutes
);
return $movie;
}
}
}
In order to get an object of a logical model, you need to define a method whose name starts with get. This method is called only if an object does not exist in a cache.
Movie::get()
.For example, to rebuild a cache when you updated a physical model, and also to delete a cache when you deleted a physical model, define a observer as follows:
namespace App\Models\Logical;
class MovieObserver
{
public function saved($m)
{
Movie::rebuild($m->id);
}
public function deleted($m)
{
Movie::clear($m->id);
}
}
\App\Models\Physical\Movie::observe(new \App\Models\Logical\MovieObserver);
Please see my unit tests.