php - 如何访问 ZF2 Field Set 中的数据库适配器?

标签 php zend-framework zend-framework2 zend-form zend-db

我遵循了一个示例,想将数据库适配器传递给字段集以创建下拉菜单。

下面的代码是我调用字段集的方式。
我如何访问 BrandFieldset 类中的数据库适配器?

$this->add(array(
    'type' => 'Application\Form\BrandFieldset',
    'name' => 'brand',
    'options' => array(
        'label' => 'Brand of the product',
    ),
));

最佳答案

实例化字段集是 FormElementManager 的责任.当您尝试访问表单、表单元素或字段集时,FormElementManager 知道在哪里可以找到它以及如何创建它。此行为总结在 Default Services 中框架部分。

由于访问表单元素的正确方法是从 FormElementManager 中检索它们,因此我会编写一个 BrandFieldsetFactory 来注入(inject)该 DB 适配器或进一步依赖于构造字段集以实现此目的。

ZF3 友好的 fieldset 工厂看起来像:

<?php
namespace Application\Form\Factory;

use Application\Form\BrandFieldset;
use Interop\Container\ContainerInterface;

class BrandFieldsetFactory
{
    /**
     * @return BrandFieldset
     */
    public function __invoke(ContainerInterface $fem, $name, array $options = null)
    {
        // FormElementManager is child of AbstractPluginManager 
        // which makes it a ContainerInterface instance
        $adapter = $fem->getServiceLocator()->get('Your\Db\Adapter');
        return new BrandFieldset($adapter);
    }
}

此时,BrandFieldset 应该扩展 Zend\Form\Fieldset\Fieldset,它的构造函数可能如下所示:

private $dbAdapter;

/**
 * {@inheritdoc}
 */
public function __construct(My/Db/Adapter $db, $options = [])
{
    $this->dbAdapter = $db;
    return parent::__construct('brand-fieldset', $options);
}

最后,在 module.config.php 文件中,我有一个配置告诉 FormElementManager 关于这个工厂:

<?php

use Application\Form\BrandFieldset;
use Application\Form\Factory\BrandFieldsetFactory;

return [
    // other config

    // Configuration for form element manager
    'form_elements' => [
        'factories' => [
            BrandFieldset::class => BrandFieldsetFactory::class
        ],
    ],
];

HINT: The BrandFieldset::init() method will be called automatically by FormElementManager after construction. You can put any post-initialization logic into this method.

关于php - 如何访问 ZF2 Field Set 中的数据库适配器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41782476/

相关文章:

zend-framework - 多重/嵌套 "select where"与 Zend_Db_Select

zend-framework - 每个月的第一天

php - zf2 表单和对象绑定(bind),不清除未传递的值

zend-framework2 - Zend 2 : Unit tests for form class

php - Resteasy 服务需要 2 个 json 对象

php - 将图像拖放到 Web 表单中

php - Zend-1048 列 'member_login' 不能为空

php - 从 Zend framework 2 开始,找不到类错误

php - 如何根据高度调整图像大小,如 google plus 中的图像并使其响应

php - CakePHP 基本身份验证和 jQuery