【问题标题】:What visibility should data holder have?数据持有者应该有什么可见性?
【发布时间】:2012-12-08 18:17:49
【问题描述】:

我想知道什么样的可见性可以为使用数据映射模式提供最佳实践?

私有/公共/受保护

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

如果私有和公共我将能够做 $user->id;在映射器类中。什么最有意义?

【问题讨论】:

    标签: php design-patterns


    【解决方案1】:

    在我看来,我经常以这种方式使用它,属性受到保护,我的类对 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);
    }
    

    使用流畅的接口看起来像这样:

    $post->setTitle('New Post')
         ->setBody('This is my answer on stackoverflow.com');
    

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

    私人

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

    公开

    将无法拦截对变量的更改。有时需要在设置上做一些事情。

    受保护

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

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 2022-08-09
      • 2018-12-20
      • 2016-11-03
      • 2014-05-25
      • 1970-01-01
      相关资源
      最近更新 更多