2012-05-14 22 views
18

Soy muy novato en CodeIgniter, y mientras voy por la I a tener problemas que, en la codificación de procedimiento, eran fáciles de solucionarCodeIgniter: variables globales en un controlador

La edición actual es: Tengo este controlador

class Basic extends Controller { 

    function index(){ 
     $data['title'] = 'Page Title'; 
     $data['robots'] = 'noindex,nofollow'; 
     $data['css'] = $this->config->item('css'); 
     $data['my_data'] = 'Some chunk of text'; 
     $this->load->view('basic_view', $data); 
    } 

    function form(){ 
     $data['title'] = 'Page Title'; 
     $data['robots'] = 'noindex,nofollow'; 
     $data['css'] = $this->config->item('css'); 
     $data['my_other_data'] = 'Another chunk of text'; 
     $this->load->view('form_view', $data); 
    } 
} 

Como se puede ver, algunos elementos de matriz repetir una y otra vez:

$data['title'] = 'Page Title'; 
$data['robots'] = 'noindex,nofollow'; 
$data['css'] = $this->config->item('css'); 

no hay una manera de hacerlos "global" en el controlador, por lo que no tengo escribirlos para eac h función? Algo así como (pero esto me da error):

class Basic extends Controller { 

    // "global" items in the $data array 
    $data['title'] = 'Page Title'; 
    $data['robots'] = 'noindex,nofollow'; 
    $data['css'] = $this->config->item('css'); 

    function index(){ 
     $data['my_data'] = 'Some chunk of text'; 
     $this->load->view('basic_view', $data); 
    } 

    function form(){ 
     $data['my_other_data'] = 'Another chunk of text'; 
     $this->load->view('form_view', $data); 
    } 

} 

Thnaks de antemano!

Respuesta

28

Lo que puede hacer es "variables de clase" que puede accederse desde cualquier método en el controlador. En el constructor, estableces estos valores.

class Basic extends Controller { 
    // "global" items 
    var $data; 

    function __construct(){ 
     parent::__construct(); // needed when adding a constructor to a controller 
     $this->data = array(
      'title' => 'Page Title', 
      'robots' => 'noindex,nofollow', 
      'css' => $this->config->item('css') 
     ); 
     // $this->data can be accessed from anywhere in the controller. 
    }  

    function index(){ 
     $data = $this->data; 
     $data['my_data'] = 'Some chunk of text'; 
     $this->load->view('basic_view', $data); 
    } 

    function form(){ 
     $data = $this->data; 
     $data['my_other_data'] = 'Another chunk of text'; 
     $this->load->view('form_view', $data); 
    } 

} 
+1

@Dalen: Gracias por corregir ese error tipográfico :-) –

+0

¡De nada! – Dalen

+0

¡Gracias! Mientras tanto, me olvidé de la pregunta porque encontré que "$ this-> load-> vars ($ array)" encaja muy bien con mis ejemplos ... de todos modos la solución provista es aún más agradable si tengo que pasar el arreglo entre el métodos de clase – Ivan

15

Puede configurar una propiedad de clase llamada data y luego establecer sus valores predeterminados en el contructor, que es lo primero que se ejecuta cuando se crea una nueva instancia en Basic. Entonces se puede hacer referencia a ella con la palabra clave $this

class Basic extends Controller 
{ 
    var $data = array(); 

    public function __construct() 
    { 
     parent::__construct(); 
     // load config file if not autoloaded 
     $this->data['title'] = 'Page Title'; 
     $this->data['robots'] = 'noindex,nofollow'; 
     $this->data['css'] = $this->config->item('css'); 
    } 

    function index() 
    { 
     $this->data['my_data'] = 'Some chunk of text'; 
     $this->load->view('basic_view', $this->data); 
    } 

    function form() 
    { 
     $this->data['my_data'] = 'Another chunk of text'; 
     $this->load->view('form_view', $this->data); 
    } 
} 
+1

Necesita agregar 'parent :: __ construct();' al constructor para que esto funcione. –

+2

Correcto, y probablemente también cargue el archivo de configuración si aún no está autocargado – Dalen

+0

¡sí! construir resolverá el problema. – rechie

3

bueno gracias Aquí está mi snipet es una variable global que sostiene una vista

/* Location: ./application/core/MY_Controller */ 

class MY_Controller extends CI_Controller { 

    function __construct() 
    { 
     parent::__construct(); 
     $this->data = array(
      'sidebar' => $this->load->view('sidebar', '' , TRUE), 
     ); 
    } 

} 

/* Location: ./application/controllers/start.php */ 
class Start extends MY_Controller { 

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

    public function index() 
    { 
     $data = $this->data; 

     $this->load->view('header'); 
     $this->load->view('start', $data); 
     $this->load->view('footer'); 
    } 
} 
+0

Gracias, eso funciona para mí –

0

¿Por qué no un ayudante de usuario?

del archivo:

/application/helpers/meta_helper.php 

contenido:

<?php 
function meta_data() { 
return array("title" => null, "robots" => "noindex, nofollow"); 
} 

En su controlador:

class Basic extends Controller { 

    function __construct(){ 
     parent::__construct(); 
     $this->load->helper('meta'); 
    }  

    function index(){ 
     $data['meta'] = meta_data(); //associate the array on it's own key; 

     //if you want to assign specific value 
     $data['meta']['title'] = 'My Specific Page Title'; 

     //all other values will be assigned from the helper automatically 

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

Y en su plantilla de vista:

<title><?php $meta['title']; ?></title> 

salida será:

<title>My Specific Page Title</title> 

esperanza que tiene sentido :-)!

0

Aunque ha sido tan largo. Puede ser útil para otros, puede usar $ this-> load-> vars ($ data); en el núcleo MY_controller para hacer que $ data array esté disponible en todas las vistas.

/* Location: ./application/core/MY_Controller */ 

class MY_Controller extends CI_Controller { 

function __construct() 
{ 
    parent::__construct(); 
    $data['title'] = 'Page Title'; 
    $data['robots'] = 'noindex,nofollow'; 
    $data['css'] = $this->config->item('css'); 
    $this->load->vars($data); 
} 

} 

/* Location: ./application/controllers/start.php */ 
class Start extends MY_Controller { 

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

public function index() 
{ 
    $data['myvar'] = "mystring"; 

    $this->load->view('header'); 
    $this->load->view('start', $data); 
    $this->load->view('footer'); 
} 
}