how to pass data from controller to custom hooks in codeigniter3 - php

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

Related

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

Simple way to check login session on all controller

I am storing admin login in session in login controller.
Now i want to check user login session on all other controller.
Can someone help with simplest way to do this?
i would use a hook here - because your session validation should be always the first thing before you do anything else
in your application/config/hooks.php type this
$hook['pre_controller'][] = array(
"class" => "AppSessionValidator",
"function" => "initialize",
"filename" => "AppSessionValidator.php",
"filepath" => "hooks"
);
After that create a File in application/hooks/
named AppSessionValidator.php and type this kind of code in
class AppSessionValidator
{
private $ci;
private $strRedirectUrl = "/login/";
private $currentController;
private $arrExludedControllers = array("login");
public function __construct()
{
$this->ci = &get_instance();
$this->currentController = $this->ci->router->class;
}
public function initialize()
{
if (!$this->ci->session->userdata("is_logged_in") && !in_array($this->currentController, $this->arrExludedControllers)
{
redirect($this->strRedirectUrl);
}
}
}
Since you want to check login session on all controllers, i think the best way to go would be to use the autoload file in config.
Create a helper file check_session.php in application/helpers/ and add this
<?php
//Get Current CI Instance
$CI = & get_instance();
//Use $CI instead of $this
//Check for session details here, here's an example
$user = $CI->session->userdata('user_id');
//Get current controller to avoid infinite loop
$controller = $CI->router->class;
//Check if user session exists and you are not already on the login page
if(empty($user) && $controller != "login" ) {
redirect('login/', 'refresh');
}
else {
return true;
}
?>
Now go to your autoload.php file at application/config/autoload.php and look for where your helper array is declared and add check_session to your helper list
$autoload['helper'] = array();
$autoload['helper'] = array('url','utility', 'check_session');
With that... you should be able to check sessions automatically on all controllers
while login:
$this->session->set_userdata('is_logged_in',TRUE);
Create model:
class Security_model extends CI_Model{
public function is_logged_in(){
if($this->session->userdata('is_logged_in')){
return true;
}
else{
$this->session->set_flashdata('feedback','Please login!');
redirect('login');
}
}
}
On your Any controller's Contructor:
$this->load->model('security_model');
$this->security_model->is_logged_in();

Hooks and a MY_Model

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

ZendFramework 2 - how do you handle from controller the layout head body footers like in ZF1?

How to do the following __construct section shown in ZF1 on the fly in ZF2 way?
I have tried $this->headTitle('..'); by ommiting ->view call, but it still fail by throwing:
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for headTitle
public function __construct() { //init is gone
$this->_helper->layout()->setLayout('brand');
$this->HeadTitle($this->title)->setIndent(8);
$this->view->headMeta()->appendName('keywords', $this->keyword)->setIndent(8);
$this->view->headMeta()->appendName('description', $this->description)->setIndent(8);
$this->view->headMeta()->appendName('Language', 'en')->setIndent(8);
$this->view->headMeta()->appendName('dc.title', $this->title)->setIndent(8);
$this->view->headMeta()->appendName('dc.keywords', $this->keyword)->setIndent(8);
$this->view->headMeta()->appendName('dc.description', $this->description)->setIndent(8);
$this->view->headLink()->appendStylesheet('/css/main.css')->setIndent(8);
$this->view->headLink()->appendStylesheet('/jquery/css/custom-theme/jquery-ui-
1.8.20.custom.css')->setIndent(8);
$post = $this->getRequest()->getPost();
$get = $this->getRequest()->getQuery();
}
You could access to 'renderer' object in your action controller:
public function indexAction()
{
$renderer = $this->getServiceLocator()->get('Zend\View\Renderer\PhpRenderer');
$renderer->headTitle('My title');
return new ViewModel();
}
I got the same question and I have developed an ZF2 plugin to use headTitle like in layout.phtml file.
https://github.com/remithomas/rt-headtitle
public function indexAction(){
$this->headTitle("My website")->setSeparator(" - ")->append("easy ?!");
return new ViewModel();
}
Write a function to handle it for all actions in a controller
protected function setHeadTitle($title = ''){
if(!empty($title)){
$renderer = $this->getServiceLocator()->get('Zend\View\Renderer\PhpRenderer');
$renderer->headTitle($title);
}
}
Use the function in your action
public function loginAction()
{
$this->setHeadTitle("Login");
//write some other codes
}
Write a plugin for all module
class HeadTitlePlugin extends AbstractPlugin
{
public function setHeadTitle($title = '')
{
if (! empty($title)) {
$renderer = $this->getController()->getServiceLocator()->
get('Zend\View\Renderer\PhpRenderer');
$renderer->headTitle($title);
}
}
}
Attach the plugin in module config
'controller_plugins' => array(
'invokables' => array(
'HeadTitlePlugin' => 'Modulename\Controller\Plugin\HeadTitlePlugin'
)
),
Call the plugin function in controller action
public function indexAction()
{
$this->HeadTitlePlugin()->setHeadTitle("Signup");
// other codes
}
Thats all

Categories