bernacamargo/template_codeigniter-3.1.10

CodeIgniter框架的模板

v1.2 2019-06-05 15:54 UTC

This package is auto-updated.

Last update: 2024-09-22 03:54:21 UTC


README

CodeHead是一个具有优化功能的库,旨在通过实用方法减少代码重复并提高生产力。我们将使用Twitter Bootstrap 4JQuery 3.4.1Font-awesome 5.8.1Toastr核心系统类来操作Codeigniter 3的功能。

摘要

安装

作为ZIP下载或克隆本地环境中的存储库,然后只需进行应用程序配置即可开始使用它来开发您的Web系统。

配置

连接到数据库

application/config/database.php中配置数据库凭据

  • YOURHOSTDB_USERNAMEDB_PASSWORDDB_NAME的值分别替换为主机、用户名、密码和数据库的名称
$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'YOURHOST',
    'username' => 'DB_USERNAME',
    'password' => 'DB_PASSWORD',
    'database' => 'DB_NAME',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

辅助函数

模板中包含一些预定义的PHP函数,以简化您的开发。

  • debug()
  • str_slug()
  • format_money()
  • validate_card()
  • time_ago()
  • hextorgba()

函数

  • debug()
/**
 * debug
 *
 * Exibe o conteúdo detalhado e identado de uma variável no PHP
 * 
 * @param  Array $arry
 * @return void
 */
function debug($arry) {
	echo '<pre>' . var_export($arry, TRUE) . '</pre>';
}
  • str_slug()
/**
 * str_slug
 *
 * Normaliza uma string removendo todos os caracteres especiais, espaços e acentos.
 * 
 * @param  String $str
 * @return String
 */
function str_slug($str) {
    return url_title(convert_accented_characters($str), "-", true);
}
  • format_money()
/**
 * format_money
 *
 * Recebe um valor float/ e converte para a exibição padrão do Real com 2 casas decimais, separando os decimais com virgula e a casa de milhares com ponto.
 * 
 * @param  Mixed $money
 * @return void
 */
function format_money($money) {
    $money = floatval($money);
    echo number_format($money, 2, ',', '.');
}
  • validate_card()
/**
 * validate_card
 *
 * Recebe um número de cartão de crédito e retorna o número do cartão, a bandeira dele e se é valido ou não.
 * 
 * @param  String $number
 * @return array $return
 */
function validate_card($number){
    // Remove spaces
    $number = str_replace(" ", "", $number);

    $cardtype = array(
        'visa'              =>    "/^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/",
        'mastercard'        =>    "/^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/",
        'discover'          =>    "/^6011-?\d{4}-?\d{4}-?\d{4}$/",
        'amex'              =>    "/^3[4,7]\d{13}$/",
        'diners'            =>    "/^3[0,6,8]\d{12}$/",
        'bankcard'          =>    "/^5610-?\d{4}-?\d{4}-?\d{4}$/",
        'jcb'               =>    "/^[3088|3096|3112|3158|3337|3528]\d{12}$/",
        'enroute'           =>    "/^[2014|2149]\d{11}$/",
        'switch'            =>    "/^[4903|4911|4936|5641|6333|6759|6334|6767]\d{12}$/"
    );

    $type = false;

    if (preg_match($cardtype['visa'], $number)) {
        $type = "visa";
    } else if (preg_match($cardtype['mastercard'], $number)) {
        $type = "mastercard";
    } else if (preg_match($cardtype['amex'], $number)) {
        $type = "amex";
    } else if (preg_match($cardtype['diners'], $number)) {
        $type = 'diners';
    } else if (preg_match($cardtype['bankcard'], $number)) {
        $type = 'bankcard';
    } else if (preg_match($cardtype['jcb'], $number)) {
        $type = 'jcb';
    } else if (preg_match($cardtype['enroute'], $number)) {
        $type = 'enroute';
    } else if (preg_match($cardtype['switch'], $number)) {
        $type = 'switch';
    } else {
        $type =  false;
    }

    $return['valid']    =    LuhnCheck($number);
    $return['ccnum']    =    $number;
    $return['type']     =    $type;

    return $return;
}

此函数使用Luhn算法来计算卡号校验和,返回TRUE或FALSE。

  • time_ago()
