Trouble using hook in codeigniter - codeigniter

I want to use hook in codeigniter after perticular function of a controller. As per the documentation it will lead the hook to run after all controllers. But i want my hook to run after perticular function.
Please help with some example...
Thank You

If you want to set few function use hook you can add it to them straightly,
If most function use hook then set hook.And judge particular function in hook.
Here is my example:
config/config.php
$config['enable_hooks'] = TRUE;
config/hook.php
// I set the hook type to 'post_system', after rendering page hook execute.
$hook['post_system'] = array(
'class' => 'HookClass',
'function' => 'abc',
'filename' => 'hookClass.php',
'filepath' => 'hooks',
'params' => ''
);
hooks/hookClass.php
class HookClass{
private $particularFunction;
private $CI;
function __construct(){
$this->particularFunction=array('f1','f2');//set particular function name
$this->CI=& get_instance(); //important!get CI class
}
function abc(){
//if method not in particular function array,execute hook
if(!in_array($this->CI->router->method, $this->particularFunction))){
//$this->CI->router->method gets the executing method name
//execute hooks
}
}
}
example_controller.php
class Example_controller extends CI_controller{
function f1(){
//f1 function,and hooks will not execute.
}
function d1(){
//d1 function and hooks will execute
}
}

Related

Laravel FormRequest with variables

How do I put my validation logic within a FormRequest, knowing that my validation rules need variables set by the controller?
public function store()
{
$commentable = Comment::getCommentable(request('input1'), request('input1'));
// I need this $commentable above in my validator below!
$this->validate(request(),[
'commentable_type' => 'required|string|alpha', // Post
'commentable_id' => 'required|uuid|exists:' . plural_from_model($commentable) . ',' . $commentable->getKeyName(),
'body' => 'required|string|min:1',
]);
// ...
}
Here is my actual code: https://i.imgur.com/3bb8rgI.png
I want to tidy up my controller's store() method, moving the validate() in a FormRequest. However, as you can see, it needs the $commentable variable, which is retrieved by the controller.
I guess I could make it so that the FormRequest could retrieve that variable itself as well, but that would be an ugly duplicate (since it would also probe the database twice...). So that is not a good solution at all.
Any idea? Cheers.
Your FormRequest class can do pre-validation steps (including adding/modifying the input data, as shown below) via the prepareForValidation hook:
protected function prepareForValidation()
{
$this->commentable = Comment::getCommentable($this->input('input1'), $this->input('input1'));
$this->merge([
'commentable_id' => $this->commentable->id,
'commentable_type' => $this->commentable->type
]);
}
You'll be able to use $this->commentable in your rules() function, as well.

Adding a post_system hook from inside a controller method in CodeIgniter

I have some code i want to work after the request is sent to the client and closed so i want to add a post_system hook to the system from inside a controller, so the post_system hook runs only when specific method is invoked.
does CodeIgniter allow that in some workaround?
My version is 3.0rc3
It should be possible. One approach is to setup the post_system hook as described in the documentation - $config['enable_hooks'] = TRUE;, define the hook in application/config/hooks.php, and write the hook class.
In the controller that will use the post_system hook define a var that will be used to decide if the hook function should actually run. Set the default value to FALSE in the constructor and set it TRUE in specific method you have in mind.
Check the value of this var in your post_system_hook function. You may want to start by checking that the controller is the one that should be hooked. Let's assume that class is 'Welcome';
post_system_hook_function(){
//the type of $CI will be the name of the controller
if(get_class($CI) !== 'welcome') {
return false;
}
if(! $var_that_flags_do_the_task){
return false
}
//do post system code here
}
i understand that you want to check a controller like if it has permition to be in ther like logged.
you need to enable the hook in your application/config/config.php
$config['enable_hooks'] = TRUE;
Then you need to add this lines in your application/config/hooks.php with the code
$hook['pre_controller'] = array(
'class' => 'PreLogin',
'function' => 'auth',
'filename' => 'PreLogin.php',
'filepath' => 'hooks'
);
in your apllication/hooks/PreLogin.php
class PreLogin{
public function __construct(){
$CI =& get_instance();
$this->CI->load->library('session');
}
public function auth(){
if( ! isset($this->CI->session->userdata('id'))){
$this->CI->session->set_flashdata('error', 'You do not have permission to enter this url');
redirect(base_url(), 'refresh');
}
}
}

Codeigniter: Extend CI_Lang class when controller loaded to use &get_instance()

I want to extend my CI_Lang class to get language values from the database. So I created a copy of the CI_Lang file and rewrote the load and construct functions.
private $CI;
function __construct()
{
parent::__construct();
log_message('debug', "Language Class Initialized");
$this->CI = &get_instance();
}
I enabled hooks in the config file and created a new hook:
$hook['post_controller_constructor'] = array(
'class' => 'MY_Lang',
'function' => '__construct',
'filename' => 'MY_Lang.php',
'filepath' => 'hooks'
);
This is working correctly. However, when I try to load languages, it's still using the old functions from CI_Lang and not the extended one. Any ideas?
Ok I found the solution without using any hooks.
First: I had to place MY_Lang.php to 'core' folder.
Second: "$this->CI = &get_instance();" has to be placed in the "load" function and not in the construct.
Hope it helps, its working here. :)

