首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数据持有者应该具有什么样的可见性?

数据持有者应该具有什么样的可见性?
EN

Stack Overflow用户
提问于 2012-12-09 02:17:49
回答 1查看 84关注 0票数 0

我想知道在使用数据映射模式时,什么可见性会给出最佳实践?

私有/公共/受保护

当受到保护时,我需要在mapper类的save()方法中使用getters()。

如果是private和public,我将能够在mapper类中执行$user->id;。什么是最有意义的?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-09 02:24:01

在我看来,我经常这样使用它,属性是受保护的,我的类对getter和setter使用了魔术方法。按照我的方式,你可以同时做到这两点。我最喜欢使用setter-methods的地方就是使用流畅的界面。

代码语言:javascript
复制
/**
 * 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接口如下所示:

代码语言:javascript
复制
$post->setTitle('New Post')
     ->setBody('This is my answer on stackoverflow.com');

关于单一可能性的一些想法:

私有

使用私有属性会阻止我扩展模型类和重用某些功能。

公共的

将无法截获对变量的更改。有时需要在布景上做一些事情。

受保护

对我来说最好的办法。这些属性不能公开更改,我强制其他开发人员为他们的属性编写具有附加功能的getter和setter。同样,在我看来,这样可以防止其他人在误用您的模型类时出错。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13780382

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档