具有参数和依赖关系的类设计

时间:2012-09-28 11:50:03

标签: php dependency-injection class-design factory

我在Zend Framework 1之后设计了我的数据库和缓存层,如下所示:

class Cache
{
    public static function create($adapter, array $params)
    {
        $class_name = 'Cache_Adapter_' . $adapter;

        return new $class_name($params);   
    }
}

abstract class Cache_Adapter
{
    public function __construct(array $params)
    {

    }
}

class Cache_Adapter_File extends Cache_Adapter
{
    // ...
}

用法示例:

// config.php
return array(
    'cache' => array(
        'adapter' => 'file',
        'params' => array(
            'path' => '/path',
        ),
    ),
);

// bootstrap.php
$dic->cache = Cache::create($config['cache']['adapter'], $config['cache']['params']);

这种方法很棒,因为每个缓存适配器都可以有不同的参数, 例如,文件缓存需要路径到存储缓存文件的目录。

然后我想创建用于在数据库中存储数据的缓存适配器,并实现了代替 标量参数数组,需要数据库抽象类依赖。

当前数据库连接在依赖注入容器中注册:

// config.php
return array(
    'db1' => array(
        'adapter' => 'mysql',
        'params' => array(
            'user' => 'root',
            'connect_timeout' => 5,
        ),
    ),
    'db2' => array(
        'adapter' => 'sqlsrv',
        'params' => array(
            'db' => 'foo',
        ),
    ),
);

// bootstrap.php
$dic->db1 = Site:Db::create($config['db1']['adapter'], $config['db1']['params']);
$dic->db2 = Site:Db::create($config['db2']['adapter'], $config['db2']['params']);

所以我想问一下除了标量配置参数数组之外,可以将零个或多个特定依赖项传递给缓存适配器,这可以在config.php中完成。

class Cache_Adapter_Db extends Cache_Adapter
{
    // Instead of abstract Cache_Adapter::__construct(array $params)
    // something like this is needed:
    // public function __construct(array $params, Db_Adapter $db)
    public function __construct(array $params)
    {

    }
}

1 个答案:

答案 0 :(得分:0)

涉及两个步骤:首先,您的缓存适配器应以正确的方式调用其父类:

class Cache_Adapter_Db extends Cache_Adapter
{
    public function __construct(array $params, Db_Adapter $db)
    {
       parent::__construct($params);
    }
}

第二:您的工厂类Cache应该接受更多参数:

class Cache
{
    public static function create($adapter, array $params, $optparams = null )
    {
        $class_name = 'Cache_Adapter_' . $adapter;

        return new $class_name($params, $optparams);   
    }
}

配置php看起来像这样:

// config.php
return array(
    'db1' => array(
        'adapter' => 'mysql',
        'params' => array(
            'user' => 'root',
            'connect_timeout' => 5,
        ),
    ),
    'db2' => array(
        'adapter' => 'sqlsrv',
        'params' => array(
            'db' => 'foo',
        ),
        'options' => 'extraoption'
    ),
);

并在bootstrap.php中:

$dic->db2 = Site:Db::create(
   $config['db2']['adapter'], 
   $config['db2']['params'],
   $config['db2']['options']
);