CodeIgniter: How to pass variables to a model whil

2019-08-02 11:47发布

问题:

In CI, I have a model...

<?php

class User_crud extends CI_Model {

var $base_url;
var $category;
var $brand;
var $filter;
var $limit;
var $page_number;

public function __construct($category, $brand, $filter, $limit, $page_number) {
    $this->base_url = base_url();
    $this->category = $category;
    $this->brand = $brand;
    $this->filter = $filter;
    $this->limit = $limit;
    $this->page_number = $page_number;
}

public function get_categories() {
    // output
    $output = "";
    // query
    $this->db->select("name");
    $this->db->from("categories");
    $query = $this->db->get();
    // zero
    if ($query->num_rows() < 1) {
        $output .= "No results found";
        return $output;
    }
    // result
    $output .= "<li><a class=\"name\">Categories</a></li>\n";
    foreach ($query->result_array as $row) {
        $output = "<li><a href=\"\">{$row['name']}</a></li>\n";
    }
    return $output;
}

while I am calling this in my controller...

<?php

class Pages extends CI_Controller {

// home page

public function home() {
}

// products page

public function products($category = "cell phones", $brand = "all", $filter = "latest") {
    // loading
    $this->load->model("user_crud");
    // 
}

Now, How can I pass the $category, $brand and $filter variables to the user_crud model while loading/instantiation?

回答1:

You shouldn't be using your model like this, just pass the items you need for the functions you require:

$this->load->model("user_crud");

$data['categories'] = $this->user_crud->get_categories($id, $category, $etc);

I would suggest (after seeing your code) that you study the fantastic codeigniter userguide as it has really good examples, and you just went a totally different way (treating model like an object). Its more simple sticking to how it was designed vs what you are doing.



回答2:

You can not. A better idea would be to setup some setters in your model class along with some private vars and set them after loading the model.

if you return $this from the setters you can even chain them together like $this->your_model->set_var1('test')->set_var2('test2');