Welcome Guest, Not a member yet? Register   Sign In
I can use this Sigleton?
#1
Wink 

(models) User_model.php:

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

class 
User_model extends CI_Model {

    private static 
$instance;

    public static function 
newInstance() {
        if(!
self::$instance instanceof self) {
            
self::$instance = new self;
        }
        return 
self::$instance;
    }
    
    public function 
__construct() {
        
parent::__construct();
    }

    public function 
getUserById($id) {
        
$this->db->select('*');
        
$this->db->from('ci_t_user');
        
$this->db->where('pk_i_id'$id);
        
$query $this->db->get();
        
$result $query->row();
        return 
$result;
    }

}
?>

(helpers) user_helper.php:

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

if (!
function_exists('get_user_name')) {
    function 
get_user_name($id) {
        
//$ci =& get_instance();
        //$user = $ci->user_model->getUserById($id);
        
$user user_model::newInstance()->getUserById($id);
        return 
$user->s_name;
    }
}

?>

Or must I use get_instance (); ?
Reply
#2

(04-12-2016, 09:12 AM)adrianolmedo Wrote: (models) User_model.php:

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

class 
User_model extends CI_Model {

 private static 
$instance;

 public static function 
newInstance() {
 if(!
self::$instance instanceof self) {
 
self::$instance = new self;
 }
 return 
self::$instance;
 }
 
 public function 
__construct() {
 
parent::__construct();
 }

 public function 
getUserById($id) {
 
$this->db->select('*');
 
$this->db->from('ci_t_user');
 
$this->db->where('pk_i_id'$id);
 
$query $this->db->get();
 
$result $query->row();
 return 
$result;
 }

}
?>

(helpers) user_helper.php:

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

if (!
function_exists('get_user_name')) {
 function 
get_user_name($id) {
 
//$ci =& get_instance();
 //$user = $ci->user_model->getUserById($id);
 
$user user_model::newInstance()->getUserById($id);
 return 
$user->s_name;
 }
}

?>

Or must I use get_instance (); ?

I do not understand why do you use additional methods like newInstance(). Just create method you need and from withing library get CI instance:

(helpers) user_helper.php:

PHP Code:
private $CI;

 public function 
__construct() {
 
  $this->$CI =& get_instance();
 
  $this->$CI->load->database('foo_model');
 }

public function 
foo() {
 
$foo_bar$this->$CI->foo_model>bar_method();

Reply




Theme © iAndrew 2016 - Forum software by © MyBB