ZF2 Autoloader:在扩展类中使用基类的工厂 [英] ZF2 Autoloader: Use factory for base class on extended classes as well
问题描述
如果我想对任何扩展我的基类的类使用相同的工厂,我想把基类工厂变成一个命名的函数,还是有更好的方法来做这个?
If I wanted to use the same factory for any class that extended my base class, would I want to turn the base class factory into a named function, or is there a better way to do this?
$serviceManager => array(
'factories' => array(
'someBaseClass' => function($thisServiceManager) {
$db = $thisServiceManager->get('db');
$thisBaseClass = new \myNamespace\thisBaseClass($db);
return $thisBaseClass;
},
),
);
EDIT
接受,这里是我测试的代码工作。
Further to the answer I accepted, here's the code I've tested that works.
类文件
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',
),
);
推荐答案
如果我要关注您的问题,扩展 someBaseClass
的类,你想让它们都以相同的方式制造吗?
If I'm following your question, you have a bunch of classes that extend someBaseClass
, and you want them all to be manufactured in the same way?
,那么这听起来像是在 ServiceManager
中使用 abstract_factories
组件的好机会。伪代码如下:
If so, then that sounds like a good opportunity to use the abstract_factories
component in the ServiceManager
. The pseudo-code would be like:
// 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' ] ];
使用具体的工厂
必须对每个扩展类(AFAIK)重复相同的功能,这将是一个痛苦的维护(IMO)。上面的抽象工厂模式基本上说:给我一个类,我会反映它是否是我关心的基类,如果是,我将运行我的工厂来获得它。
Using the concrete factories
, you'd have to repeat the same function for each extended class (AFAIK), which would be a pain to maintain (IMO). The abstract factory pattern above basically says: give me a class, I'll reflect it to see if it's the base class I care about and, if so, I'll run my factory to get it.
更多信息 abstract_factories
,如果您以前从未使用过。
More info on abstract_factories
if you've never used it before.
这篇关于ZF2 Autoloader:在扩展类中使用基类的工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!