Biraj Bora
Biraj Bora

Reputation: 949

Is it a good practice to use database queries in helper functions in codeigniter?

I've used database queries in helper functions in the CodeIgniter framework.

Suppose, a database has many tables, e.g. school, student, ... etc. and there are common tasks are required in the application, such as generating random unique ids for each entry into a table, retrieving an entire row of the matched row from a table, ... etc. are required.

Now, we can write functions for each task in the respective models of the database, e.g.

In School_model :

class School_model extends CI_Model
{
    // some code ...    

    function generateID()
    {
        // code to generate unique id by checking the database
    }

    // some code ...
}

and in Student_model :

class Student_model extends CI_Model
{
    // some code ...    

    function generateID()
    {
        // same code to generate unique id except the table name
    }

    // some code ...
}

Or we can pass the table_name as an argument to a helper function as:

function generate_ID( $table_name )
{
    // code to genetrate unique id by checking in $table_name
}

The later prevants code duplication ( DRY ). But is it a good practice to use database queries in functions outside the models.

Upvotes: 0

Views: 269

Answers (1)

Mukesh Ram
Mukesh Ram

Reputation: 6328

I think, extending Codeigniter core is the better approach for this.

class MY_Model extends CI_Model { 

You can write the function generate_ID( $table_name ){ inside core model

Finally extend your model with MY_Model

class Student_model extends MY_Model

Upvotes: 2

Related Questions