codeigniter hooks can't get $ci object to work - codeigniter

I've just started looking at hooks today not 100% sure what I'm doing wrong but I'm getting an error when I try and use the $ci object in my function.
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: hooks/language.php
Line Number: 12
My hooks file looks like this. It's in the hooks directory in my application folder.
class Language{
var $ci;
public function __construct(){
$this->ci =& get_instance();
}
function get_language(){
echo $this->ci->session->userdata('language');
}
}
I need to get the value in the session to use in my function. Am I not supposed to do it like this?
Thanks you!

In the Base4/5.php file the get_instance() function is written and it is conditionally loaded so it won’t be present until after it is loaded. And that's the reason its giving error.

Just done another Google search and it seems the Hook I was using Pre Controller was before the object was created I've changed the hook and it seems to work fine now.

I used post_controller_constructor for my hook, then the CI worked.
And I had to turn on hooks in the config.

Below is default application/config/hooks.php
// Stores the requested URL, which will sometimes be different than previous url
$hook['post_controller'][] = array(
'class' => 'App_hooks',
'function' => 'save_requested',
'filename' => 'App_hooks.php',
'filepath' => 'hooks',
'params' => ''
);
// Allows us to perform good redirects to previous pages.
$hook['post_controller'][] = array(
'class' => 'App_hooks',
'function' => 'prep_redirect',
'filename' => 'App_hooks.php',
'filepath' => 'hooks',
'params' => ''
);
// Maintenance Mode
$hook['post_controller_constructor'][] = array(
'class' => 'App_hooks',
'function' => 'check_site_status',
'filename' => 'App_hooks.php',
'filepath' => 'hooks',
'params' => ''
);
/* End of file hooks.php */
/* Location: ./application/config/hooks.php */
I have changed it to below and it works fine for me
// Stores the requested URL, which will sometimes be different than previous url
$hook['post_controller_constructor'][] = array(
'class' => 'App_hooks',
'function' => 'save_requested',
'filename' => 'App_hooks.php',
'filepath' => 'hooks',
'params' => ''
);
// Allows us to perform good redirects to previous pages.
$hook['post_controller'][] = array(
'class' => 'App_hooks',
'function' => 'prep_redirect',
'filename' => 'App_hooks.php',
'filepath' => 'hooks',
'params' => ''
);
// Maintenance Mode
$hook['post_controller'][] = array(
'class' => 'App_hooks',
'function' => 'check_site_status',
'filename' => 'App_hooks.php',
'filepath' => 'hooks',
'params' => ''
);
/* End of file hooks.php */
/* Location: ./application/config/hooks.php */

Related

call several functions within same class in hooks

I need to call several functions from the same class in a hook file.
This is my current code:
$hook['post_controller_constructor'] = array(
'class' => 'get_info_general',
'function' => 'prepare',
'filename' => 'get_info_general.php',
'filepath' => 'hooks',
'params' => ''
);
$hook['post_controller_constructor'] = array(
'class' => 'get_info_general',
'function' => 'get_info_general',
'filename' => 'get_info_general.php',
'filepath' => 'hooks',
'params' => ''
);
$hook['post_controller_constructor'] = array(
'class' => 'get_info_general',
'function' =>'get_achievements',
'filename' => 'get_info_general.php',
'filepath' => 'hooks',
'params' => ''
);
Unfortunately only the last function get_achievements is called. I also tried:
$hook['post_controller_constructor'] = array(
'class' => 'get_info_general',
'function' => 'prepare',
'function' => 'get_info_general',
'function' => 'get_achievements',
'filename' => 'get_info_general.php',
'filepath' => 'hooks',
'params' => ''
);
But it gives me the same result.
Is there any way to get all three functions to be called correctly, one after another? I didn't find documentation or similar questions.
You just need to make multidimensional array. From docs:
If want to use the same hook point with more than one script, simply make your array declaration multi-dimensional, like this:
$hook['post_controller_constructor'][] = array(
'class' => 'get_info_general',
'function' => 'prepare',
'filename' => 'get_info_general.php',
'filepath' => 'hooks',
'params' => ''
);
$hook['post_controller_constructor'][] = array(
'class' => 'get_info_general',
'function' => 'get_info_general',
'filename' => 'get_info_general.php',
'filepath' => 'hooks',
'params' => ''
);
$hook['post_controller_constructor'][] = array(
'class' => 'get_info_general',
'function' =>'get_achievements',
'filename' => 'get_info_general.php',
'filepath' => 'hooks',
'params' => ''
);
Notice the brackets after each array index:
$hook['post_controller_constructor'][]

Sorting in CakePHP with custom routes

I was trying to find a solution on-line (as always) but came up with nothing obviously.
I'm using CakePHP and I need to add some sorting into some controllers. I would also like to create custom routes for that. So here's my code that is not working (pagination works, sorting nope):
RatesController.php:
public $paginate = array(
'Rate' => array(
'limit' => 10,
'order' => array(
'Rate.created' => 'desc'
),
'conditions' => array( 'Rate.accepted' => 1 ),
//'fields' => array('Rate.*', 'User.username')
),
'Airline' => array(
'limit' => 50,
/*'order' => array(
'Airline.rate' => 'desc',
'Airline.name' => 'asc'
),*/
'conditions' => array(
'Airline.rate >' => 0
),
'fields' => array('Airline.id', 'Airline.name', 'Airline.image_id', 'Airline.rate', 'Image.*')
)
);
function index($category = 'airlines'){
pr($this->request);
$data = $this->paginate('Airline');
pr($data);
}
And in view:
$this->Paginator->options(array(
'url' => array(
'controller' => 'rates',
'action' => 'index',
'category' => $category
)
));
echo $this->Paginator->first('«', array('escape' => false), null, array('class' => 'disabled', 'escape' => false));
echo $this->Paginator->prev('<', array('escape' => false), null, array('class' => 'disabled', 'escape' => false));
echo $this->Paginator->numbers(array(
'modulus' => 6,
'separator' => false
));
echo $this->Paginator->next('>', array('escape' => false), null, array('class' => 'disabled', 'escape' => false));
echo $this->Paginator->last('»', array('escape' => false), null, array('class' => 'disabled', 'escape' => false));
echo' sort by ';
echo $this->Paginator->sort('Airline.rate');
echo' or by ';
echo $this->Paginator->sort('Airline.name');
Routes:
Router::connectNamed(array('page'), array('default' => false, 'greedy' => false));
Router::connectNamed(array('sort', 'direction'), array('default' => false, 'greedy' => false));
Router::connect('/rate-airlines', array('controller' => 'rates', 'action' => 'index', 'category' => 'airlines'));
/*
Router::connect(
'/rate-airlines/:page/',
array('controller' => 'rates', 'action' => 'index', 'category' => 'airlines'),
array(
'named' => array('page' => '[a-z]+')
)
);
Router::connect(
'/rate-airlines/:page/:sort/:direction',
array('controller' => 'rates', 'action' => 'index', 'category' => 'airlines'),
array(
'pass' => array('page', 'sort', 'direction'),
//'id' => '[0-9]+',
'named' => array('page' => '[\d]+', 'sort', 'direction')
)
);*/
Router::connect(
'/rate-airlines/:sort/:direction',
array('controller' => 'rates', 'action' => 'index', 'category' => 'airlines'),
array(
'named' => array('sort', 'direction')
)
);
I seriously have no idea why it's not working, I've already spent hours trying to make it work, seeking answers.
Ps. No matter what I did I couldn't manage to put :sort and :direction into named array in request:
CakeRequest Object
(
[params] => Array
(
[plugin] =>
[controller] => rates
[action] => index
[named] => Array
(
)
[pass] => Array
(
)
[sort] => Airline.rate
[direction] => asc
[category] => airlines
[isAjax] =>
)
...
)
Any ideas please?
Mike
You really shouldn’t use route parameters for sorting. It was such a bad idea that CakePHP have dropped them in the forth-coming 3.x release.
Instead, use query string parameters. That’s exactly what they’re for: manipulating a single view. If you have a list, pass parameters like ‘sort’ and ‘direction’ there.
Say you have a URL like http://example.com/rates/?sort=name&direction=asc, you can then parse it in your controller as follows:
<?php
class RatesController extends AppController {
public function index() {
$sort = isset($this->request->query['sort']) ? $this->request->query['sort'] : 'created';
$direction = isset($this->request->query['direction']) ? $this->request->query['direction'] : 'desc';
$this->Paginator->settings = array(
'order' => array($sort => $direction)
);
$rates = $this->paginate('Rate');
$this->set(compact('rates'));
}
}
I also like to go one step further and use query strings for pagination…
<?php
class AppController extends Controller {
public $paginate = array(
'paramType' => 'querystring'
);
}
…But that’s just personal preference.
The above was written during a long day. After thinking about it, CakePHP handles sorting in pagination out of the box. You don’t need to manually specify routes containing the name parameters.
So long as you use the Pagination component and Paginator helper (as you have done), and defined a single route for your controller action, you don’t need to do anything else. In your case, your controller would look like:
<?php
class RatesController extends AppController {
public function index() {
$rates = $this->paginate('Rate');
$this->set(compact('rates'));
}
}
And your view would look like:
<?php echo $this->Paginator->sort('Airline.name'); ?>
If you wanted to rewrite /rates to /rates-airlines, then your single route would look like this:
<?php
Router::connect('/rates-airlines', array(
'controller' => 'rates',
'action' => 'index',
));
With the above, the paginate call will take into account the column to sort by and the direction.
Sorry for the convoluted answer above!
thanks for your replies. The thing is that I really need custom routing for pagination, so I finally managed to achieve what I wanted using following code:
In AppController.php (note that all $this->request->query[...] variables were added just because I also wanted to use sorting interface via forms with GET method)
function beforeFilter() {
if (isset($this->request->params['page'])) {
$this->request->params['named']['page'] = $this->request->params['page'];
}elseif( isset($this->request->query['page']) ){
$this->request->params['named']['page'] = $this->request->query['page'];
}
if (isset($this->request->params['sort'])) {
$this->request->params['named']['sort'] = $this->request->params['sort'];
}elseif (isset($this->request->query['sort'])) {
$this->request->params['named']['sort'] = $this->request->query['sort'];
}
if (isset($this->request->params['direction'])) {
$this->request->params['named']['direction'] = $this->request->params['direction'];
}elseif (isset($this->request->query['direction'])) {
$this->request->params['named']['direction'] = $this->request->query['direction'];
}
in routes.php
Router::connect('/rates-airlines', array('controller' => 'rates', 'action' => 'index', 'airlines'));
Router::connect(
'/rates-airlines/:page',
array('controller' => 'rates', 'action' => 'index', 'airlines'),
array(
'named' => array('page' => '[\d]+')
)
);
Router::connect(
'/rates-airlines/:page/:sort/:direction',
array('controller' => 'rates', 'action' => 'index', 'airlines'),
array(
'named' => array('page' => '[\d]+', 'sort', 'direction')
)
);
Router::connect(
'/rates-airlines/:sort/:direction',
array('controller' => 'rates', 'action' => 'index', 'airlines'),
array(
'named' => array('sort', 'direction')
)
);
Hope someone will find this useful!
Mike
There is an easier way. Just add one more route with '/*':
Router::connect('/rates-airlines', array('controller' => 'rates', 'action' => 'index', 'airlines'));
Router::connect('/rates-airlines/*', array('controller' => 'rates', 'action' => 'index', 'airlines'));
And all will work correctly.

The model name you are loading is the name of a resource that is already being used: model

I load my models like this
class Admin_user extends CI_Controller {
function __construct()
{
parent::__construct();
CheckLoginIn();
$this->load->model('admin_user_model','model');
}
function index(){
//my function..
}
}
Initially every thing was good...
then i had to use hooks..
my hooks.php file
$hook['pre_controller'] = array(
'class' => 'MyClass',
'function' => 'get_code',
'filename' => 'Myclass.php',
'filepath' => 'hooks'
);
now i get this error.
The model name you are loading is the name of a resource that is already being used: model
however if i set $config['enable_hooks'] = FALSE; everything works fine...
Got the answer.. i had to user post_controller_constructor instead of pre_controller so my hooks file will be
$hook['post_controller_constructor'] = array(
'class' => 'MyClass',
'function' => 'get_code',
'filename' => 'Myclass.php',
'filepath' => 'hooks'
);

Drupal 7 ajax and session

I have created a .module file which includes a form and an ajax call back. Here is a simple code of the .module file:
function form_registration_form($form, &$form_state) {
$form['registration']['email'] = array(
'#type' => 'textfield',
'#required' => TRUE,
'#size' => 44,
'#maxlength' => '80',
'#attributes'=> array('placeholder' => 'Email','data-email'=>'','data-min-chars'=>'5'),
);
$form['registration']['password'] = array(
'#type' => 'password',
'#required' => TRUE,
'#size' => 44,
'#maxlength' => '80',
'#attributes'=> array('placeholder' => 'Password'),
);
$form['registration']['submit'] = array(
'#value' => 'SIGN IN',
'#type' => 'submit',
'#submit' => array('form_registration_handler'),
);
return $form;
}
and in the function form_registration_handler I create a session (name it test).
Here is the ajax menu call back function:
function mymodule_menu() {
$items['ajax/innerAction'] = array(
'title' => 'Browser Inner Action',
'page callback' => 'innerActionCallBack',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function innerActionCallBack() {
header('Access-Control-Allow-Origin: *');
drupal_session_start();
print session_id();
}
This function is used on my page.tpl.php file to create an ajax to server.
The problem here is when I call the ajax, the session id is different when
I refresh the browser and I can not retreive the Session test that I created earlier.
Do you know what is happening here. Any helps are really appreciated.
Ok so I have figured out the answer. I have to login the user into Drupal first so that Drupal can retrieve the correct sessionID.

creating and managing cache and session in Zend Framwork 2

i just started working with ZF2 ...
i want to initialize cache and session in config file and be able too use it in the application ( every where ) either using service manager or ... i have been searching Google for hours with no lock ... couldn't find anything useful in the documentations and ...
i tried this in module.config.php(Application module):
'service_manager' => array(
'factories' => array(
'cache' => '\Zend\Cache\StorageFactory',
),
),
'cache' => array(
'storage' => array(
'adapter' => 'Filesystem',
'options' => array(
'cache_dir' => __DIR__ . '/../../../data/cache'
),
),
'plugins' => array('WriteControl', 'IgnoreUserAbort'),
'options' => array(
'removeOnFailure' => true,
'exitOnAbort' => true,
'ttl' => 100
),
),
i got this error : While attempting to create cache(alias: cache) an invalid factory was registered for this instance type.
so whats the valid factory ?
so any one can help me out here ?
tanks...
Use a closure as factory instead because Zend\Cache\StorageFactory doesn't implement Zend\ServiceManager\FactoryInterface
'service_manager' => array(
'factories' => array(
'cache' => function () {
return Zend\Cache\StorageFactory::factory(array(
'storage' => array(
'adapter' => 'Filesystem',
'options' => array(
'cache_dir' => __DIR__ . '/../../../data/cache',
'ttl' => 100
),
),
'plugins' => array(
'IgnoreUserAbort' => array(
'exitOnAbort' => true
),
),
));
},
),
)
Btw. clean up your cache configuration and where you get the plugin in WriteControl and the option removeOnFailure from?
I've come to this topic from Google with the same error name but definitely different reason. Error could be caused by file not found error. If you get this error, check your config record
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
and be sure that needed file (mapper in my case) is located in the directory according to upper rules.

Resources