在codeigniter中从控制器到模型的GET或POST值

时间:2016-02-22 13:37:36

标签: php codeigniter codeigniter-3

有没有办法将值从一个控制器传递给模型作为GET或POST

我有1个控制器 V1 和1个型号 Vmodel

class V1 extends CI_Controller {        
    function __construct()
    {
        parent::__construct();
        $this->load->model('Vmodel','',TRUE);
    }
    /* index action */
    public function index()
    {
      $user='abcd';
      $details  = $this->Vmodel->login();
    }       
}       

模型

class V1Modelnew extends CI_Model{
public function __construct() {

    }

          public function login()
          {
            //here, I need to get the user variable as post
            echo $_POST['user'];
          }
}

我需要获得价值' abcd'作为模型中的POST。有什么办法吗?

4 个答案:

答案 0 :(得分:2)

代码中的错误

  1. 您将模型加载为$this->load->model('Vmodel'但您定义的模型为V1Modelnew
  2. 您没有将$user值传递给模型函数
  3. 没有与$_POST['user']
  4. 相关联的值

    在控制器中

    class V1 extends CI_Controller {        
        function __construct()
        {
            parent::__construct();
            $this->load->model('V1Modelnew'); # Changed
        }
    
        public function index()
        {
          $user='abcd';
          $details  = $this->V1Modelnew->login($user); # Changed
        }       
    }
    

    在模型中

    class V1Modelnew extends CI_Model{
    
        public function __construct() 
        {
    
        }
    
        public function login($user) # Changed
        {
            echo $user; # Changed
        }
    }
    

答案 1 :(得分:0)

这里存在架构问题。您不希望模型访问$ _POST或$ _GET中的值。这会将您的模型层耦合到应用程序的HTTP层。

相反,您希望将必要的值作为函数参数传递给模型。

你的控制器:

$details = $this->Vmodel->login('abcd', $_POST['password']);

你的模特:

public function login($username, $password) {
    // return $details
}

答案 2 :(得分:0)

尝试这种方式

class V1 extends CI_Controller {        
    function __construct()
    {
        parent::__construct();
        $this->load->model('Vmodel','',TRUE);
    }
    /* index action */
    public function index()
    {
      $user=$this->input->post('user');
      $details  = $this->Vmodel->login($user);
    }       
}

型号:

class Vmodel extends CI_Model{ //use Vmodel NOT V1Modelnew 
public function __construct() {

    }

          public function login($user)
          {

            echo $user;
          }
}

如果您想要用户postget,则需要以这种方式在Controller中执行此操作:

$value = $this->input->post('value_name'); // for Post
$value = $this->input->get('value_name'); // for GET

如需了解更多信息,请阅读documentation

答案 3 :(得分:0)

控制器

class V1 extends CI_Controller {        
    function __construct()
    {
        parent::__construct();
        $this->load->model('Vmodel','',TRUE);
    }
    /* index action */
    public function index()
    {
      $user='abcd';
      $details  = $this->Vmodel->login($_POST);
    }       
}       

模型

class V1Modelnew extends CI_Model{
public function __construct() {

    }

          public function login($data='')
          {
            //here, I need to get the user variable as post
            echo $_POST['user'];
          }
}
相关问题