PHP Cookie类配置

时间:2015-03-05 00:57:22

标签: php arrays oop cookies

我正在编写一个cookie类,但是希望将默认配置保存在一个单独的文件中,该文件只是为了特定于应用程序的原因而返回一个数组。我想知道将配置数组放入类中的最佳方法是什么。我喜欢第一个实现,因为它更清洁,但我想知道第二个实现是否被认为是一个坏的做法?我不希望该类直接了解或依赖于外部文件,但不确定传递它的最佳方式。

/* config/Cookie.php */
return [
    'expire'   => null,
    'path'     => null,
    'domain'   => null,
    'secure'   => false,
    'htpponly' => false
]

我正在考虑以两种方式之一构建它:

第一种方式对我来说看起来更干净,但我不确定如何获得默认配置项。

class Cookie
{
    protected $name;
    protected $value;
    protected $expires;
    protected $path;
    protected $domain;
    protected $secure;
    protected $httponly;

    public function __construct($name, $value, $expire = null, $path = null, $doamin = null, $secure = false, $httponly = false)
    {
        $this->name = $name;
        $this->value = $value;
        $this->expire = $expire
        // ...
    }

或者将配置数组传递给构造函数的第二种方式

class Cookie
{
    protected $name;
    protected $value;
    protected $config = array(
        'expire    => null,
        'path'     => null,
        'domain'   => null,
        'secure    => false,
        'httponly' => false
    );

    public function __construct($name, $value, array $config = null)
    {
        $this->name = $name;
        $this->value = $value;
        $this->config = array_merge($this->config, $config);
    }

    // ... $name and $value getters

    public function getExpire()
    {
        return $this->config['expire'];
    }

将类属性存储在数组中会被视为不好的做法吗?

0 个答案:

没有答案