Я делаю класс BaseModel и хочу использовать магические методы __set и __get вместо определения сеттеров и геттеров для каждого отдельного свойства.Есть ли лучший способ определить __get без использования переменных переменных или массива для всех переменных-членов?
В настоящее время я использую переменные переменные, потому что я не мог найти другой способ, выполнив его. Переменные переменные считаются плохой практикой или я не беспокоюсь ни о чем?
abstract class BaseModel implements \ArrayAccess {
/**
* Don't allow these member variables to be written by __set
*
* @var array
*/
protected $noSet = array();
/**
* Don't allow these member variables to be retrieved by __get
*
* @var array
*/
protected $noGet = array();
public function offsetExists($offset)
{
return property_exists($this, $offset);
}
public function offsetGet($offset)
{
return $this->__get($offset);
}
public function offsetSet($offset , $value)
{
return $this->__set($offset, $value);
}
public function offsetUnset($offset)
{
unset($this->$offset);
}
public function __get($member)
{
if($member == 'noSet' || $member == 'noGet')
{
throw new \InvalidArgumentException ("Tried to access a forbidden property", 1);
}
if(! property_exists($this, $member))
{
throw new \InvalidArgumentException ("Tried to access a non-existent property", 1);
}
if(in_array($member, $this->noGet))
{
throw new \InvalidArgumentException ("Tried to access a forbidden property", 1);
}
return $this->$member;
}
public function __set($member, $value)
{
if($member == 'noSet' || $member == 'noGet')
{
throw new \DomainException ("Tried write to a non-writable property.", 1);
}
if(! property_exists($this, $member))
{
throw new \InvalidArgumentException ("Tried to access a non-existent property", 1);
}
if(in_array($member, $this->noSet))
{
throw new \DomainException ("Tried write to a non-writable property.", 1);
}
return $this->$member = $value;
}
PS: Проверьте __call. Мы избавились от так много крутизны в наших моделях :) – Jessica