Как загрузить одну вспомогательную функцию во все функции контроллера, не вызывая ее каждый раз во всех функциях

Я хочу добавить эти вспомогательные функции во всех функциях контроллера

// this is my helper file custom_helper.php

// $autoload['helper'] = array('url','form', 'custom_helper');

function notifications()
{
$CI = get_instance();
$CI->load->model('custom_model');
$select = "id, name";
$tableName = "users";
$whereCondition = "created_at = CURDATE()";
$result = $CI->custom_model
->FetchWithSelect($select,$tableName,$whereCondition);
return $result;
}

0

Решение

Создайте вспомогательный файл в папке application / helper: xyz_helper.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

function notifications()
{
$CI = get_instance();
$CI->load->model('custom_model');
$select = "id, name";
$tableName = "users";
$whereCondition = "created_at = CURDATE()";
$result = $CI->custom_model
->FetchWithSelect($select,$tableName,$whereCondition);
return $result;
}

затем откройте файл application / config / autoload.php: добавьте

$autoload['helper'] = array('url', 'file','form','xyz');

Также вам не нужно помещать «custom_helper» в $ autoload [‘helper’], просто поместите «custom» и файл в application / helper / custom_helper.php

2

Другие решения

В /application/config/autoload.php измените:

$autoload['helper'] = array();

в

$autoload['helper'] = array('html', 'url');
1

Ваш контроллер, вероятно, расширяет класс контроллера Codeigniter. Итак, вам нужен еще один класс, расширяющий его:

<?php

class Basecontroller extends CI_Controller
{
public function notifications()
{
$CI = get_instance();
$CI->load->model('custom_model');
$select = "id, name";
$tableName = "users";
$whereCondition = "created_at = CURDATE()";
$result = $CI->custom_model
->FetchWithSelect($select,$tableName,$whereCondition);
return $result;
}
}

Тогда во всех ваших контроллерах расширяйте этот класс!

<?php

class Home extends Basecontroller
{
public function someActionOrOther()
{
$this->notifications(); // now works
}
}
0

Вызывая вспомогательную функцию в конструкторе каждого контроллера, я не думаю, что вспомогательную функцию нужно было вызывать в каждой функции контроллера.

0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector