Inheritance in CodeIgniter
I am building a series of forms, and I am trying to inherit the functionality of a parent Form class into all the forms. For example,
LeaveForm extends Form
开发者_运维技巧 (Model)
LeaveFormController extends FormController
I am handling all the leave form specific stuff in LeaveFormController
and LeaveForm
.
In LeaveFormController
constructor, I simply call the parent class constructor, then load the LeaveForm
Model. And in FormController
constructor, I load Form model.
My problem is, I get an error,
Cannot redeclare class form in Form.php
Have I got my architecture wrong? How do I handle this ?
check if the class has already been initialized like this:
if (!class_exists('classname'))
{
// ok fine create new instance now
}
Possibly when you $this->load->model('Form')
, you manually include
d the models/form.php
file?
In your leaveform.php
model file, make sure you load the superclass model you extend using codeigniter's model loading mechanism instead of require
or include
. Codeigniter has a loader that keeps track of already-loaded files to avoid redeclaring classes, but you need to use $this->load
to use it. It won't know about files loaded directly with include
or require
.
So at the top of leaveform.php
, use this:
$CI =& get_instance(); $CI->load->model('Form');
This is not related, but you will have pain unless you namespace your CodeIgniter model classes the same way you namespace Controller classes.
Try using FormModel extends CI_Model {};
Instead of Form extends CI_Model {};
精彩评论