【问题标题】:Fetch data from a Core Controller in CodeIgniter在 CodeIgniter 中从核心控制器获取数据
【发布时间】:2018-05-22 05:17:07
【问题描述】:

我正在开发一个社交网络应用。 我面临一个问题,我试图从数据库中名为 users 的表中获取名称和用户名。 为了能够在不单独访问所有控制器的情况下做到这一点,我必须创建一个名为 MY_Controller 的核心控制器。

这是问题(MY_Controller 没有公共 $users):

<?php

class MY_Controller extends CI_Controller
{

//public $users = array('username' => $this->input->post('username')); 


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

        //Get user data to make it available for both Admin and Public Controllers
        $this->load->model('User_model');
        $this->users = $this->User_model->get_list();

        //Load Menu Library
        $this->load->library('menu');
        $this->pages = $this->menu->get_pages();

        // Brand/Logo
        $this->favicon = 'https://blogpersonal.net/wp-content/uploads/2017/08/favicon-v2-150x150.png';
        $this->brand = 'Some Name';
        $this->description = 'Some Description';
        $this->credits = 'https://blogpersonal.net/';
        $this->version = '1.1.1';
    }
}

class Admin_Controller extends MY_Controller
{

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

        if (!$this->session->is_admin) {
            redirect('admin/login');
        }

        //some code here

    }
}

class Public_Controller extends MY_Controller{
    function __construct(){
        parent::__construct();

        //some code here

    }

}

class Social_Controller extends MY_Controller
{

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

        if (!$this->session->is_member) {
            redirect('dashboard/login');
        }

        //some code here

    }
}

如您所见,我使用 __construct 函数加载了 User_model 以使其可用并在所有控制器中使用。

我想在一个名为模板的文件夹中获取数据。 views>templates>any document 但是当我尝试在这样的视图中获取它时:

    <?php if($this->users) : ?>
        <li class="dropdown user user-menu">
          <!-- Menu Toggle Button -->
          <a href="#" class="dropdown-toggle" data-toggle="dropdown">
            <!-- The user image in the navbar-->
            <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="user-image" alt="User Image">
            <!-- hidden-xs hides the username on small devices so only the image appears. -->
            <span class="hidden-xs"><?php echo $this->users['username']; ?></span>
          </a>

        </li>
    <?php endif; ?>

这是老错误。它向我显示了一个错误。难道我做错了什么?有人可以解释我如何解决它。这是我第一次无法获取数据。 这是我得到的结果:

遇到了 PHP 错误

严重性:通知

消息:未定义变量:用户

文件名:Templates/public.php

行号:161

回溯:

文件: C:\xampp\htdocs\codeigniter\application\views\Templates\public.php 行:161 函数:_error_handler

文件:C:\xampp\htdocs\codeigniter\application\libraries\Template.php 行:34 功能:查看

文件:C:\xampp\htdocs\codeigniter\application\controllers\Pages.php 行:12 功能:加载

文件:C:\xampp\htdocs\codeigniter\index.php 行:315 功能: 需要一次

这是我的模型(User_model),以备不时之需:

<?php

class User_model extends CI_MODEL
{

    function __construct()
    {
        parent::__construct();
        $this->table = 'users';
    }

    public function get_list()
    {
        $query = $this->db->get($this->table);
        return $query->result();
    }

    public function get($id)
    {
        $this->db->where('id', $id);
        $query = $this->db->get($this->table);
        return $query->row();
    }

    public function add($data)
    {
        $this->db->insert($this->table, $data);
    }

    public function update($id, $data)
    {
        $this->db->where('id', $id);
        $this->db->update($this->table, $data);
    }

    public function delete($id)
    {
        $this->db->where('id', $id);
        $this->db->delete($this->table);
    }

    public function login($username, $password)
    {
        $this->db->select('*');
        $this->db->from($this->table);
        $this->db->where('username', $username);
        $this->db->where('password', $password);
        $this->db->limit(1);

        $query = $this->db->get();

        if ($query->num_rows() == 1) {
            return $query->row()->id;
        } else {
            return false;
        }
    }
}

现在有了向我建议的更改,它现在显示一个新错误:

新错误:

遇到了 PHP 错误

严重性:通知消息:未定义索引:用户名文件名: Templates/public.php 行号:168

回溯:

文件: C:\xampp\htdocs\codeigniter\application\views\Templates\public.php 行:168 函数:_error_handler

文件:C:\xampp\htdocs\codeigniter\application\libraries\Template.php 行:34 功能:查看

文件: C:\xampp\htdocs\codeigniter\application\controllers\public\Dashboard.php 行:13 功能:加载