/**
 * time_ago
 *
 * Recebe um Timestamp e retorna o tempo que passou desta data até o momento atual.
 * 
 * @param  Integer $time
 * @return boolean
 */

function time_ago($time){
    $time_difference = time() - $time;
    if ($time_difference < 1) {
        return 'less than 1 second ago';
    }
    $condition = array(
        12 * 30 * 24 * 60 * 60 =>  'year',
        30 * 24 * 60 * 60       =>  'month',
        24 * 60 * 60            =>  'day',
        60 * 60                 =>  'hour',
        60                      =>  'minute',
        1                       =>  'second'
    );
    foreach ($condition as $secs => $str) {
        $d = $time_difference / $secs;
        if ($d >= 1) {
            $t = round($d);
            return 'about ' . $t . ' ' . $str . ($t > 1 ? 's' : '') . ' ago';
        }
    }
}
  • hextorgba()
/**
 * hextorgba
 *
 * Recebe uma string referente a um valor hexadecimal, um valor de transparencia entre 0-1 e converte para RGBA.
 * 
 * @param  String $hex
 * @param  Float $transp
 * @return boolean
 */
function hextorgba($hex, $transp = 1) {
    list($r, $g, $b) = sscanf($hex, "#%02x%02x%02x");
    echo 'rgba(' . $r . ',' . $g . ',' . $b . ', ' . $transp . ')';
}

资产

application/config/assets.php中定义所有导入.js.css的源

  • $config['default']数组中配置从左到右的资产加载顺序。请注意,functions.jsstyle.css应该最后加载。如果在此数组中定义,则资产将被加载。
$config['default'] = ['bootstrap', 'vendors', 'toastr', 'custom'];

$config["default"]是定义哪些和以何种顺序导入资产的数组。

custom索引必须始终位于数组的最后一个位置。

  • 定义要使用的插件路径,始终遵循数组结构(如下例所示),并将此名称添加到$config['default'](如上所示)中。
$config['modulo_name'] = [
    'css'   =>  [
        site_url('assets/path/to/css/file1.css'),
        site_url('assets/path/to/css/file2.css'),
        site_url('assets/path/to/css/file3.css'),
        site_url('assets/path/to/css/file4.css')
    ],
    'js'    =>  [
        site_url('assets/path/to/js/file1.js'),
        site_url('assets/path/to/js/file2.js'),
        site_url('assets/path/to/js/file3.js'),
        site_url('assets/path/to/js/file4.js')
    ]
];

默认加载(bootstrap和toastr)

请注意,由于如果在文档末尾加载Jquery,则无法在<body>的中间使用它,因此我在视图application/views/master.php中加载了jquery 3.4.1

// Bootstrap 4.3.1
$config['bootstrap'] = [
    'css' => [ 
        'https://stackpath.bootstrap.ac.cn/bootstrap/4.3.1/css/bootstrap.min.css',
        site_url('assets/vendors/bootstrap-datepicker-1.9.0-dist/css/bootstrap-datepicker.min.css')
    ],
    'js'  => [
        'https://unpkg.com/popper.js/dist/umd/popper.min.js',
        'https://stackpath.bootstrap.ac.cn/bootstrap/4.3.1/js/bootstrap.min.js',
        site_url('assets/vendors/bootstrap-datepicker-1.9.0-dist/js/bootstrap-datepicker.min.js')
    ]
];
// Toastr notification
$config['toastr'] = [
    'css'   =>  [
        site_url('assets/vendors/toastr/toastr.min.css')
    ],
    'js'    =>  [
        site_url('assets/vendors/toastr/toastr.min.js')
    ]
];


/**
 * ====================================
 * ADICIONAR OS PLUGINS NO ARRAY ABAIXO
 * ====================================
 */

// Plugins localizados na pasta assets/vendors
$config['vendors'] = [
    'css' => [

    ],

    'js' => [

    ]
];

// Ultimo módule a ser carregado
$config['custom'] = [
    'css' => [  
        site_url('assets/css/style.css'),
    ],
    'js' => [ 
        site_url('assets/js/functions.js'),         
    ]
];

$config模板的构造函数中加载。要显示CSS和JS,使用模板中的print_css()print_js()函数。

模板库

这个类的主要功能是辅助MVC流程,并具有加载资源(模块)、渲染视图、定义页面标题和加载控制器到视图信息的函数。

class Template {

    // instancia do codeigniter
    public $ci;

    // arquivos de css para carregar na página
    public $css;

    // arquivos de js para carregar na página
    public $js;

    // as views que serão carregadas
    public $views = array();

    // modulos para carregar
    public $modules = array();

    // adiciona uma variavel a ser carregada na view
    public $data = array();

    // pagina a ser carregada
    public $p_page = 'home';

    // guard
    public $guard;

    // titulo da pagina
    public $title = '';

    // método construtor
    public function __construct() {

        // pega a instancia do ci
        $this->ci =& get_instance();

        // pega a biblioteca de configuração
        $this->ci->config->load( 'assets' );

        // pega a biblioteca de guard
        $this->ci->load->library( 'Guard' );
        $this->guard = $this->ci->guard;

        // carrega os módulos padrão
        $this->loadDefault();
    }
}

方法

  • set_title()
  • print_title()
  • loadDefault()
  • use_module()
  • loadModules()
  • set()
  • item()
  • addCss()
  • addJs()
  • print_js()
  • print_css()
  • view()
  • print_view()
  • page()
  • print_component()
  • print_page()
  • render()

由于许多方法只是辅助函数,并且在实践中很少被开发者使用,因此我不会解释所有方法。

主要方法

  • set()
    /**
     * set
     *
     * seta o valor para uma variavel
     * 
     * @param String $chave
     * @param String $valor
     * @return void
     */
    public function set( $chave, $valor ) {
        $this->data[$chave] = $valor;
    }

此函数应在控制器中使用,以向视图发送信息。

示例

class Usuario extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Usuarios_model');
    }

    public function index(){
        $usuarios = $this->Usuarios_model->getAll(); // busca todos os usuarios no bd
        $this->template->set("usuarios", $usuarios); // seta os usuarios ($usuarios) encontrados para a posição 'usuarios' do array do template
    }
}
  • item()
    /**
     * item
     *
     * pega o valor de uma varivel
     * 
     * @param  String
     * @return mixed [Retorna o objeto do array indicado pela $chave ou null caso não exista]
     */
    public function item( $chave ) {
        return ( isset( $this->data[$chave] ) ) ? $this->data[$chave] : null;
    }

此函数应在视图中使用,以从控制器恢复发送的信息。

示例

$usuarios = $this->template->item('usuarios'); //Armazena em $usuarios os dados adicionados anteriormente no controller

foreach ($usuarios as $user) {
    echo $user['nome'] . '<br>';
}
  • set_title()
    /**
     * set_title
     *
     * Define o titulo da página html
     * 
     * @param String $title [Titulo da página]
     * @return void
     */
    public function set_title( $title ) {
        $this->title = $title;
    }

此函数应在控制器中使用,以定义将要加载的页面标题。

示例

class Home extends MY_Controller {

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

    public function index(){
        $this->template->set_title("Página inicial"); // Seta o titulo da pagina
    }
}
  • print_title()
    /**
     * print_title
     *
     * Exibe o titulo atual
     * 
     * @return void
     */
    public function print_title() {
        echo $this->title;
    }

此函数应在视图中使用,一旦控制器通过set_title函数定义了标题,即可打印页面标题。应在加载HTML结构的视图master.php中调用此函数。

示例

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <!-- Meta, title, CSS, favicons, etc. -->
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="Content-Language" content="pt-br">
  
        <!-- TITLE -->
        <title><?PHP $template->print_title(); ?></title> <!-- Exibe na tela o title setado no controller -->
        .
        .
        .
  • print_js()
    /**
     * print_js
     *
     * Imprime o js
     * 
     * @return void
     */
    public function print_js() {
        if(count($this->js) > 0){
            foreach( $this->js as $js ) {
                if(ENVIRONMENT == 'production')
                echo '<script src="'.$js.'" type="text/javascript"></script>';
                else{
                    echo '<script src="'.$js.'?version='.time().'" type="text/javascript"></script>';
                }
            }
        }
    }

此函数应在视图中使用,以在屏幕上打印在资源中定义的JS文件。应在加载HTML结构的视图master.php中调用此函数。

示例

        .
        .
        .
        <!-- PRINT JS - CONFIG IN config/assets.php -->
        <?php $template->print_js(); ?>
    </body>
</html>
  • print_css()
    /**
     * print_css
     *
     * Imprime o css
     * 
     * @return void
     */
    public function print_css() {
        if(count($this->css) > 0){
            foreach( $this->css as $css ) {
                if(ENVIRONMENT == 'production'){
                    echo '<link href="'.$css.'" rel="stylesheet" media="screen"/>';
                }
                else{
                    echo '<link href="'.$css.'?version='.time().'" rel="stylesheet" media="screen"/>';   
                }
                
            }
        }
    }

此函数应在视图中使用,以在屏幕上打印在资源中定义的CSS文件。应在加载HTML结构的视图master.php中调用此函数。

示例

<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <!-- Meta, title, CSS, favicons, etc. -->
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="Content-Language" content="pt-br">
        
        <title><?PHP $template->print_title(); ?></title> <!-- Exibe na tela o title setado no controller -->


        <?PHP $template->print_css(); ?>

    </head>
    .
    .
    .

请注意,在print_cssprint_js函数中,有一个对ENVIRONMENT的检查,该检查定义了项目所处的阶段,具有productiontestingdevelopment值。当不在生产环境时,文件的URL会添加一个后缀?version='.time().',这样浏览器就总是被迫下载文件,从而避免缓存问题。

  • print_component()
    /**
     * page
     *
     * carrega um componente
     * 
     * @param  String
     * @param Array $var [Array de dados a serem enviados para a view]
     * @return void
     */
    public function print_component( $component , $var = false) {
        
        // carrega a pagina
        $this->ci->load->view( 'components/'.$component, $var);
    }

此函数应在视图中使用,以打印存在于application/views/components/中的现有组件。

  • print_page()
    /**
     * print_page
     *
     * Carrega uma view salva em views/pages/[view].php
     * 
     * @param  String
     * @return void
     */
    public function print_page( $page = false ){

        // verifica se o usuário deseja carregar uma pagina em especifico
        $this->p_page = $page ? $page : $this->p_page;

        // carrega a pagina
        $this->ci->load->view( 'pages/'.$this->p_page );
    }

此函数应在视图中使用,以打印存在于application/views/pages/中的现有页面。

  • render()

这可以作为一个替代方案使用Codeigniter中的$this->load->view()来加载完整页面,请查看主视图以更好地理解加载流程。

    /**
     * render
     *
     * Renderiza a página escolhida em um layout escolhido (master.php)
     * 
     * @param  String $layout
     * @param  String $page
     * @return void
     */
    public function render( $layout = false, $page = false ) {

        // carrega os modulos
        $this->loadModules();

        // verifica se o usuário deseja carregar uma pagina em especifico
        $this->p_page = $page ? $page : $this->p_page;

        // carrega a view
        $this->ci->load->view( $layout, [ 'template' => $this ] );
    }

此函数应在控制器中使用,以在application/views/pages/中显示现有页面,并在application/views/master.php布局中加载其相应的CSS和JS模块。

示例

class Home extends MY_Controller {

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

    public function index(){
        $this->template->set_title("Página inicial"); // Seta o titulo da pagina
        $this->template->render('master', 'home'); // Carrega a view /views/pages/home.php dentro do layout views/master.php
    }
}

守卫库

这个类的作用是简化对用户会话变量的操作,使用Codeigniter的Session Library函数。

仅限于用户会话($_SESSION['user']$this->session->user);

class Guard {

    // instancia do codeigniter
    public $ci;

    // dados do usuario logado
    public $user = false;

    // método construtor
    public function __construct() {

        // pega a instancia do ci
        $this->ci =& get_instance();

        // carrega a librarie de sessao
        $this->ci->load->library( 'session' );

        // pega os dados do usuario
        if ( $user = $this->ci->session->userdata( 'user' ) ) {
            $this->user = $user;
        }
    }

方法

  • logged()
    /**
     * logged
     *
     * Verifica se o usuário está logado ou não
     * 
     * @return Boolean
     */
    public function logged(){
        return $this->user ? true : false;
    }

示例

if($this->guard->logged()){
  echo 'Usuário logado';
}
else{
  echo 'Usuário deslogado';
}
  • item()
    /**
     * item
     *
     * Retorna um item do array $user salvo na sessão
     * 
     * @param  String $key [Campo do array $user]
     * @return Object or NULL
     */
    public function item( $key ) {
        return isset( $this->user[$key] ) ? $this->user[$key] : null;
    }

示例

$nome = $this->guard->item('nome');
echo $nome;
// Fulano da Silva
  • login()
    /**
     * login
     *
     * Tenta fazer o login do usuario através de um e-mail e senha inseridos
     * 
     * @param  String $email [E-mail para logar]
     * @param  String $senha [Senha para logar]
     * @return Boolean
     */
    public function login( $email, $senha ) {

        // carrega a model de usuários
        $this->ci->load->model( 'Usuarios_model' );

        // faz o login
        if ( $user = $this->ci->Usuarios_model->validate( $email ) ) {
            
            // Valida a senha do usuário
            // Para cadastrar a senha no banco utilize a função password_hash() do PHP
            if(password_verify($senha, $user['senha'])){        
                // guarda na sessao
                $this->ci->session->set_userdata( 'user', $user );            
                
                // guarda no atributo
                $this->user = $user;
                
                return true;
            }
        }
        
        return false;
    }

在这个函数中使用了用户模型中的 validate() 方法。该函数负责通过提供的电子邮件和密码参数进行搜索,并返回关于搜索到的用户的元组或如果找不到则返回 false。另一个重要点是,必须使用哈希来加密密码,需要使用 password_hash 函数将密码插入到数据库中,并使用 password_verify 函数在登录时验证密码。

示例

$email = 'fulano@example.com';
$senha = '123456';

if($this->guard->login($email, $senha)){
    echo 'Bem-vindo!';
}
else{
    echo 'Credenciais inválidas';
}
  • update()
    /**
     * update
     *
     * Busca o usuario no banco de dados e atualiza a sessão com os dados 'novos'
     * 
     * @return Boolean
     */
    public function update() {

        // verifica se existe um usuário logado
        if ( !$this->user ) return false;

        // carrega a model de usuários
        $this->ci->load->model( 'Usuarios_model' );

        // pega os dados do perfil do usuario logado
        if ( $user = $this->ci->Usuarios_model->getById( $this->user['id_usuario'] ) ) {

            // seta a sessao
            $this->ci->session->set_userdata( 'user', $user );

            // seta o usuario
            $this->user = $user;

            return true;

        } else return false;
    }

示例

echo $this->guard->item('nome'); // Fulano da Silva

$dados = ['id' => $id_usuario, 'nome' => 'Bernardo'];  //Seta os dados para o update

$this->Usuarios_model->update($dados); // Atualiza o nome do usuario com id = $id_usuario

echo $this->guard->item('nome'); // Fulano da Silva

$this->guard->update(); // Atualiza a sessão com os valores do banco

echo $this->guard->item('nome'); // Bernardo
  • getShortName()
    /**
     * getShortName
     *
     * @param String $nome [Nome completo do usuario]
     * @return String [Concatena o primeiro e o ultimo nome do usuario]
     */
    public function getShortName($nome = false){
        if(!$nome)
            $nome = $this->user['nome'];

        $nomes = explode(" ", $nome);

        if(count($nomes) > 1)
            $nome = $nomes[0] . " " . $nomes[count($nomes)-1];        
        else
            $nome = $nomes[0];

        return $nome;
    }

示例

echo $this->guard->item('nome'); // Fulano da Silva

echo $this->guard->getShortName(); // Fulano Silva

echo $this->guard->getShortName('Fulano de Oliveira da Silva'); // Fulano Silva
  • logout()
    /**
     * logout
     *
     * Limpa a sessão 'user'
     * 
     * @return void
     */
    public function logout() {
        $this->ci->session->unset_userdata('user');
    }

示例

$this->guard->logout();

核心MY_Controller

位于 application/core/MY_Controller.php

这个类相对简单,因为每个 controller 都非常具体。然而,在构造函数中我们加载了 TemplateGuard 库。

所有 的控制器都应该通过 PHP 的 extends 关键字继承自 MY_Controller

class MY_Controller extends CI_Controller {
    
