我想知道在使用数据映射模式时,什么可见性会给出最佳实践?
私有/公共/受保护
当受到保护时,我需要在mapper类的save()方法中使用getters()。
如果是private和public,我将能够在mapper类中执行$user->id;。什么是最有意义的?
发布于 2012-12-09 02:24:01
在我看来,我经常这样使用它,属性是受保护的,我的类对getter和setter使用了魔术方法。按照我的方式,你可以同时做到这两点。我最喜欢使用setter-methods的地方就是使用流畅的界面。
/**
* Handling non existing getters and setters
*
* @param string $name
* @param array $arguments
* @throws Exception
*/
public function __call($name, $arguments)
{
$type = substr($name, 0, 3);
// Check if this is a getter or setter
if (in_array($type, array('get', 'set'))) {
$property = lcfirst(substr($name, 3));
// Only if the property exists we can go on
if (property_exists($this, $property)) {
switch ($type) {
case 'get':
return $this->$property;
break;
case 'set':
$this->$property = $arguments[0];
return $this;
break;
}
} else {
throw new \Exception('Unknown property "' . $property . '"');
}
} else {
throw new Exception('Unknown method "' . $name . '"');
}
}
/**
* Magic Method for getters
*
* @param string $name
* @return mixed
*/
public function __get($name)
{
$method = 'get' . ucfirst($name);
return $this->$method();
}
/**
* Magic Method for setters
*
* @param string $name
* @param mixed $value
*/
public function __set($name, $value)
{
$method = 'set' . ucfirst($name);
return $this->$method($value);
}使用fluent接口如下所示:
$post->setTitle('New Post')
->setBody('This is my answer on stackoverflow.com');关于单一可能性的一些想法:
私有
使用私有属性会阻止我扩展模型类和重用某些功能。
公共的
将无法截获对变量的更改。有时需要在布景上做一些事情。
受保护
对我来说最好的办法。这些属性不能公开更改,我强制其他开发人员为他们的属性编写具有附加功能的getter和setter。同样,在我看来,这样可以防止其他人在误用您的模型类时出错。
https://stackoverflow.com/questions/13780382
复制相似问题