文件:C:\xampp\htdocs\codeigniter\index.php 行:315 功能: 需要一次

现在,如果取消注释核心控制器(MY_Controller)中的公共 $users,它也会向我显示一个新错误:

公共 $users 超出 __construct 函数的新错误

致命错误:常量表达式在 C:\xampp\htdocs\codeigniter\application\core\MY_Controller.php 上线 6 遇到 PHP 错误

严重性:编译错误

消息:常量表达式包含无效操作

文件名:core/MY_Controller.php

行号:6

回溯:

这是我试图将数据获取到的图片:

我做错了吗?感谢您的帮助。

这里是视图(public.php)文件:

<ul class="nav navbar-nav">
          <?php if(!$this->session->is_member) : ?>
          <li><?php echo anchor('public/users/login', 'Login'); ?></li>
          <li><?php echo anchor('public/users/register', 'Register'); ?></li>
          <?php else : ?>
            <!-- Messages: style can be found in dropdown.less-->
            <li class="dropdown messages-menu">
              <!-- Menu toggle button -->
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                <i class="fa fa-envelope-o"></i>
                <span class="label label-success">4</span>
              </a>
              <ul class="dropdown-menu">
                <li class="header">You have 4 messages</li>
                <li>
                  <!-- inner menu: contains the messages -->
                  <ul class="menu">
                    <li><!-- start message -->
                      <a href="#">
                        <div class="pull-left">
                          <!-- User Image -->
                          <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">
                        </div>
                        <!-- Message title and timestamp -->
                        <h4>
                          Support Team
                          <small><i class="fa fa-clock-o"></i> 5 mins</small>
                        </h4>
                        <!-- The message -->
                        <p>Why not buy a new awesome theme?</p>
                      </a>
                    </li>
                    <!-- end message -->
                  </ul>
                  <!-- /.menu -->
                </li>
                <li class="footer"><a href="#">See All Messages</a></li>
              </ul>
            </li>
            <!-- /.messages-menu -->
            <!-- Notifications Menu -->
            <li class="dropdown notifications-menu">
              <!-- Menu toggle button -->
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                <i class="fa fa-bell-o"></i>
                <span class="label label-warning">10</span>
              </a>
              <ul class="dropdown-menu">
                <li class="header">You have 10 notifications</li>
                <li>
                  <!-- Inner Menu: contains the notifications -->
                  <ul class="menu">
                    <li><!-- start notification -->
                      <a href="#">
                        <i class="fa fa-users text-aqua"></i> 5 new members joined today
                      </a>
                    </li>
                    <!-- end notification -->
                  </ul>
                </li>
                <li class="footer"><a href="#">View all</a></li>
              </ul>
            </li>
            <!-- Tasks Menu -->
            <li class="dropdown tasks-menu">
              <!-- Menu Toggle Button -->
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                <i class="fa fa-flag-o"></i>
                <span class="label label-danger">9</span>
              </a>
              <ul class="dropdown-menu">
                <li class="header">You have 9 tasks</li>
                <li>
                  <!-- Inner menu: contains the tasks -->
                  <ul class="menu">
                    <li><!-- Task item -->
                      <a href="#">
                        <!-- Task title and progress text -->
                        <h3>
                          Design some buttons
                          <small class="pull-right">20%</small>
                        </h3>
                        <!-- The progress bar -->
                        <div class="progress xs">
                          <!-- Change the css width attribute to simulate progress -->
                          <div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100">
                            <span class="sr-only">20% Complete</span>
                          </div>
                        </div>
                      </a>
                    </li>
                    <!-- end task item -->
                  </ul>
                </li>
                <li class="footer">
                  <a href="#">View all tasks</a>
                </li>
              </ul>
            </li>
            <!-- User Account Menu -->
            <?php if($this->users) : ?>
                <li class="dropdown user user-menu">
                  <!-- Menu Toggle Button -->
                  <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                    <!-- The user image in the navbar-->
                    <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="user-image" alt="User Image">
                    <!-- hidden-xs hides the username on small devices so only the image appears. -->
                    <span class="hidden-xs"><?php echo $this->users['username']; ?></span>
                  </a>
                  <ul class="dropdown-menu">
                    <!-- The user image in the menu -->
                    <li class="user-header">
                    <img src="<?php echo base_url(); ?>assets/img/user2-160x160.jpg" class="img-circle" alt="User Image">
                      <p><?php echo $this->users['name']; ?> - Web Developer<small>Member since Nov. 2012</small></p>
                    </li>
                    <!-- Menu Body -->
                    <li class="user-body">
                      <div class="row">
                        <div class="col-xs-4 text-center">
                          <a href="#">Followers</a>
                        </div>
                        <div class="col-xs-4 text-center">
                          <a href="#">Sales</a>
                        </div>
                        <div class="col-xs-4 text-center">
                          <a href="#">Friends</a>
                        </div>
                      </div>
                      <!-- /.row -->
                    </li>
                    <!-- Menu Footer-->
                    <li class="user-footer">
                      <div class="pull-left">
                        <a href="#" class="btn btn-default btn-flat">Profile</a>
                      </div>
                      <div class="pull-right">
                        <a href="<?php echo base_url(); ?>public/users/logout" class="btn btn-default btn-flat">Sign out</a>
                      </div>
                    </li>
                  </ul>
                </li>
            <?php endif; ?>
            <li>
                <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a>
            </li>
          <?php endif; ?>
          </ul>