cannot set user data in session codeigniter

please look at this.
The code below is from my model class (using datamapper orm)
function login()
{
$u = new User();
$u->where('username', $this->username)->get();
$this->salt = $u->salt;
$this->validate()->get();
if (empty($this->id))
{
// Login failed, so set a custom error message
$this->error_message('login', 'Username or password invalid');
return FALSE;
}
else
{
// Login succeeded
$data = array
(
'username' => $u->username,
'usergroup' => $u->usergroup->get(),
'is_logged_in' => true
);
$this->session->set_userdata($data);
return TRUE;
}
}
when i do this i get
**Fatal error: Call to a member function set_userdata() on a non-object**
but when i do this instead
$data = array
(
'username' => $u->username,
'usergroup' => $u->usergroup->get(),
'is_logged_in' => true
);
$obj=& get_instance();
$obj->session->set_userdata($data);
It works.
Please what is the right way to get this working ?
Thanks in advance.
your model did not extends CI_Model
after that you have to add constructor to your model
add this code to yours
function __construct()
{
parent::__construct();
$this->load->library('session');
}
Well, you didn't provide enough information.
The first code looks fine, provided that:
You actually load the session class before calling it (you also need to create an encryption key in your configs).
$this->load->library('session');
$this->session->set_userdata($data);
The above code, or your code, is inside a controller, a model or a view.
$this relates to the CI's superclass, in particular to an instance of the Session class, so if you're calling that inside a helper (collection of functions), or inside a library (where you need to create a CI instance first), it won't work.

Codeigniter MVC Sample Code

Hi
I am following the getting started guide for Codeigniterr given at http://www.ibm.com/developerworks/web/library/wa-codeigniter/
I have followed the instruction to create the front view and added controller to handle form submission. Ideally, when i submit the form, it should load the model class and execute the function to put details on the database, but instead it is just printing out the code of the model in the browser.
**Code of view (Welcome.php)**
----------------
<?php
class Welcome extends Controller {
function Welcome()
{
parent::Controller();
}
function index()
{
$this->load->helper('form');
$data['title'] = "Welcome to our Site";
$data['headline'] = "Welcome!";
$data['include'] = 'home';
$this->load->vars($data);
$this->load->view('template');
}
function contactus(){
$this->load->helper('url');
$this->load->model('mcontacts','',TRUE);
$this->mcontacts->addContact();
redirect('welcome/thankyou','refresh');
}
function thankyou(){
$data['title'] = "Thank You!";
$data['headline'] = "Thanks!";
$data['include'] = 'thanks';
$this->load->vars($data);
$this->load->view('template');
}
}
/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */
**Code of Model**
--------------
class mcontacts extends Model{
function mcontacts(){
parent::Model();
}
}
function addContact(){
$now = date("Y-m-d H:i:s");
$data = array(
'name' => $this->input->xss_clean($this->input->post('name')),
'email' => $this->input->xss_clean($this->input->post('email')),
'notes' => $this->input->xss_clean($this->input->post('notes')),
'ipaddress' => $this->input->ip_address(),
'stamp' => $now
);
$this->db->insert('contacts', $data);
}
**OUTPUT after clicking submit**
-----------------------------
class mcontacts extends Model{ function mcontacts(){ parent::Model(); } } function addContact(){ $now = date("Y-m-d H:i:s"); $data = array( 'name' => $this->input->xss_clean($this->input->post('name')), 'email' => $this->input->xss_clean($this->input->post('email')), 'notes' => $this->input->xss_clean($this->input->post('notes')), 'ipaddress' => $this->input->ip_address(), 'stamp' => $now ); $this->db->insert('contacts', $data); }
I have tried doing these things
1. Making all PHP codes executable
2. Change ownership of files to www-data
3. make permission 777 for whole of www
But, the code of model seems to be just printed ... PLEASE HELP
Just a few minor points that might help you:
In your controller, point the index method at the method you would like to call on that page. For example:
function index()
{
$this->welcome();
}
That will help keep things clean and clear, especially if anyone else comes in to work on the code with you later. I chose welcome because that's the name of your controller class and that will keep things simple.
In your model, this:
class mcontacts extends Model{
Should be:
class Mcontacts extends Model{
Capitalize those class names! That could be giving you the trouble you describe.
See here for more info on this: http://codeigniter.com/user_guide/general/models.html
Don't use camel case in your class or method names. This isn't something that will cause your code to fail, but it's generally accepted practice. See Codeigniter's PHP Style guide for more information on this: http://codeigniter.com/user_guide/general/styleguide.html
It's difficult to see with the formatting as it is, but do have an extra curly brace after the constructor method (mcontacts()) in the model? This would cause problems! Also although the code looks generally ok, there are probably better ways to use the framework especially if you do anything more complicated than what you've shown. For example, autoloading, form validation etc. Can I suggest you have a read of the userguide? It's very thorough and clear and should help you alot. http://codeigniter.com/user_guide/index.html

Resources