Welcome Guest, Not a member yet? Register   Sign In
Re-instantiating a library with new __construct() params?
#1

[eluser]WoolyG[/eluser]
Hi all,

I'm using a library that's loaded upon a model's usage:

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

class Mynice_model extends CI_Model {

    public function __construct(){

        $lib_params = array();

       // Set the username and password into the array
        $lib_params[] = '150151';
        $lib_params[] = '5854';
        
        // Push the login deets to the library
        $this->load->library('mycustomlibrary', $lib_params);
    }

....

.. this works fine, but in (only) one of the same model's methods I need to send a different username & password to the library. So I'm doing this:

Code:
....

public function redeem_balance($card_number, $amount, $user_id = NULL)
    {

        $lib_params = array();

        $staff_code = "";
        if(isset($user_id) && ($user_id != null))
        {
            $staff_code = $user_id.":";
        }

        $lib_params[] = $staff_code.'150151';
        $lib_params[] = '5854';
        $this->load->library('mycustomlibrary', $lib_params);

        //.. continue
    }

....


redeem_balance() is part of the Mynice_model, and, when called, attempts to reload the 'mycustomlibrary' library using a different $lib_params array.

Is this sort of thing OK to do? If the library is called in the __construct() method, then is it okay to re-load it using alternative params for a subsequently-called method?

I know this isn't very DRY-adherent, but it's just a one-off within the app, so I'm doing it anyway Smile

All input appreciated!
Wooly



#2

[eluser]Aken[/eluser]
Once you load a library, you will not be able to load it again with new constructor parameters. See Loader::library() for why:

Code:
if ($library == '' OR isset($this->_base_classes[$library]))
{
return FALSE;
}

What you should do is implement an init() method (or whatever you want to name it), that allows you to "reset" parameters. Then, rather than reloading the library, you just reset its params.

Code:
class Mylib {

public $prop;

public function __construct($prop = array())
{
  $this->init($prop);
}

public function init($prop)
{
  $this->prop = $prop;
}

// Your other stuff
}

// -------------

// First load:
$this->load->library('mylib', array('foo' => 'bar'));

// Later, when you want to change something:
$this->mylib->init(array('fizz' => 'buzz'));




Theme © iAndrew 2016 - Forum software by © MyBB