Skip to content

Instantly share code, notes, and snippets.

@tomzx
Created May 25, 2014 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomzx/a98fd99736c656dd19b1 to your computer and use it in GitHub Desktop.
Save tomzx/a98fd99736c656dd19b1 to your computer and use it in GitHub Desktop.
Model attribute accessors ala ruby (for Laravel)
<?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