Created
May 25, 2014 23:48
-
-
Save tomzx/a98fd99736c656dd19b1 to your computer and use it in GitHub Desktop.
Model attribute accessors ala ruby (for Laravel)
This file contains 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 | |
trait ModelAttribute | |
{ | |
protected $attr_reader = []; | |
protected $attr_writer = []; | |
protected $attr_accessor = []; | |
public function getAttribute($key) | |
{ | |
if (!$this->isReadable($key)) { | |
throw new \Exception('Property undefined or not readable: '.get_class($this).'::$'.$key); | |
} | |
return parent::getAttribute($key); | |
} | |
public function setAttribute($key, $value) | |
{ | |
if (!$this->isWritable($key)) { | |
throw new \Exception('Property undefined or not writable: '.get_class($this).'::$'.$key); | |
} | |
parent::setAttribute($key, $value); | |
} | |
protected function isReadable($key) | |
{ | |
return in_array($key, $this->attr_accessor) || in_array($key, $this->attr_reader); | |
} | |
protected function isWritable($key) | |
{ | |
return in_array($key, $this->attr_accessor) || in_array($key, $this->attr_writer); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment