CodeIgniter Hooks to display content on all pages - php

I have a sidebar displayed on all my websites pages the same content should be displayed each time:
current cash
username
more info...
For the username I'm using the session within the regular controllers so that's alright but for the cash, I need to make a call to the database. I've tried to use hooks but I can't figure out how to display the info in the view (the variable is undefined).
I'm stuck when loading the session.
I get the message: Unable to locate the specified class: Session.php eventhough my session library is autoloaded and I added it one more time in the hook, just in case...
autoload.php
$autoload['libraries'] = array('database','session','form_validation','pagination', 'template');
My hooks.php
$hook['post_controller_constructor'] = array(
'class' => 'get_info_general',
'function' => 'get_info_general',
'filename' => 'get_info_general.php',
'filepath' => 'hooks',
'params' => ''
);
My get_info_general.php
class get_info_general extends CI_Controller{
private $CI;
public function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('session');
$this->load->library('database');
}
function get_info_general(){
$this->load->model('usersModel');
$cash = $this->usersModel->check_cash_player();
$data['cash'] = $cash;
} }
In UsersModel:
public function check_cash_player(){
$currentUserID = $this->usersModel->get_user_id();
$query = $this->db
->select('cash')
->from('place')
->where('id_player', $currentUserID)
->get();
return $query->row('cash');
}
UPDATE:
After #alexander popov suggestion I changed the code to:
class get_info_general {
private $CI;
public function __construct() {
$CI =& get_instance();
$CI->load->helper('url');
$CI->load->library('session');
}
function get_info_general(){
$this->load->model('usersModel');
$cash = $this->usersModel->check_cash_player();
$data['cash'] = $cash;
} }
And I get: Undefined property: get_info_general::$load
UPDATE 2:
Using the code provided here I don't get any error message and my page is displayed. However $cash is still undefined in my page. Adding the following code to get_info_general.php doesn't help:
$data['cash'] = $cash;
$data['main_content'] = 'loginForm';
$this->load->view('templates/default',$data);

Related

how to pass data from controller to custom hooks in codeigniter3

I have a hooks class in my app where I want to send my session data from my controller. but I am having problem passing data. I don't know whether is it possible to send data from controller to hooks.
here is an exampple of an hooks class the code is below
function switchUser()
{
$CI = &get_instance();
$user_id=$CI->uid;
if ($user_id == 'client') {
echo "hello";
}
}
here is my controller
class Client_Controller extends MX_Controller
{
public $uid;
function __construct($dbase=array())
{
parent::__construct();
$this->uid=$this->session->userdata("uid");
}
}
In hooks.php file, I have the following code
$hook['pre_controller'] = array(
'function' => 'switchDatabase',
'filename' => 'switchDatabase.php',
'filepath' => 'hooks'
);
Please help me to solve this issue.
Hope this will help you :
In your switchUser method
use this
$CI->session->userdata("uid")
Instead of this
$CI->uid
Whole code should be like this :
function switchUser()
{
$CI = &get_instance();
$user_id = $CI->session->userdata("uid")
if ($user_id == 'client') {
echo "hello";
}
}
For more : https://www.codeigniter.com/user_guide/general/hooks.html

codeIgniter can't access session in Hook

