Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php namespace Helper;
- use Exception;
- /**
- * Trait PropertyAccessor
- * @package Helper
- */
- trait PropertyAccessor
- {
- /**
- * Accessor patterns
- * @var
- */
- protected $getter = 'get%s';
- protected $setter = 'set%s';
- /**
- * Return accessor method name
- * @param $template
- * @param $name
- * @return string
- */
- protected function accessorName($template, $name)
- {
- $name = ucfirst($name);
- return sprintf($template, $name);
- }
- /**
- * Variable getter
- * @param $name
- * @return mixed
- * @throws Exception
- */
- public function __get($name)
- {
- $getter = $this->accessorName($this->getter, $name);
- $name = '_' . $name;
- if (property_exists($this, $name) && method_exists($this, $getter)) {
- return $this->$getter($this->$name);
- } else {
- if (property_exists($this, $name)) {
- throw new Exception("${name} property has not getter");
- }
- throw new Exception("Undefined variable ${name}");
- }
- }
- /**
- * Variable setter
- * @param $name
- * @param $value
- * @return mixed
- * @throws Exception
- */
- public function __set($name, $value)
- {
- $setter = $this->accessorName($this->getter, $name);
- $name = '_' . $name;
- if (property_exists($this, $name) && method_exists($this, $setter)) {
- return ($this->$name = $this->$setter($value));
- } else {
- if (property_exists($this, $name)) {
- throw new Exception("${name} property has not setter");
- }
- throw new Exception("Undefined variable ${name}");
- }
- }
- }
- /****
- * Использование
- **/
- class Some
- {
- use Helper\PropertyAccessor;
- protected $_id = 42;
- protected function getId($v){ return $v * 2; }
- }
- $s = new Some;
- echo $s->id; // => 84
- $s->id = 23; // => Execption: "_id property has not setter"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement