【问题标题】:How to pass the data to view in codeigniter如何将数据传递到codeigniter中查看
【发布时间】:2015-12-28 18:17:08
【问题描述】:

假设我有一个像这样叫做 home 的控制器

class Home extends CI_Controller{


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

        //load the settings model
        $this->load->Model('settings_model');

        //get the all settings and store it into a variable
        $siteSettings = $this->settings_model->SiteSettings();


        //how to pass the data to view
        $data['site'] = $siteSettings;
    }

    public function index()
    {
        //some code and pass the value to view
        $data["some_item"] = "some value";

        //Load the view
        $this->load->view("home",$data);
    }

    public function SomeMethod1()
    {
        //some code and pass the value to view
        $data["some_item"] = "some value";

        //Load the view
        $this->load->view("home",$data);
    }


    public function SomeMethod2()
    {
        //some code and pass the value to view
        $data["some_item"] = "some value";

        //Load the view
        $this->load->view("home",$data);
    }


}

但我的问题是我想将 $siteSettings 传递给我的每个方法。我不想每次都从 settings_model 获取数据,因为我使用不同的家庭控制器方法。我只想从 __construct() 上的数据库中获取数据,并在调用不同方法时将值传递给每个方法。

我怎样才能做到这一点?我应该使用公共变量并将获取的数据存储到该变量并从不同的方法调用该变量吗?

【问题讨论】:

  • is $siteSettings 是数组还是一个元素??
  • $siteSettings 是一个数组。

标签: php codeigniter


【解决方案1】:

在会话中设置。并且可以访问整个项目。

public function __construct()
{
    parent::__construct();
    $this->session->unset_userdata('site'); # unset on each and every time

    $this->load->Model('settings_model');
    $siteSettings = $this->settings_model->SiteSettings();

    $this->session->set_userdata('site', $siteSettings);  # Set after end of __construct
}

或者这样做

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

    $this->load->Model('settings_model');
    $this->data['site']  = $this->settings_model->SiteSettings();
}

函数中

$this->load->view("name",$this->data);

【讨论】:

  • 我想过这个,但是我有没有其他方法可以实现这个?
  • 因为您的代码$data['site'] 是否传递任何数据??
  • 是的。通过这种方法 ($this->settings_model->SiteSettings();) 我从数据库中提取数据并将其存储到名为 $siteSettings 的变量中
  • 现在它工作正常。谢谢兄弟的帮助。接受。
猜你喜欢
  • 2014-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多