I’m new to CodeIgniter and I have this function which I use in more than one model.
// Returns TRUE if the array of values supplied
// each correspond to a column in the database table.
// Else returns the value of the bad column.
private function _columns_exist( $columns, $table ) {
foreach( $columns as $key => $value ) {
if( !$this->db->field_exists( $key, $table ) ) {
return $key;
}
}
return TRUE;
}
What is considered the correct way to write the function once, and reuse it from many different files?
Do I want to create a whole library just for this one function?
The point of CodeIgniter is that there are basically two types of custom functions. Ones that live in Libraries as library methods and ones that live in Helpers as simple functions.
The difference between them is minimal and it is for you to decide where to keep them, but the best practice is that helper functions are mostly standalone and library methods are the ones that use CI libraries like database, sessions, your other models.
For your function it’s best to make a library and keep it there, but you can, as well, make a helper as you’re not overusing any database querying. If it was me, I would make a helper:
Make a file in the
helpersdirectory nameddb_helper.phpand add an elementdbto helper array inautoload.phpfile. Note that you don’t need to write the full namedb_helper, onlydb.Put this code in
db_helper.phpfile you’ve created:Now you can use this function anywhere – in your controllers, models, even view files as you would if it was a simple function:
Note that you don’t use
$thisin helpers or libraries, you must get an instance of CodeIgniter singleton object first, then you manipulate it. You can find more info on this in the user guide or on StackOverflow.Also see my comments to darkdad‘s answer, that is another great approach I would go for.