I have created on hook to set current visiting URL to session. I have to use this URL later on. I have called session method of codeIgniter using $this->CI =& get_instance(); and then $this->CI->session->userdata but it is giving
Trying to get property of non-object on $this->CI->session->userdata line
I have done following things to enable hooks in CI
config.php
$config['enable_hooks'] = TRUE;
hooks.php
$hook['pre_controller'] = array(
'class' => 'Preclass',
'function' => 'checkreq',
'filename' => 'preclass.php',
'filepath' => 'hooks',
'params' => array()
);
preclass.php
class Preclass
{
private $CI;
public function __construct()
{
$this->CI =& get_instance();
}
public function checkreq($value='')
{
var_dump($this->CI->session->userdata);
die;
}
}
Note: Don't close this post as Duplicate of PHP errors. As I know about errors. This is in CodeIgniter and I want to check session before any controller method gets invoked.
From comment: "But I want it before controller methods invoke even before constructor"
To solve your issue, this is about the best you can do:
Make an MY_Controller.php in application/core:
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
// class is just an alias for the controller name
if (!$this->user->is_allowed($this->router->class)) {
redirect('somepage');
}
}
}
Then have all your controllers extend MY_Controller:
class Somecontroller extends MY_Controller {
public function __construct() {
parent::__construct();
// nothing below the above line will be reached
// if the user isn't allowed
}
}
Whether or not you have a __construct() method in the class: nothing will happen so long as the user isn't allowed to access the page e.g. nothing after parent::__construct() will be called - even methods. Again, the fact that the parent constructor is called is implied if no constructor exists for the controller.
Note: if you autoload a model and do the same logic in the MY_Controller in the models __construct() the same results should be achieved. I just find this method cleaner.
This is not possible in Codeigniter as session itself a library and you are trying to call it pre_controller. When controllers not loaded yet how can you use it even in hook.
Solution
You may use post_controller_constructor instead what are using now
$hook['post_controller_constructor'] = array(
'class' => 'Preclass',
'function' => 'checkreq',
'filename' => 'preclass.php',
'filepath' => 'hooks',
'params' => array()
);
otherwise you may also use native session here
hope it help

How to access static variable declared in Controller from Library in Codeigniter?

