在PHP中创建动态工厂方法(< 5.3)

时间:2010-04-03 19:04:13

标签: php dynamic factory

如何在PHP中创建动态工厂方法?通过动态工厂方法,我的意思是一种工厂方法,它将根据给定参数的某些方面自动发现要创建的对象。最好不要先在工厂注册它们。我可以将可能的对象放在一个公共位置(目录)中。

我想避免在工厂方法中使用典型的switch语句,例如:

public static function factory( $someObject )
{
    $className = get_class( $someObject );
    switch( $className )
    {
        case 'Foo':
            return new FooRelatedObject();
            break;
        case 'Bar':
            return new BarRelatedObject();
            break;
        // etc...
    }
}

我的具体案例涉及工厂根据要投票的项目创建投票存储库。这些项都实现了Voteable接口。像这样:

Default_User implements Voteable ...
Default_Comment implements Voteable ...
Default_Event implements Voteable ...

Default_VoteRepositoryFactory
{
    public static function factory( Voteable $item )
    {
        // autodiscover what type of repository this item needs
        // for instance, Default_User needs a Default_VoteRepository_User
        // etc...
        return new Default_VoteRepository_OfSomeType();
    }
}

我希望能够为这些项目添加新的Voteable项目和投票存储库,而无需触及工厂的实施。

1 个答案:

答案 0 :(得分:2)

如果switch语句已经完成,那么基本上是命名约定。获取传入的对象的类,并使用它来实例化新类。简单的例子如下。

//pseudo code, untested
class Default_VoteRepositoryFactory
{
    public static function factory( Voteable $item, $arg1, $arg2 )
    {
        $parts = explode('_', get_class($item));
        $type  = array_pop();
        $class = 'Default_VoteRepository_' . $type;
        return new $class($arg1, $arg2);
        // autodiscover what type of repository this item needs
        // for instance, Default_User needs a Default_VoteRepository_User
        // etc...
    }
    //can be as complex or as simple as you need
    protected static function getType(stdClass $item)
    {
        $parts = explode('_', get_class($item));
        return array_pop($parts);       
    }
}
相关问题