Data available for all views in codeigniter

2019-01-17 21:54发布

问题:

I have a variable, contaning data that should be present in the entire site. Instead of passing this data to each view of each controller, I was wondering if there is a way to make this data available for every view in the site.

Pd. Storing this data as a session variable / ci session cookie is not an option.

Thanks so much.

回答1:

Create a MY_Controller.php file and save it inside the application/core folder. In it, something like:

class MY_Controller extends CI_Controller {

   public $site_data;

   function __construct() {
       parent::__construct();
       $this->site_data = array('key' => 'value');
   }
}

Throughout your controllers, views, $this->site_datais now available. Note that for this to work, all your other controllers need to extend MY_Controllerinstead of CI_Controller.



回答2:

You need to extend CI_Controller to create a Base Controller:

https://www.codeigniter.com/user_guide/general/core_classes.html

core/MY_Controller.php

<?php

class MY_Controller extend CI_Controller {

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

         //get your data
         $global_data = array('some_var'=>'some_data');

         //Send the data into the current view
         //http://ellislab.com/codeigniter/user-guide/libraries/loader.html
         $this->load->vars($global_data);

     }  
}

controllers/welcome.php

 class Welcome extend MY_Controller {
      public function index() {
          $this->load->view('welcome');
      }
 }

views/welcome.php

var_dump($some_var);

Note: to get this vars in your functions or controllers, you can use $this->load->get_var('some_var')



回答3:

Set in application/config/autoload.php

$autoload['libraries'] = array('config_loader');

Create application/libraries/Config_loader.php

defined('BASEPATH') OR exit('No direct script access allowed.');

class Config_loader
{
    protected $CI;

    public function __construct()
    {
        $this->CI =& get_instance(); //read manual: create libraries

        $dataX = array(); // set here all your vars to views

        $dataX['titlePage'] = 'my app title';
        $dataX['urlAssets'] = base_url().'assets/';
        $dataX['urlBootstrap'] = $dataX['urlAssets'].'bootstrap-3.3.5-dist/';

        $this->CI->load->vars($dataX);
    }
}

on your views

<title><?php echo $titlePage; ?></title>
<!-- Bootstrap core CSS -->
<link href="<?php echo $urlBootstrap; ?>css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap theme -->
<link href="<?php echo $urlBootstrap; ?>css/bootstrap-theme.min.css" rel="stylesheet">


回答4:

If this is not an Variable(value keep changing) then I would suggest to create a constant in the constant.php file under the config directory in the apps directory, if it's an variable keep changing then I would suggest to create a custom controller in the core folder (if not exist, go ahead an create folder "core") under apps folder. Need to do some changes in other controller as mentioned here : extend your new controller with the "CI_Controller" class. Example

open-php-tag if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class LD_Controller extends CI_Controller { } close-php-tag

Here LD_ is my custom keyword, if you want to change you can change it in config.php file under line# 112 as shown here : $config['subclass_prefix'] = 'LD_'; and extend this class in all your controllers as "class Mynewclass extends LD_Controller.. And in LD_controller you've to write the method in which you want to define the variable/array of values & call that array in all over the application as shown here : defining variable : var $data = array(); Method to get values from db through the Model class:

function getbooks()
{
   $books =   $this->mybooks_model->getbooks(); //array of records
   $this->data = array('books'=>$books);
}

to call this variable in the views : print_r($this->data['books']);); you will get all the array values... here we've to make sure atleast one "$data" parameter needs to be passed if not no problem you can define this $data param into the view as shown here : $this->load->view('mybookstore',$data);

then it works absolutely fine,,, love to share... have a fun working friends



回答5:

you can use $this->load->vars('varname', $data);[ or load data at 1st view only] onse and use in any loaded views after this



回答6:

Use sessions in your controllers

$this->session->set_userdata('data');

then display them in your view

$this->session->userdata('data');

Or include a page in base view file e.g index.php

include "page.php";

then in page.php,

add $this->session->userdata('data'); to any element or div

then this will show on all your views



回答7:

I read all answers, but imho the best approch is via hook:

  1. Create hook, let's get new messages for example:

    class NewMessages {
        public function contact()
        {
            // Get CI instance CI_Base::get_instance();
            $CI = &get_instance(); // <-- this is contoller in the matter of fact
            $CI->load->database();
    
            // Is there new messages?
            $CI->db->where(array('new' => 1));
            $r = $CI->db->count_all_results('utf_contact_requests');
    
            $CI->load->vars(array('new_message' => $r));
        }
    }
    
  2. Attach it to some of the flow point, for example on 'post_controller_constructor'. This way, it will be loaded every time any of your controller is instantiated.

    $hook['post_controller_constructor'][] = array(
        'class'    => 'NewMessages',
        'function' => 'contact',
        'filename' => 'NewMessages.php',
        'filepath' => 'hooks',
        'params'   => array(),
    );
    
  3. Now, we can access to our variable $new_message in every view or template.

As easy as that :)



回答8:

You could override the view loader with a MY_loader. I use it on a legacy system to add csrf tokens to the page where some of the forms in views don't use the builtin form generator. This way you don't have to retrospectively change all your controllers to call MY_Controller from CI_Controller.

Save the below as application/core/MY_Loader.php

<?php
class MY_Loader extends CI_Loader {
    /**
     * View Loader
     *
     * Overides the core view function to add csrf token hash into every page.
     *
     * @author   Tony Dunlop
     *
     * @param   string  $view   View name
     * @param   array   $vars   An associative array of data
     *              to be extracted for use in the view
     * @param   bool    $return Whether to return the view output
     *              or leave it to the Output class
     * @return  object|string
     */
    public function view($view, $vars = array(), $return = FALSE)
    {
        $CI =& get_instance();
        $vars['csrf_token'] = $CI->security->get_csrf_hash();
        return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_prepare_view_vars($vars), '_ci_return' => $return));
    }
}


标签: codeigniter