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

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. :)

Related

Cache files permissions fix for Kohana Twig module

How to configure Kohana + Twig module so the Twig will set "writable by all" permissions on all of it's cache directory and it's descendant files?
So, for example, when I run my application through the Apache module (mod_php) and cache file owner is apache (or httpd) user, I will be able to remove cache files (to clean the cache or completely remove whole application) using regular user and ssh access.
I'm able to do it with Kohana's cache, but Twig's cache is created somehow differently.
It's not very easy, but not too complicated either. I have achieved state presented below by trial-and-error method.
Create a class that inherits from Twig_Cache_Filesystem and will be used instead of it. Check this out:
<?php
namespace Application\Twig;
class Cache_Filesystem extends \Twig_Cache_Filesystem
{
public function write($key, $content)
{
$old = umask(0000);
parent::write($key, $content);
umask($old);
}
}
Note, that this class must have it's name unique, so it is a good idea to namespace it. Also, it must be accessible to other code, so consider using composer's autoloading feature.
This is the fix itself, rest of the guide is just the way of implementing it into Kohana+Twig ecosystem.
Copy Twig.php from modules/kohana-twig/classes/Twig.php into your application's directory, i.e. application/classes/Twig.php (thank you Kohana's Cascading Filesystem!)
Modify a bit newly copied file, to let Twig_CacheInterface instance be passed in the config file (application/config/twig.php) instead of just a simple string (specifying to the Twig's cache directory). Take a look of my example:
<?php defined('SYSPATH') or die('No direct script access.');
class Twig extends Kohana_Twig
{
/**
* Initialize the Twig module
*
* #throws Kohana_Exception
* #return bool
*/
public static function init()
{
$path = Kohana::$config->load('twig.environment.cache');
if (is_string($path)) {
return parent::init();
} else if ($path instanceof Twig_CacheInterface) {
return true;
}
throw new Kohana_Exception('Twig cache could not be initialized');
}
}
In configuration file for kohana-twig module, i.e. application/config/twig.php (if not yet copied from module to your application, do it now), define environment.cache key like this:
return array(
'loader' => array(
'extension' => 'twig',
'path' => 'views',
),
'environment' => array(
'auto_reload' => (Kohana::$environment >= Kohana::TESTING),
'autoescape' => true,
'base_template_class' => 'Twig_Template',
// Following line is related to this issue and fix:
'cache' => new \Application\Twig\Cache_Filesystem(APPPATH . 'cache/twig'),
'charset' => 'utf-8',
'optimizations' => - 1,
'strict_variables' => false,
),
'functions' => array(),
'filters' => array(),
'tests' => array(),
}
This works for me. Hopefully it will help someone struggling with similar problem.

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

Trouble using hook in 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
}
}

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