这是我的控制器:
class Search extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('search_model');
$this->search_model->search_result = $_POST;
}
public function index()
{
$data['results'] = $this->search_model->get_results();
$this->load->view('search_results', $data);
}
这是我的模型:
class Search_model extends CI_Model {
protected $search_query;
function __construct($search_query)
{
parent::__construct();
$this->load->database();
$this->search_query = $search_query;
}
但这似乎不起作用。我想做的是将发布的表单($_POST)传递给我的模型,然后用它做一些事情。但将$_POST传递给我模型的每个方法似乎很麻烦。我的计划是提取用$_POST发送的变量,并将其构造为$website_url、$text_query等属性,然后在方法中用$this->website_url调用这些变量;
我对CodeIgniter还比较陌生,所以只需要掌握基本的
为了您的特殊目的,您可以尝试以下代码
控制器:
class Search extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('search_model');
$this->init();
}
private function init()
{
$this->search_model->init( $this->input->post() );
}
public function index()
{
$data['results'] = $this->search_model->get_results();
$this->load->view('search_results', $data);
}
型号:
class Search_model extends CI_Model {
protected $search_query;
function __construct()
{
parent::__construct();
$this->load->database();
}
public function init( $search_query )
{
$this->search_query = $search_query;
}
您有protected $search_query;
,无法从控制器访问它。您必须将其更改为public
,或者为其创建getter和setter,或者根据您的域/业务逻辑仅创建getter。
它应该是显而易见的,因为你应该得到一个错误说
致命错误:无法访问文件some/path/to/file中受保护的属性!
不要将"搜索查询"放在模型构造函数中。
控制器:
class Search extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('search_model');
}
public function index()
{
if ($this->input->server('REQUEST_METHOD') == 'POST')
{
// you should probably validate/clean the post data instead
// of sending it straight to the model
$results = $this->search_model->get_where($_POST);
}
else
{
// if it's not a post, you probably need something...
// either here, or somewhere in your view to handle empty data
$results = array();
}
$data['results'] = $results
$this->load->view('search_results', $data);
}
您的型号:
class Search_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->database(); // <--- you may want to autoload 'database' library
}
function get_where($where)
{
$this->db->where($where);
// add select, order, joins, etc here
return $this->db->get('mytable'); // whatever your table name is
}