Skip to content

Instantly share code, notes, and snippets.

@nelson6e65
Last active August 29, 2015 14:25
Show Gist options
  • Save nelson6e65/5e3c4b79bd2989239ec2 to your computer and use it in GitHub Desktop.
Save nelson6e65/5e3c4b79bd2989239ec2 to your computer and use it in GitHub Desktop.
'Controller::beforeFilter' implementation in CodeIgniter2 example
<?php # File: application/config/hooks.php
# . . .
$hook['post_controller_constructor'] = [
'class' => 'ControllerHook',
'function' => 'beforeFilter',
'filename' => 'controller.php',
'filepath' => 'hooks',
'params' => []
];
# . . .
<?php # File: application/controller/examples.php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Examples extends MY_Controller
{
# . . .
public function index()
{
// localhost/app/examples
// MY_Controller::testBeforeFilter() will run before to call this->index()
var_dump(__METHOD__);
}
# . . .
}
<?php # File: application/core/MY_Controller.php
if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
/**
* Clase base que extiende el funcionamiento del controlador base del sistema.
*/
class MY_Controller extends CI_Controller
{
# . . .
protected function testBeforeFilter($action)
{
var_dump(__METHOD__, $action);
}
/**
* Before to filter implementation.
* This method is called before controller actions, and after constructor.
*
* @return void
* */
public function beforeFilter()
{
$calledAction = $this->router->fetch_method();
$this->testBeforeFilter($calledAction);
}
# . . .
}
<?php # File: application/hooks/controller.php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Hook to provide some functions to controllers.
*
* @author Nelson Martell <nelson6e65-dev@yahoo.es>
*/
class ControllerHook
{
private $ci;
public function __construct()
{
$this->ci =& get_instance();
// var_dump($this->ci->router);
$this->ci->load->library('session');
$this->ci->load->helper('url');
}
/**
* Methoth that will be called before controller actions calls.
*
* @return void
*/
public function beforeFilter()
{
// $called_function = $this->ci->router->fetch_method();
if (method_exists($this->ci, 'beforeFilter')) {
return $this->ci->beforeFilter();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment