0
votes

I have an existing controller (classA) which needs to use a new helper class (classB). Typically I would place classB into a library and do

$this->load->library('classb');
$this->classb->method();

However, I've run into a problem where I am defining const's in my classB which are required by the constructor

classB {
    const MYDEFINE = 1;
    ...
}

The problem with this approach is the definition of MYDEFINE is NOT available until I load the library, but I need to create the $params array with the arguments to send the classB constructor. So I get a case of chicken vs. egg

$params = array();
$params['open_mode'] = classB::MYDEFINE;
$instance = $this->load->library('classB', $params);

I've been able to solve this problem by not using a library - and instead using a @include_once('classB') in my classA controller which is working fine. The file classB.php is therefore stored in the controllers directory.

I'm wondering if others have run across this problem and how they might have solved it (other than by decaaring the consts elsewhere). I looked at a post by PhilSurgeon (http://philsturgeon.co.uk/blog/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY) on an alternative method but its not quite the right fit for this problem (at least I don't think so).

2

2 Answers

0
votes

I'm unclear why you would declare a constant, and then load it into the config when you initialize the class...that makes no sense, is why you have the chicken-and-egg issue

I would set things up roughly as:

private $myvar = 'My Constant Value';

function __construct() ... etc

and then you can access it using:

$this->myvar

anywhere in your library class, including the construct if you want to change it via your config

EDIT: You could still use a constant is that is more appropriate, but then pass it to the $this->myvar in your construct() as a above. The point is, your Constant should never be worked with outside of the class

0
votes

how about creating a bootstrap library like

include 'path/to/class/b';

class Init_class_b Extends class_b
{
   function __construct($params)
   {
      // handle the variables here
      parent::__construct();
   }
}

then:

$this->load->library('Init_class_b',$params_for_construct);

$this->Init_class_b->method()