I have over 20 similar function and looking for way to not repeat same thing every time when i create new function
Is there anyway to make it dynamic/smart ?
Index function is receive calls from other server, they can pass function name and data to index
public function index() {
if (isset($this->request->post)) {
$data = $this->request->post;
if ($this->api_key($data['key'])) {
call_user_func(array($this, $data['function_name']), $data);
}
}
}
This are the similar functions
public function addDelivery($data) {
if (!empty($data)) {
$this->load->model('api');
$query = $this->model_api->addDelivery($data);
if ($query === true) {
$json['success'] = true;
}else{
$json['error'] = $query;
}
echo json_encode($json);
}
}
public function addStatus($data) {
if (!empty($data)) {
$this->load->model('api');
$query = $this->model_api->addStatus($data);
if ($query === true) {
$json['success'] = true;
}else{
$json['error'] = $query;
}
echo json_encode($json);
}
}
public function editDelivery($data) {
if (!empty($data)) {
$this->load->model('api');
$query = $this->model_api->editDelivery($data);
if ($query === true) {
$json['success'] = true;
}else{
$json['error'] = $query;
}
echo json_encode($json);
}
}
public function editStatus($data) {
if (!empty($data)) {
$this->load->model('api');
$query = $this->model_api->editStatus($data);
if ($query === true) {
$json['success'] = true;
}else{
$json['error'] = $query;
}
echo json_encode($json);
}
}
CodePudding user response:
You could use call_user_func()
to replace the extra functions, as long as:
- You don't want to use those methods outside the
index()
method. - The name in
$data['function_name']
matches the method you want to call.
It could work something like this:
public function index() {
if (isset($this->request->post)) {
$data = $this->request->post;
if ($this->api_key($data['key']) && !empty($data)) {
$this->load->model('api');
$query = call_user_func([$this->model_api, $data['function_name']], $data);
if ($query === true) {
$json['success'] = true;
} else {
$json['error'] = $query;
}
echo json_encode($json);
}
}
}
I cannot test this code, so I cannot be certain it works.