ZF2自动加载器:在扩展类上也使用工厂作为基类

时间:2014-07-27 15:01:39

标签: php class zend-framework2 factory

如果我想为扩展我的基类的任何类使用相同的工厂,我是否希望将基类工厂转换为命名函数,或者有更好的方法来执行此操作吗?

$serviceManager => array(
    'factories' => array(
        'someBaseClass' => function($thisServiceManager) {
            $db = $thisServiceManager->get('db');
            $thisBaseClass = new \myNamespace\thisBaseClass($db);
            return $thisBaseClass;
        },
    ),
);

修改

除了我接受的答案之外,这里有我测试过的有效的代码。

班级档案

use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class baseClassFactory implements \Zend\ServiceManager\AbstractFactoryInterface
{
    public function canCreateServiceWithName (ServiceLocatorInterface $locator, $name, $requestedName = '')
    {
        return ('baseClass' === $name || is_subclass_of($name, 'baseClass'));
    }

    public function createServiceWithName (ServiceLocatorInterface $locator, $name, $requestedName = '')
    {
        $db = $locator->get('db');
        $query = new $name($db);
        return $query;
    }
}

配置

$serviceManager => array(
    'abstract_factories' => array(
        'baseClassFactory',
    ),
);

1 个答案:

答案 0 :(得分:3)

如果我关注您的问题,那么您有一堆扩展someBaseClass的类,并且您希望所有类都以相同的方式制作?

如果是这样,那么这听起来是使用abstract_factories中的ServiceManager组件的好机会。伪代码就像:

// warning: untested pseudo-code
class MyAbstractFactory implements \Zend\ServiceManager\AbstractFactoryInterface {
    public function canCreateServiceWithName($_, $_, $name) {
        // if I'm asked for someBaseClass or a child of someBaseClass, return true: false otherwise
        return ('someBaseClass' === $name || is_subclass_of($name, 'someBaseClass'));
    }

    public function createServiceWithName($locator, $_, $name) {
        // your factory logic here
        // $object = ...
        return $object;
    }
}

您的配置如下:

$serviceManager = [ 'abstract_factories' => [ 'MyAbstractFactory' ] ];

使用具体的factories,您必须为每个扩展类(AFAIK)重复相同的功能,这将是一个难以维护(IMO)。上面的抽象工厂模式基本上说:给我一个课,我会反思它是否是我关心的基类,如果是,我会经营我的工厂来获得它

More info on abstract_factories if you've never used it before.