how can i get in ci4 instance into helper function? $CI =&get_instance(); <- that was in version 3, how does this go in version Codeigniter 4?
I made a gist for it. here is a way to do it.
- Create a helper file, you can name it whatever you want.
- Add the following codes to the helper you just created.
Content of the helper file: i.e: utility_helper.php
<?php
$CI_INSTANCE = []; # It keeps a ref to global CI instance
function register_ci_instance(\App\Controllers\BaseController &$_ci)
{
global $CI_INSTANCE;
$CI_INSTANCE[0] = &$_ci;
}
function &get_instance(): \App\Controllers\BaseController
{
global $CI_INSTANCE;
return $CI_INSTANCE[0];
}
Call
register_ci_instance($this)
at the very beginning of your base controllerNow you may use
get_instance()
where ever you want just like CI3:$ci = &get_instance()
There are three notes I want to mention
- I tested on PHP8 only.
- I'm not sure if
&
is needed when callingget_instance
. however, you have the option to use any form you want. so calling$ci = get_instance()
is ok too, but you may do$ci = &get_instance()
as you wish. - Make sure you change
\App\Controllers\BaseController
to something appropiate(i.e: your base controller). type hinting is great since IDEs understand them.
Create a common helper to keep the controller instance. Suppose here it is common_helper.php
$CI4 = new \App\Controllers\BaseController;
function register_CI4(&$_ci)
{
global $CI4;
$CI4 = $_ci;
}
In your BaseController
public $user_id;
protected $helpers = ['form', 'url', 'common']; // Loading Helper
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
register_CI4($this); // Registering controller instance for helpers;
$this->user_id = 4;
}
Now you will get the controller instance in all other helpers. Suppose a new heper user_helper
as
function show_user_id()
{
global $CI4;
echo $CI4->user_id; // Showing 4
}
I tested it in PHP Version: 8.0.6
For me, this is the best solution for me:
if (!function_exists('getSegment'))
{
/**
* Returns segment value for given segment number or false.
*
* @param int $number The segment number for which we want to return the value of
*
* @return string|false
*/
function getSegment(int $number)
{
$request = \Config\Services::request();
if ($request->uri->getTotalSegments() >= $number && $request->uri->getSegment($number))
{
return $request->uri->getSegment($number);
}
else
{
return false;
}
}
}
In CI4, just use the following:
$db = model('YourModel');
I get it (using CodeIgniter4):
in controller:
helper('login');
$isLog=isLogged($this,"user","passwd");
if($isLog)
....
else
....
in helper:
use App\Models\Loginmodel as Loginmodel;
function isLogged($ci,$e,$c){
$ci->login = new Loginmodel;
$ci->login->Like('paassword',$c);
$id=$ci->login->select('id')->where('username',$e)->findAll();
return $id;
}
I hope this helps.
© 2022 - 2024 — McMap. All rights reserved.