我无法理解工厂的实际运作方式。我准备了短文件来测试它的表单元素。
Application / config / module.config.php
<?php
namespace Application;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
use Application\Route\StaticRoute;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Application\Form\Factory\AbcFormFactory;
use Application\Form\AbcForm;
return [
'form_elements' => [
'factories' => [
AbcForm::class => AbcFormFactory::class,
],
],
//(...)
];
Application / src / Form / Factory / AbcFormFactory.php
<?php
namespace Application\Form\Factory;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use Application\Form\AbcForm;
class AbcFormFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return new AbcForm("It works");
}
}
应用/ SRC /窗体/ AbcForm.php
<?php
namespace Application\Form;
use Zend\Form\Element;
use Zend\Form\Form;
use Zend\Hydrator\ClassMethods as ClassMethodsHydrator;
use Zend\InputFilter\InputFilter;
class AbcForm extends Form
{
public function __construct($letter='no factory')
{
die($letter);
}
}
上面的代码显示no factory
,因此忽略工厂。如果没有被忽略,它将显示It works
。
如何为form_elements创建合适的工厂?
更新 我在控制器中调用表单:
<?php
namespace Application\Controller;
use Application\Form\AbcForm;
use Zend\Mvc\Controller\AbstractActionController;
class AbcController extends AbstractActionController
{
public function indexAction()
{
$form = new AbcForm();
}
}
什么触发器形成工厂__invoke方法?我认为,当通过 new 实现表单类时,应该运行表单工厂__invoke方法。或者不是?