Hooks and a MY_Model - php

I was hoping I could find someone that could answer a question for me. I'm Jamie Rumbelow's MY_Model and curious to know if I can use it functionality if I need to run a function from it inside of a hook.
$hook['pre_controller'] = array(
'class' => 'Logins_model',
'function' => 'pre_init', // Run some sort of get function here
'filename' => 'logins_model.php',
'filepath' => 'models',
//'params' => array('beer', 'wine', 'snacks')
);
EDIT 2 : Would you say that this is an okay hook or have I lost all grasp of this?
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class User_hook {
private $CI;
function __construct() {
$CI =& get_instance();
}
public function validate_user() {
$this->CI->load->model('logins_model', 'login'); //Alternatively put this in autoload.php
$this->CI->load->model('users_model', 'user');
$user_id = $this->CI->session->userdata('user_id');
if (($user_id !== TRUE) && (!is_numeric($user_id)) && (strlen($user_id) < 5))
{
redirect('login');
}
$user_data = $this->CI->user->get($user_id);
$user_data->login = $this->CI->login->get_by('user_id', $user_id);
if (empty($user_data))
{
redirect('login');
}
}
}

Yes, but not using the code that you suggest. You need to create your own custom hook class and then load (or autoload) and call your model there.
It is also important to note that this will not work for pre_controller hooks as the CodeIgniter object is not yet available. The hook must be post_controller_constructor or later. Take this hook class for example for hooks/some_hook.php.
class some_hook {
private $CI;
function __construct() {
$CI =& get_instance();
}
public function some_function() {
$this->CI->load->model('logins_model'); //Alternatively put this in autoload.php
$this->CI->logins_model->some_function_in_logins();
}
}
Then you would load it using:
$hook['post_controller_constructor'] = array(
'class' => 'some_hook',
'function' => 'some_function',
'filename' => 'some_hook.php',
'filepath' => 'hooks'
);

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

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

CodeIgniter Hooks to display content on all pages

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);

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