    // médoto construtor
    public function __construct() {
        parent::__construct();
     
        // Carrega o Template e Guard
        $this->load->library( 'Template' );
        $this->load->library( 'Guard' );
    }
}

核心MY_Model

位于 application/core/MY_Model.php

这个类负责允许在使用 SQL 处理数据库的 Web 应用程序中重用常见功能。

注意:MY_Model 不替代 Query Builder,因此如果您需要使用某些复杂查询,不要使用 MY_Model 来实现。

class MY_Model extends CI_Model {
    
    /**
    * table
    *
    * nome da tabela no model
    *
    * @protected
    */
    protected $table;

    /**
    * table_id
    *
    * chave da tabela no model
    *
    * @protected
    */
    protected $table_id;

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

基本上,这是通过使用面向对象的继承概念实现的魔法。因此,开发者创建的模型应该通过 extends 关键字继承这个类。

$table(表名)和 $table_id(主键)是为此必需的属性,因为它们代表任何基本 SQL 查询的变量,因此我们可以重用 CI 中已存在的 create、update 和 delete 等函数,同时还可以为所有基本模型创建一些新函数,如 getAll() 或 getAllLimit()。

必须在这些继承此类的所有模型中初始化这些变量。

  • 例如,对于主键为 id_usuariousuarios 表的模型
class Usuarios_model extends MY_Model {

    /**
    * table
    *
    * nome da tabela no model
    *
    * @protected
    */
    protected $table = 'usuarios';

    /**
    * table_id
    *
    * chave da tabela no model
    *
    * @protected
    */
    protected $table_id = 'id_usuario';

    // metodo construtor
    public function __construct() {
        parent::__construct();
    }
}

方法

  • create()
   /**
   * create
   * 
   * insere um novo dado
   *
   * @param Array $dados [Dados a serem inseridos na tabela]
   * @return Boolean [Retorna true caso os dados tenham sido inseridos e false caso contrario]
   */
   public function create( $dados ){
       return $this->db->insert( $this->table, $dados );
   }

示例

$this->load->model('Usuarios_model');

$dados = [
   'nome'          => 'Fulano da Silva',
   'email'         => 'fulano@example.com',
   'senha'         => '123456',
   'sexo'          => 'masculino',
   'data_nasc'     => '1996-04-03'
]; 

if($this->Usuarios_model->create($dados)){
   echo 'Usuário cadastrado com sucesso!';
}
else{
   echo 'Houve um erro no servidor.';
}
  • update()
  /**
   * update
   * 
   * atualiza um dado
   *
   * @param Array $dados [Dados a serem atualizados. *O campo 'id' deve ser passado obrigatoriamente]
   * @return Boolean [Retorna true caso os dados tenham sido atualizados e false caso tenha algum erro de lógica no SQL]
   */
   public function update( $dados ) {

       // prepara os dados
       $this->db->where( $this->table_id, $dados['id']);

       // deleta o id
       unset( $dados['id'] );
       if ( isset( $dados[$this->table_id] ) ) unset( $dados[$this->table_id] );

       // faz o update
       return $this->db->update($this->table, $dados); 
   }

数组中的 id 字段是 必需的

示例

$this->load->model('Usuarios_model');

$dados = [
    'id'            => 1,
    'nome'          => 'Fulano da Silva',
    'email'         => 'fulano@example.com',
    'senha'         => '123456',
    'sexo'          => 'masculino',
    'data_nasc'     => '1996-04-03'
]; 

if($this->Usuarios_model->update($dados)){
    echo 'Usuário atualizado com sucesso!';
}
else{
    echo 'Houve um erro no servidor.';
}

请注意,无论主键的名称如何,用于更新的数据数组必须始终包含一个名为 id 的字段!

  • delete()
  /**
   * delete
   * 
   * deleta um dado
   *
   * @param mixed $id [Chave primária da tabela]
   * @return Boolean [Retorna true caso remova a linha ou false caso contrario]
   */
   public function delete( $id ) {
       $this->db->where( $this->table_id, $id );
       return $this->db->delete( $this->table ); 
   }

示例

$this->load->model('Usuarios_model');

if($this->Usuarios_model->delete(1)){
    echo 'Usuário deletado com sucesso!';
}
else{
    echo 'Houve um erro no servidor.';
}
  • getById()
   /**
   * getById
   * 
   * pega um dado por id
   *
   * @param  $id [Chave primária da tabela]
   * @return mixed [Retorna um array com os dados requisitados ou false caso não encontre nada]
   */
   public function getById( $id ){
       
       // faz a busca
       $this->db->select( '*' )
       ->from( $this->table )
       ->where( [$this->table_id => $id ] );
       $query = $this->db->get();

       // verifica se existem resultados
       return ( $query->num_rows() > 0 ) ? $query->result_array()[0] : false;
   }

示例

$this->load->model('Usuarios_model');

$user = $this->Usuarios_model->getById(1);

if($user){
    echo $user['nome']; //Fulano da Silva
}
else{
    echo 'Usuário não encontrado';
}
  • getAll()
   /**
   * getAll
   * 
   * pega todos os registros
   *
   * @param mixed $where [Opcional: Condições da consulta]
   * @param String $fields [Opcional: Campos do SELECT da consulta]
   * @param mixed $orderby [Opcional: Ordenação da consulta]
   * @return mixed [Retorna a coleção de dados requisitadas em uma matriz]
   */
   public function getAll( $where = false, $fields = '*', $orderby = false) {
       
       if($orderby){
           $orderby = explode(" ", $orderby);
           $order = $orderby[1];
           $order_colum = $orderby[0];
       }
       else{
           $order = 'asc';
           $order_colum = $this->table_id;
       }

       // monta a busca
       $this->db->select( $fields );
       $this->db->from( $this->table );

       //verifica se existe um where
       if ( $where ) $this->db->where( $where );

       $this->db->order_by($order_colum, $order);

       // pega os dados do banco
       $query = $this->db->get();

       // verifica se existem resultados
       return ( $query->num_rows() > 0 ) ? $query->result_array() : false;
   }   

示例 1

$this->load->model('Usuarios_model');

$users = $this->Usuarios_model->getAll(); // Busca todas as tuplas da tabela `usuarios`

if($users){
    foreach ($users as $user) {
        echo $user['nome'] . '<br>';
    }
}
else{
    echo 'Usuário não encontrado';
}

示例 2

$this->load->model('Usuarios_model');

$users = $this->Usuarios_model->getAll('sexo = masculino', 'usuarios.nome', 'nome asc'); // Será feita a consulta na tabela `usuarios` atrás das tuplas que possuem o sexo definido como masculino e retornará todos os nomes em ordem crescente.

if($users){
    foreach ($users as $user) {
        echo $user['nome'] . '<br>';
    }
}
else{
    echo 'Usuário não encontrado';
}

示例 3

$this->load->model('Usuarios_model');

$users = $this->Usuarios_model->getAll(false, 'usuarios.nome', 'nome asc'); // Será feita a consulta na tabela `usuarios` e retornara todos os nomes dos usuarios ordenados pelo nome crescente.

if($users){
    foreach ($users as $user) {
        echo $user['nome'] . '<br>';
    }
}
else{
    echo 'Usuário não encontrado';
}
  • getAllLimit()
   /**
    * getAllLimit
    * 
    * @param int $limit [Inteiro que define a quantidade máxima de resultados da consulta]
    * @return Array[] [Retorna a coleção de dados requisitadas em uma matriz]    
    * 
    */
   public function getAllLimit($limit){
       $this->db->from($this->table)
       ->select('*')
       ->limit($limit);

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

       return ($busca->num_rows() > 0) ? $busca->result_array() : array();

   }

示例

$this->load->model('Usuarios_model');

$users = $this->Usuarios_model->getAllLimit(5); // Será feita a consulta na tabela `usuarios` e retornará as 5 primeiras linhas.

if($users){
    foreach ($users as $user) {
        echo $user['nome'] . '<br>';
    }
}
else{
    echo 'Usuário não encontrado';
}

这个函数仅用于辅助应用程序开发,在产品环境中很少使用。当您想要测试数据列表并且可以限制结果数量但不能进行筛选时,请使用此函数。

通知

此模板的通知系统使用 JavaScript 库 Toastr 以及 Codeigniter 的本地函数 SESSION Flashdata

我们将使用 notifyUser() 函数通过 JavaScript 显示通知。

/**
* notifyUser
* 
* notifica o usuario
*
* @param String type [Tipo de notificação]
* @param String text [Conteúdo da notificação]
* @param Int delay [Tempo para a notificação sumir]
*/
function notifyUser(type, text, delay = 8000) {
    var icon = "";
    var title = "";

    // Toastr config
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "newestOnTop": false,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "preventDuplicates": true,
        "onclick": null,
        "showDuration": 300,
        "hideDuration": 1000,
        "timeOut": delay,
        "extendedTimeOut": 1000,
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    }