I want to access the static variable declared in Codeigniter Controller and I want to use it in the Library. Here is the code.
Controller Location & Name:
Name : Console
Location : ./application/controllers/Console.php
Library Location & Name:
Name : Api
Location : ./applications/libraries/Api.php
Console.php
class Console extends CI_Controller {
public static $access_agents = [
'2017_app_v1.0',
'2017_api_v1.0'
];
public static $developer_secret = [
'HTTP_X_DEVELOPER_SECRET' => 'XYZ'
];
}
Api.php
class Api
{
public static $CI;
public function __construct()
{
self::$CI = & get_instance();
}
public static function print_services_list($list)
{
if(self::get_custom_header(##### CALL_STATIC_VARIABLE_HERE ######))
$array = [
'status' => '200',
'message' => 'OK',
'text' => "List of APIs under this Interface gateway.",
'data' => $list
];
self::print_json_array($array);
}
}
As I described I want to access the Static variable declared in Console Class into here where I have used ##### CALL_STATIC_VARIABLE_HERE ######
I have tried things like these: (I knew it wouldn't work probably and I was right)
Console::$developer_secret - NOT WORKING
self::$CI->Console::$developer_secret - NOT WORKING
self::$CI->Console->$developer_secret - NOT WORKING
Why don't you place these variables in the config file?
Create a PHP file in application/config folder. Name it whatever you want. Then place your variables in the file as below.
<?php
$config['static_var']['your-static-variable-name'] = 'Whatever value you want to initialize'
If you want to add another variable
<?php
$config['static_var']['your-another-static-variable-name'] = 'Whatever value you want to initialize'
Once the file is saved please load the config file in your library.
class Api
{
protected $CI;
protected $my_var;
protected $my_another_var;
public function __construct()
{
$this->CI =& get_instance();
$this->CI->load->config('your config file name');
$this->my_var = $this->CI->config->item('your-static-variable-name','static_var');
$this->my_another_var = $this->CI->config->item('your-another-static-variable-name','static_var');
}
}
Now use $myvar wherever you want. Hope this can help you.

What is the best prestashop-way to include tpl in AdminController?

I need interacts with a .tpl file in my adminController class, but when I try to do that, this error appears
Fatal error: Call to undefined method RiddlePageController::getCacheId() in /home/USER/public_html/prestashop/modules/RiddleModule/controllers/admin/RiddlePage.php on line 48
This is my admin controller code:
class RiddlePageController extends AdminController {
public function __construct()
{
$this->html = '';
$this->display = 'view';
$this->meta_title = $this->l('metatitle');
$this->module = "RiddleModule";
parent::__construct();
}
public function initContent()
{
$this->postProcess();
$this->show_toolbar = true;
$this->display = 'view';
$this->meta_title = $this->l('Modulo');
parent::initContent();
}
public function initToolBarTitle()
{
$this->toolbar_title = $this->l('Titulo');
}
public function initToolBar()
{
return true;
}
public function renderView() {
$this->context->smarty->assign(
array(
'img1' => "http://www.free-3dmodels.com/image/Flowers-3D-Model-3662994d.png",
'img2' => "http://www.all3dmodel.com/Images/39.jpg"
)
);
// in return have error "getCacheId"
return $this->display(__FILE__, 'content.tpl', $this->getCacheId());
// return "<b>This works fine!!</b>";
}
my tpl file have only {$img1} and {$img2} for testing.
Maybe I do all wrong, and this is not the best way to make in my own admin page.
Your error is because the AdminController class doesn't have the getCacheId method.
To answer to your question you have to made some little fix.
First (extends ModuleAdminController not AdminController):
class AdminRiddlePageController extends ModuleAdminController
{
}
Then if you want to view your custom tpl, place a view.tpl file in:
prestashop/modules/RiddleModule/views/templates/admin/riddlepage/helpers/view/
or
prestashop/modules/RiddleModule/views/templates/admin/riddle_page/helpers/view/ (I don't remember well if the underscore is necessary)
And your renderView method should be like this:
public function renderView()
{
/* Your code */
/* Use this snippet to assign vars to smarty */
$this->tpl_view_vars = array(
'myvar' => 1,
'secondvar' => true
)
return parent::renderView();
}
AdminController class has not an implementation of display method you use to render TPL.
You can use something like this after set module var:
$this->module->display(_PS_MODULE_DIR_.$this->module->name.DIRECTORY_SEPARATOR.$this->module->name.'.php', 'content.tpl')
Good luck.
As #TheDrot told us, the answer are in using $this->context->smarty->fetch(location), but not in renderList, but in the return statement of renderView is OK and prestashop get the tpl file and load correctly the smarty variables. Ex:
public function renderView(){
$this->context->smarty->assign(
array(
'img1' => "http://www.free-3dmodels.com/image/Flowers-3D-Model-3662994d.png",
'img2' => "http://www.all3dmodel.com/Images/39.jpg"
)
);
return $this->context->smarty->fetch(_PS_MODULE_DIR_ . "RiddleModule/controllers/front/prueba.tpl");
}
The file location isn't important to load the TPL file in this case

can not access user data in hooks - code iginitor

This is my hooks.php
$hook['pre_controller'] = array(
'class' => 'UpdateSession',
'function' => 'index',
'filename' => 'UpdateSession.php',
'filepath' => 'hooks',
'params' => array()
);
And this is my UpdateSession.php which is placed in hooks folder.
<?php
class UpdateSession extends CI_Controller
{
public function __construct()
{
$this->CI =& get_instance();
$this->CI->load->library("session");
}
public function index()
{
if($this->CI->session->userdata('user_id'))
{
$query = $this->CI->db->get_where('cp_sessions', array('user_id' => $this->CI->session->userdata('user_id')));
$session_info = $query->row_array();
if($session_info['session_id'] != $this->CI->session->userdata('user_id'))
{
$new_session_id = array('session_id' => $this->CI->session->userdata('user_id'));
$this->db->update('cp_sessions', $new_session_id, array('user_id' => $this->CI->session->userdata('user_id')));
}
}
}
}
This gives me the following error
Fatal error: Call to a member function library() on a non-object in
C:\xampp\htdocs\website\pokeradda\application\hooks\UpdateSession.php on line 8
I have tried to remove extends CI_Controller but same problem is there.
if you are using pre-controller hook means you are calling your class before controllers are loaded. so that You can not get the CI instance in this hook, because CI is not loaded yet!
you can’t get the CI instance in SOME hooks :
CAN’T : pre_system , pre_controller
CAN : post_controller_constructor, post_controller, display_override, cache_override, post_system
you can use My_controller and extend your controller from it. add the functionality in My_controller constructor. (a suggestion as a work-around)

Categories