【问题讨论】:

  • 您应该用作属性。公共 $users;并且在您的构造中($this->users = $this->User_model->get_list();。当您在函数中声明变量时,只能在该函数中访问(或者如果您作为参数传递给另一个)。
  • 好吧,我按照您在 __construct 函数中的建议进行了更改,但如果我执行 foreach,它就可以工作;做一个 if 条件仍然不起作用。将其用作财产是什么意思?我尝试公开我的 __construct 函数,但我看不出有任何区别。感谢您的帮助。
  • @Kevin - 你会启动谷歌并查找类的属性是什么,然后“啊哈”时刻会实施 webmasterdo 的建议。那么你能展示你更新后的代码吗?
  • 好的,那么我们可以看到加载视图的代码吗?这就是您的问题所在
  • 你出于什么原因尝试 - public $users = array('username' => $this->input->post('username'));公共 $users=array();是所有你需要定义和初始化它。你不能在那里运行代码。

标签: php mysql codeigniter fetch codeigniter-3


【解决方案1】:

你目前有这个...而我这里只显示 sn-ps...

class MY_Controller extends CI_Controller
{
    function __construct()
    {
        parent::__construct();

        //Get user data to make it available for both Admin and Public Controllers
        $this->load->model('User_model');
        $data['users'] = $this->User_model->get_list();

<<<<snip>>>>

建议您将本地定义的 $data['users'] 转换为 "Property"

所以我们现在有两个变化...

1 声明属性

2 设置属性。

class MY_Controller extends CI_Controller
{
    public $users = array(); // Add the property $user, safe def of an empty array

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

        //Get user data to make it available for both Admin and Public Controllers
        $this->load->model('User_model');
        //$data['users'] = $this->User_model->get_list();
        // Give the property something to share. 
        $this->users = $this->User_model->get_list();


    <<<<snip>>>>

现在所有扩展 MY_Controller 的控制器现在都可以访问 $this->在 MY_Controller 中创建的用户...

所以你引用 $this->users 你想在哪里使用它。

我建议您首先阅读类、属性、方法和继承。通常这足以让你变得危险。这需要一点时间来适应,但值得付出努力......

更新: 在你调用你的视图的控制器中,你会做 $data['users'] = $this->users;

在您看来,您现在像以前一样将其称为 $users->field_name。 我们所做的只是在您的基类中定义 $users,它现在可以作为 $this->users 访问,因此您的所有扩展 MY_Controller 类的控制器/方法都可以访问它。

【讨论】:

  • 它显示了同样的错误:/。感谢您的帮助
  • 那么什么在 public.php 中,因为这是发生错误的地方。能否请您出示该代码。
  • 我更新了我的问题,你可以在那里看到我到目前为止的内容。感谢您的帮助,也许我加载视图不正确?
  • 是的 - 在你的控制器中你可以设置 $data['users'] = $this->users;并将其传递到您的视图中。然后你参考 $users->the_field_name。您应该阅读 Codeigniter 用户指南中的视图等。
  • 一开始就是这样,但没有成功。
【解决方案2】:

你目前有这个。

class MY_Controller extends CI_Controller
{

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

    //Get user data to make it available for both Admin and Public Controllers
    $this->load->model('User_model');
    $data['users'] = $this->User_model->get_list();

你应该使用 $this->data['users'] 代替 $data

class MY_Controller extends CI_Controller
{

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

    //Get user data to make it available for both Admin and Public Controllers
    $this->load->model('User_model');
    $this->data['users'] = $this->User_model->get_list();

当你加载你的视图时,使用下面的代码

$this->load->view('view_name',$this->data);

它将显示存储在父类构造函数中的所有变量(视图中)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多