Reputation: 13
I am using CodeIgniter 3.
Here's my Admin
controller where I insert a record into the table people
:
class Admin extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function addpeople() {
insert in into people values('','pramod','emp0784');
}
}
This is another controller where I perform the same operation as the Admin
controller, but it writes the same code twice. I want to reuse the code in the Employee
controller:
class Employee extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function addpeople() {
insert in into people values('','pramod','emp0784');
}
}
Another way I found is to redirect(../admin/addpeole)
in Employee
, but it changes the URL.
Is there any another way to reuse same code in the Admin
controller in the Employee
controller without changing the URL?
Upvotes: 1
Views: 630
Reputation: 2729
Controllers should not communicate with the database directly, You should be using Models to communicate with the database, And your Controllers should be communicating with models then sending the output either directly or through a view.
You can create a model under application/models
You'll have to give it a name that does not conflict with controllers so most people add the suffix _model
or _m
e.g: application/models/Employees_model.php
it should extends CI_Model the code would be something like this.
class Employees_model extends CI_Model {
public function add_employee($data) {
// insert code goes here
}
]
then in your controller you load the model & send it the $data to create an employee
class Employees extends CI_Controller {
public function create () {
$this->load->model('employees_model');
$this->employees_model->add_employee($this->input->post());
}
}
Upvotes: 1
Reputation: 11987
try this
In core create a file called MY_Controller.php
and extend from CI_Controller.
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Admin_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function addpeople() {
insert in into people values('','pramod','emp0784');
}
}
?>
Write the function in that controller
Extend Employees
form the controller created in core.
class Employee extends Admin_controller{
public function __construct() {
parent::__construct();
}
function abc() {
$this->addpeople();// this will insert the values for you
}
}
Upvotes: 0