Good practices Codeigniter

Asked

Viewed 610 times

2

I see several programmers calling all views to build a page in the example controller:

$this->load->view('head',$var);
$this->load->view('home');
$this->load->view('script');
$this->load->view('fim_html');

<html>
  <?php $this->load->view('head');?>
  <body>
    <?php echo $conteudo ;?>
  </body>
    <?php $this->load->view('script');?>
  </html>

I know it works the same way, but does it get in the way of something? (besides code organization)

How best to use code insertion in the Controller?

2 answers

3


Really add a lot view in controller is not very good, so I ended up finding a library very simple that I use.

To use the library create the file Template.php in application/views/Template.php and add the following code:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Template {
    var $template_data = array();

    function set($name, $value)
    {
        $this->template_data[$name] = $value;
    }

    function load($template = '', $view = '' , $view_data = array(), $return = FALSE)
    {               
        $this->CI =& get_instance();
        $this->set('contents', $this->CI->load->view($view, $view_data, TRUE));         
        return $this->CI->load->view($template, $this->template_data, $return);
    }
}

Add to file application/config/autoload.php the library to load with application

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

Create the file php template. (or the nomenclature you want) in the folder view and add the following code as test:

<html>
<body>
    <div id="contents"><?= $contents ?></div>
</body>
</html>

The variable $meet is where the view which you wish will be inserted. As an example, I created a view with the name about php. with the following code:

<h1>About</h1>
<p>I'm so human!</p>

Now to use the add template on controller:

$this->template->load('template', 'about');

Where:

  • template : Template file name created in folder view;
  • about : Name of the file that contains the content you want to insert into the variable $meet.

If you want to add data that will be used in view, just add the array as the third parameter, as shown in the example:

$this->template->load('template', 'about', array(‘titulo’=> “Titulo da pagina”));

I hope I’ve helped.

  • All right, yes, I will edit the answer

2

There is no better way. There is n way to do something. I particularly think it’s bad to keep loading too many Views in the Controller.

I started studying Codeigniter coming from the background ASP.NET MVC. There has the concept of Masterpage/Layout. I was able to do something close to that with Codeigniter.

I have a masterpage which has the basic structure of HTML, it will load a View to Menu, Footer, and will also load another View which is content itself.

masterpage.php

<?php
  defined('BASEPATH') OR exit('No direct script access allowed');

?>

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?=$viewtitle?></title>
    <link href="<?=base_url('/assets/css/bootstrap.min.css')?>" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  </head>
  <body>

    <?php $this->load->view("menu"); ?>

    <div class="container">
        <?php
          // aqui serão carregadas as views parciais
          $this->load->view($viewname);
         ?>
    </div>

    <?php $this->load->view("rodape"); ?>

    <script src="<?=base_url('/assets/js/bootstrap.min.js')?>"></script>
    <script src="<?=base_url('/assets/js/util.js')?>"></script>
  </body>
</html>

For this I created a Controller in the Core folder

My_controller.php

class BaseController extends CI_Controller {

  // variavel que será retornada para as views
  // irá conter as informações necessárias para a view manipular as informações
  protected $data;

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

    // declara o array que contem as informacoes que vao para a view
    $this->data = array();
  }

  public function setData($nome, $valor) {
    $this->data[$nome] = $valor;
  }

  protected function setView($nome, $titulo) {
    $this->setData("viewname", $nome);
    $this->setData("viewtitle", $titulo);
  }

  public function loadView($nome, $titulo) {
    $this->setView($nome, $titulo);
    $this->load->view("masterpage", $this->data);
  }

}

I use it like this

class Produto extends BaseController {

   public function listarProdutos(){
      $this->load->model("ProdutoModel");
      $this->setData("produtos", $this->ProdutoModel->listar());

      // criei uma view chamada listagemProdutos.php
      // ela será carregada dentro da masterpage.php
      $this->loadView("listagemProdutos", "Listagem de Produtos");
   }  
}

listProducts.php

<ul>
<?php foreach($produtos as $produto) {?>
  <li><?=$produto->nome?></li>
<?php } ?>
</ul>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.