Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I put constants file for Codeigniter (PHP)?

I have a list of constants (I'm using them as an enum), some are define statements, and some are just global variables.

Where am I suppose to put them in the MVC framework so I can use them for both my model and my controller that needs to reference it?

I'd rather not stick it into config/constants.php since they shouldn't be called except for by this model and the controllers that use it.

Edit 1: Clarification

To be more specific, I have my message_model model and it has a bunch of constants that I need that are stored in message_model_constants.php. Where should I put message_model_constants.php and is there a way to have it automatically included by the controller that loads message_model when message_model is not (and I don't want it to be) auto-loaded.

Edit 2:

I really don't want to have the constants auto-loaded except for when I use the model

like image 354
wag2639 Avatar asked Jun 14 '10 21:06

wag2639


2 Answers

Go to application/config/constants.php and define your constant their and you can use your constants on Model-View-Controller of CI not include "Helper" and "Library"

But in your case I prefer you to create a php file that has your constants and rename it to something like my_constants_helper.php.

In your model or controller __construct just

$this->load->helper('my_constants');

And hooray you can access them =)

like image 143
DominixZ Avatar answered Oct 19 '22 22:10

DominixZ


You can choose to load a particular config file when you load a particular model in the controller. For instance in your file:

application/controllers/messages.php

You would use a line like this:

$this->config->load('messages');

If you include it at the top of your controller like this

function __construct() { 
   $this->config->load('messages');
   $this->load->model('message_model');
}

Then all of those constants will be available to all the functions and methods in the given controller. You then call each config constant like:

$this->config->item('item name')

And you can name protected $variables; in the construct as well for shorter syntax.

If you are using these config constants and the message model in multiple different controllers you may want make a "Library" file that then loads both the config and the model and declares all variables there.

like image 43
Brennan Novak Avatar answered Oct 20 '22 00:10

Brennan Novak