Previously I was using Codeigniter 3 and I load all helpers, libraries using the autoload.php
. Now migrating to CI4 where I tried the following,
- I tried loading my helper files in the
BaseController.php
- I tried loading the helper in
__construct
at myController.php
as well.
I have a Library say Demo.php and function check_user_logged()
. When I called my get_cookie()
from the function, it says Call to undefined function App\Libraries\get_cookie()
.
This function check_user_logged()
when it is called from a controller as,
<?php
use App\Libraries\Demo;
protected $demo;
public function __construct()
{
helper('cookie');
$this->demo = new Demo();
}
public function index()
{
$this->demo->check_user_logged();
}
The Demo.php
<?php
namespace App\Libraries;
Class Demo
{
public function check_user_logged()
{
print_r(get_cookie('name')); // just for simplicity printing the cookie
}
}
Is it the only way to load the cookie helper in Demo library constructor? Or I am missing something?
CodePudding user response:
I personally prefer loading a helper in a specific function/class that needs it.
Option 1:
Loading the cookie helper in the library's constructor.
<?php
namespace App\Libraries;
class Demo
{
public function __construct()
{
helper('cookie');
}
public function check_user_logged()
{
print_r(get_cookie('name')); // just for simplicity printing the cookie
}
}
Option 2:
Loading the cookie helper in the library's method.
The helper function
get_cookie()
gets the cookie from the currentRequest
object, not fromResponse
. This function checks the$_COOKIE
array if that cookie is set and fetches it right away.
<?php
namespace App\Libraries;
class Demo
{
public function check_user_logged()
{
helper('cookie');
print_r(get_cookie('name')); // just for simplicity printing the cookie
}
}
Option 3A:
Getting the cookie in the current Response's cookie collection.
<?php
namespace App\Libraries;
class Demo
{
public function check_user_logged()
{
print_r(\Config\Services::response()->getCookie('name')); // just for simplicity printing the cookie
}
}
Option 3B:
Using the cookies(...)
global function. No need to load any helpers.
Fetches the global
CookieStore
instance held byResponse
.
<?php
namespace App\Libraries;
class Demo
{
public function check_user_logged()
{
print_r(cookies()->get('name')); // just for simplicity printing the cookie
}
}
CodePudding user response:
Loading the generic CI4 cookie helper in the BaseController should work.
protected $helpers = ['cookie','my_security_helper' ];
Can you post your original faulty code?