【问题标题】:Codeigniter call controller method from modelCodeigniter 从模型调用控制器方法
【发布时间】:2017-10-06 09:38:52
【问题描述】:

我有两个控制器和一个模型,如下所示,我想在侧面模型中调用第二个控制器方法。但我不知道怎么称呼它。

1) 控制器1

   class controller1 extends CI_Controller {

    function __construct() {
        parent::__construct();

        $this->load->model('job');
    }

    public function getjob() {
        $this->job->check_payment();
    }

}

2) Paypal.php(控制器)

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Paypal extends CI_Controller {

    function __construct() {
        parent::__construct();

        $this->load->model('job');

        // Load helpers
        $this->load->helper('url');

        // Load PayPal library
        $this->config->load('paypal');

        $config = array(
            'Sandbox' => $this->config->item('Sandbox'),
            'APIUsername' => $this->config->item('APIUsername'),
            'APIPassword' => $this->config->item('APIPassword'),
            'APISignature' => $this->config->item('APISignature'),
            'APISubject' => '',
            'APIVersion' => $this->config->item('APIVersion')
        );

        // Show Errors
        if ($config['Sandbox']) {
            error_reporting(E_ALL);
            ini_set('display_errors', '1');
        }

        $this->load->library('Paypal_pro', $config);
    }

    function sendPayemnt() {
        echo "Hello...";
    }

}

2) Job.php(模型)

class Job extends CI_Model {

    function check_payment() {
        // I want to call method of Paypal controller here...
    }

}

我希望有人帮助我解决它。 谢谢,

【问题讨论】:

  • 为什么要脱离 Codeigniter 的结构?
  • 编写一个辅助函数而不是控制器并从模型中调用它。这是 Codeigniter 的正确结构。
  • 我知道这不是有效的编码结构,但这是满足我要求的唯一方法。

标签: php codeigniter


【解决方案1】:

虽然在技术上是可行的,但如果您认为需要这样做,则表明您的应用程序设计存在缺陷。

控制器层是应用程序的主干,用于处理来自用户的请求、与模型层通信以及将视图中的输出拼接在一起。您的模型层应该对控制器和视图视而不见,而只处理数据操作。这是对 MVC 模式的过度简化的解释(您可以在其他地方找到相关资源)。

你可以这样使用:

class controller1 extends CI_Controller{

public function testsample(){
        $this->load->model('modal1');
        $stations=$this->modal1->getController();
        echo "<pre>"; print_r($stations);exit;
    }

    public function getData(){
        $ta=array(0=>'Sample',1=>'test');
        return $ta;
    }
}

模态:

class modal1 extends CI_Model {
   function getController()
   {
        $controllerInstance = & get_instance();
        $controllerData = $controllerInstance->getData();
        return $controllerData;
   }
}

输出:

Array
(
    [0] => Sample test cases
    [1] => test
)

我将以 controller1/testsample 的身份访问我的控制器操作 你也可以使用 curl 来调用控制器动作

【讨论】:

  • 您好,抱歉,我是 codeigniter 的新手。所以不知道如何在我的情况下使用您的答案?你能解释一下吗?谢谢,
  • @Hardik :我已经更新了示例,现在检查一下。我希望现在很清楚。如果它解决了您的问题,请接受答案并投票。
  • 感谢您的回答和更新。抱歉,我已经更新了我的问题。如果可能的话,请您检查一下。我感谢您的帮助。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多