Advertisement
Serafim

Untitled

Feb 18th, 2014
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.03 KB | None | 0 0
  1. <?php namespace Helper;
  2.  
  3. use Exception;
  4.  
  5. /**
  6.  * Trait PropertyAccessor
  7.  * @package Helper
  8.  */
  9. trait PropertyAccessor
  10. {
  11.     /**
  12.      * Accessor patterns
  13.      * @var
  14.      */
  15.     protected $getter = 'get%s';
  16.     protected $setter = 'set%s';
  17.  
  18.     /**
  19.      * Return accessor method name
  20.      * @param $template
  21.      * @param $name
  22.      * @return string
  23.      */
  24.     protected function accessorName($template, $name)
  25.     {
  26.         $name = ucfirst($name);
  27.         return sprintf($template, $name);
  28.     }
  29.  
  30.     /**
  31.      * Variable getter
  32.      * @param $name
  33.      * @return mixed
  34.      * @throws Exception
  35.      */
  36.     public function __get($name)
  37.     {
  38.         $getter = $this->accessorName($this->getter, $name);
  39.         $name   = '_' . $name;
  40.         if (property_exists($this, $name) && method_exists($this, $getter)) {
  41.             return $this->$getter($this->$name);
  42.         } else {
  43.             if (property_exists($this, $name)) {
  44.                 throw new Exception("${name} property has not getter");
  45.             }
  46.             throw new Exception("Undefined variable ${name}");
  47.         }
  48.     }
  49.  
  50.     /**
  51.      * Variable setter
  52.      * @param $name
  53.      * @param $value
  54.      * @return mixed
  55.      * @throws Exception
  56.      */
  57.     public function __set($name, $value)
  58.     {
  59.         $setter = $this->accessorName($this->getter, $name);
  60.         $name   = '_' . $name;
  61.         if (property_exists($this, $name) && method_exists($this, $setter)) {
  62.             return ($this->$name = $this->$setter($value));
  63.         } else {
  64.             if (property_exists($this, $name)) {
  65.                 throw new Exception("${name} property has not setter");
  66.             }
  67.             throw new Exception("Undefined variable ${name}");
  68.         }
  69.     }
  70. }
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77. /****
  78.  * Использование
  79. **/
  80. class Some
  81. {
  82.   use Helper\PropertyAccessor;
  83.  
  84.   protected $_id = 42;
  85.   protected function getId($v){ return $v * 2; }
  86. }
  87.  
  88. $s = new Some;
  89. echo $s->id; // => 84
  90. $s->id = 23; // => Execption: "_id property has not setter"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement