Created
November 1, 2012 10:47
-
-
Save wayneashleyberry/3993012 to your computer and use it in GitHub Desktop.
key-value storage for eloquent models
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
// add key-value storage to models | |
class Eloquent extends \Eloquent { | |
protected $metaClass = 'ObjectMeta'; | |
public function meta() | |
{ | |
return $this->has_many($this->metaClass); | |
} | |
public function set_meta($key, $value) | |
{ | |
$meta = $this->meta()->where('key', '=', $key)->first(); | |
if ($meta) | |
{ | |
$meta->value = $value; | |
$meta->save(); | |
} | |
else | |
{ | |
$metaClass = $this->metaClass; | |
$meta = new $metaClass(array( | |
'key' => $key, | |
'value' => $value | |
)); | |
$this->meta()->insert($meta); | |
} | |
} | |
public function get_meta($key) | |
{ | |
$meta = $this->meta()->where('key', '=', $key)->first(); | |
if ($meta) | |
{ | |
return $meta->value; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
class ObjectMeta extends \Eloquent { | |
public static $key = 'key'; | |
public static $table = 'object_meta'; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$object = Object::find(1); | |
$object->set_meta('zef', 'side'); | |
var_dump($object->get_meta('zef')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment