【问题标题】:How to create a dummy Controller in Command Shell pass to Component CakePHP 2.4.3如何在命令外壳中创建一个虚拟控制器传递给组件 CakePHP 2.4.3
【发布时间】:2021-08-28 00:07:14
【问题描述】:

我使用的是 CakePHP 2.4.3

我在 Command Shell PhulyShell.php 中的代码

<?php
App::uses('ComponentCollection', 'Controller');
App::uses('HopeeComponent', 'Controller/Component');

class PhulyShell extends AppShell {

    public $components = array('Hopee');

    public function initialize() {
        $collection = new ComponentCollection();
        $this->Hopee = new HopeeComponent($collection);
    }
}

HopeeComponent.php 以前是别人写的,我无权编辑。 在文件里面有一段代码

public function __construct(ComponentCollection $collection, $settings = array()) {
     if($this->_Controller->request != null){
        $shortcut_app_flag = $this->_Controller->request->query('phuly_app');
     }
}

因为没有控制器会抛出错误$this->_Controller

Notice Error: Trying to get property of non-object in [cakephp-2.4.3/phuly/Controller/Component/HopeeComponent.php, line 112]

我知道一种解决方案是将控制器传递给它

<?php
App::uses('ComponentCollection', 'Controller');
App::uses('HopeeComponent', 'Controller/Component');
App::uses('AppController', 'Controller');
App::uses('TestController', 'Controller');

class PhulyShell extends AppShell {

    public $components = array('Hopee');

    public function initialize() {
        $collection = new ComponentCollection();
        $collection->init(new TestController);
        $this->Hopee = new HopeeComponent($collection);
    }
}

它可以工作并且没有显示通知错误,但我不想创建文件TestController.php,我不能使用AppController.php

有没有办法将虚拟控制器传递给组件而不在 Shell 命令中创建文件控制器?

谢谢大家!

【问题讨论】:

  • 这真的不是你应该做的。告诉那些说您不允许编辑文件的人,他们执行此类限制是错误的,因为这将导致您不得不编写错误的代码。如果您需要在组件和 shell 命令中使用相同的代码,那么您应该将该代码移动到两个层都可以使用的单独服务中!

标签: php cakephp cakephp-2.4 cakephp-2.x


【解决方案1】:

我自己找到了答案,只是使用Controller,我没有注意到这一点我很笨

   <?php
    App::uses('ComponentCollection', 'Controller');
    App::uses('HopeeComponent', 'Controller/Component');
    App::uses('Controller', 'Controller');
    
    class PhulyShell extends AppShell {
    
        public $components = array('Hopee');
    
        public function initialize() {
            $collection = new ComponentCollection();
            $collection->init(new Controller);
            $this->Hopee = new HopeeComponent($collection);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    相关资源
    最近更新 更多