【问题标题】:Yii2 missing required parameter in a constructorYii2 在构造函数中缺少必需的参数
【发布时间】:2015-11-16 08:56:24
【问题描述】:

我创建了一个新的XmlResponseFormatter,现在我想更改rootTag

class newXmlResponseFormatter extends XmlResponseFormatter 
{  
    /**
     * @var string the name of the root element.
     *
     */
    public $rootTag;

    public function __construct($rootTag) {        
        parent::__construct();

        $this->rootTag = $rootTag;        
    }
}

我在控制器中设置了该值:

$xmlFormater = new newXmlResponseFormatter('newRootTag');

在控制器中该值可用,它设置在 $rootTag 中,但它抛出了以下异常:

在实例化“app\components\override\newXmlResponseFormatter”时出现异常 'yii\base\InvalidConfigException' 和消息“缺少必需的参数“rootTag”。在 /var/www/html/Admin/vendor/yiisoft/yii2/di/Container.php:451

有谁知道可能是什么问题? 提前致谢!

【问题讨论】:

    标签: yii2


    【解决方案1】:

    XmlResponseFormatter 中的第一个参数是$config,因为XmlResponseFormatter 扩展了Object 类。你是violated liskov substitution principle

    你应该像这样重写你的构造函数:

    class newXmlResponseFormatter extends XmlResponseFormatter
    {
        /**
         * @var string the name of the root element.
         *
         */
        public $rootTag;
    
        /**
         * newXmlResponseFormatter constructor.
         *
         * @param string $rootTag
         * @param array $config
         */
        public function __construct($rootTag, $config = [])
        {
            $this->rootTag = $rootTag;
    
            parent::__construct($config);
        }
    }
    

    在 yii2 中,您应该您的代码之后调用父构造函数,并在您的代码之前调用父构造函数init

    $config 需要这样简单的配置模型:

    new newXmlResponseFormatter(['rootTag' => 'newRootTag']);
    

    【讨论】:

    • 我按照你说的做了:code class newXmlResponseFormatter extends XmlResponseFormatter { /** * @var string 根元素的名称。 * */ 公共 $rootTag;公共函数 __construct($rootTag, $config = []) { parent::init(); $this->rootTag = $rootTag;父::__construct($config); } }code 控制器:code$xmlFormater = new newXmlResponseFormatter('newRootTag', []);code 但是,我仍然有同样的错误,异常...
    • init 应该在单独的 init 函数中调用 构造函数。从构造函数中删除它,它将起作用:)
    • 还是不行 :( code public function __construct($rootTag, $config = []) { $this->rootTag = $rootTag; parent::__construct($config); } 公共函数 init() { parent::init(); }code
    • 尝试删除构造函数,初始化,并使用它:new newXmlResponseFormatter(['rootTag' => 'newRootTag']);
    • 然后,我可以从我的控制器动态更改该值: $response->formatters['xml']['rootTag'] = "newValue";
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多