    switch(type){
      case 'success':
        toastr.success(text);
      break;

      case 'error':
        toastr.error(text);
      break;

      case 'warning':
        toastr.warning(text);
      break;

      case 'info':
        toastr.info(text);      
      break;

      case 'loading':
        icon = "<i class='fa fa-spin fa-spinner'></i>&ensp;";
        
        toastr.options.timeOut = 0;
        toastr.options.extendedTimeOut = 0;

        toastr.info("<i class='fa fa-spin fa-spinner'></i>&ensp;" + text);
        
      break;

      default:
        toastr.error('Houve um erro ao exibir a notificação');
      break;
    }

};

为了在执行 redirect 后将通知从 Controller 传递到 View,我们将使用 SESSION FLASHDATA 概念,它允许在下一个请求中存储有效的信息,之后这些信息将被自动删除。

如何在 Controller 中创建通知的示例。

public function login(){
    $post = $this->input->post();

    if($this->guard->login($post['email'], $post['senha'])){
        $this->session->set_flashdata('success', 'Bem vindo!');
    }
    else
        $this->session->set_flashdata('error', 'Credenciais inválidas.');

    redirect(site_url(),'location');
}

application/views/components/alerts.php 文件包含 PHP 和 JavaScript 之间的连接。

<?php if($this->session->flashdata('success')): ?>
    <script>
        $(document).ready(function(){
            notifyUser('success', '<?php echo $this->session->flashdata('success') ?>');
        });
    </script>
<?php endif; ?>


<?php if($this->session->flashdata('error')): ?>
    <script>
        $(document).ready(function(){
            notifyUser('error', '<?php echo $this->session->flashdata('error') ?>');
        });
    </script>
<?php endif; ?>

<?php if($this->session->flashdata('warning')): ?>
    <script>
        $(document).ready(function(){
            notifyUser('warning', '<?php echo $this->session->flashdata('warning') ?>');
        });
    </script>
<?php endif; ?>

<?php if($this->session->flashdata('info')): ?>
    <script>
        $(document).ready(function(){
            notifyUser('info', '<?php echo $this->session->flashdata('info') ?>');
        });
    </script>
<?php endif; ?>


<?php if($this->session->flashdata('loading')): ?>
    <script>
        $(document).ready(function(){
            notifyUser('loading', '<?php echo $this->session->flashdata('loading') ?>');
        });
    </script>
<?php endif; ?>

notifyUser() 函数定义在 assets/js/functions.js 中。

有两种方法可以向用户显示通知

  • PHP

没有控制器,在调用 redirect() 之前,必须创建一个带有以下五种类型之一的索引的 session flashdata。

$this->session->set_flashdata('success', 'Muito bom, sua ação foi concluída com sucesso!');
  • JavaScript

在任何视图中,只需调用函数 notifyUser,将通知类型作为第一个参数传递,将所需消息作为第二个参数。

notifyUser('success', 'Muito bom, sua ação foi concluída com sucesso!');

存在五种预定义的通知类型:successerrorwarninginfoloading

  • success

应用于成功通知。

  • error

应用于系统错误或故障通知。

  • warning

应用于提醒用户注意的通知。

  • info

应用于向用户提供额外信息的通知。

  • loading

应用于使用 ajax 的功能,在 beforeSend() 中调用 notifyUser 函数,以便向用户传达正在进行的感知,因为 ajax 是动态的,用户最终可能无法感知。

示例 loading 通知

$.ajax({
    url: '/path/to/file',
    type: 'POST',
    dataType: 'json',
    data: data,
    beforeSend: function(){
        notifyUser('loading', 'Carregando informações...');
    }
})
.done(function(response) {
    PNotify.removeAll(); //Remove todas as notificações

    console.log("success");
})
.fail(function(xhr, status) {
    console.log("error");
})
.always(function() {
    console.log("complete");
});
  • 移除活动通知

要使通知消失,只需使用 Toastr 的函数。

toastr.clear();

JS插件

位于 assets/vendors/

贡献

由 Bernardo Camargo 开发 @bernacamargo

许可证

MIT