Should I not be using Index as the name for a controller class in CodeIgniter? I have an Index controller, and I'm seeing its methods being called multiple times. More specifically, I always see its index method called first, whether or not I'm visiting a path that should be routed there.
In application/controllers/index.php
class Index extends CI_Controller
{
public function index()
{
echo "index";
}
public function blah()
{
echo "blah";
}
}
When I visit index/blah, I see indexblah printed. When I visit index/index, I see indexindex. If I rename the controller to something else (e.g. Foo), it doesn't have a problem. That's the obvious workaround, but can anyone tell me why this is happening? Should I report this as a bug to CodeIgniter?
(Notes: I have no routes set up in configs/routes.php; my index.php is outside the CodeIgniter tree)
To further clarify what the issue is, in PHP4 Constructors were a function that had the same name as the Class...
example
class MyClass
{
public function MyClass()
{
// as a constructor, this function is called every
// time a new "MyClass" object is created
}
}
Now for the PHP5 version (Which codeigniter now, as of 2.0.x, holds as a system requirement)
class MyClass
{
public function __construct()
{
// as a constructor, this function is called every
// time a new "MyClass" object is created
}
}
So To answer the question that addresses the problem...
Should I not be using Index as the name for a controller class in CodeIgniter?
I believe it would be best to not choose Index as a controller name as the index() function has a reserved use in codeigniter. This could cause issues depending on your PHP configuration.
can anyone tell me why this is happening?
When your controller get's instantiated, index as the constructor is getting called.
Compare Constructors and DestructorsDocs:
For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class . [highlighting by me]
In your case your Controller does not have any __construct() function but a function that has the same name as the class: index. It is getting called in the moment Codeigniter resolves and loads and then instantiates your Index Controller.
You can solve this by just adding the constructor to your Controller:
class Index extends CI_Controller
{
public function __construct() {}
public function index()
{
echo "index";
}
public function blah()
{
echo "blah";
}
}
After this change, it does not happen again.
Should I report this as a bug to CodeIgniter?
No, there is not really a need to report this as a bug, it's how the language work and as Codeigniter supports PHP 4 it must remain backwards compatible and needs to offer PHP 4 constructors. (Note: The Codeigniter project documents, they need server support for PHP version 5.1.6 or newer, but the actual code has PHP 4 compatiblity build in, I'm referring to the codebase here, not the documentation.)
Here is another solution using Codeigniter3
require_once 'Base.php';
class Index extends Base
{
public function __construct()
{
parent::index();
$classname=$this->router->fetch_class();
$actioname=$this->router->fetch_method();
if($actioname=='index' || $actioname == '')
{
$this->viewall();
}
}
}
And the viewall() had the following
$this->siteinfo['site_title'].=' | Welcome';
$this->load->view('templates/header', $this->siteinfo);
$this->load->view('templates/menu', $this->siteinfo);
$this->load->view('index/viewall', $data);
$this->load->view('templates/footer', $this->siteinfo);
The Base controller does all the library and helper loading for the entire application which is why it is being required in the default class
Basically from my short understanding of CodeIgniter, having a default action as index is a wrong. I found this out by using the printing the result of $this->router->fetch_method(); in the construct() of my index class. The default action by CodeIgniter is index, you may only set the default controller within application/config/routes.php and not the default action.
So my advice, never use index() as the default action especially if you are using index as the default controller
Related
I have a Controller class that extends from AppController in CakePHP.
And this Controller class has a public function .. lets say testFunc()
class xyzController extends AppController {
..
..
public function testFunc($params, $auth_username)
{
..
..
}
}
I have made this function public since I need to call it from another Controller that too extending from AppController.
class abcController extends AppController {
..
..
public function callingFunc()
{
...
$controller = new xyzController($this->request, $this->response);
$controller->testFunc($params, $username);
}
..
..
}
But since I made it public, I see that testFunc() is accessible using curl command for the below https path
https://[ip_address]/xyz/testFunc/arg=test/root
As you can see, the above path takes "root" as argument to testFunc() and gives full access to anyone using the above path in curl command.
My requirement is to remove this security issue.
I am totally new to PHP and CakePHP. Can someone please give any pointers to how I can proceed?
"I need to call it from another Controller". This is almost never actually true, it usually indicates a flawed design. If testFunc is not meant to be accessed through a browser, then move it to somewhere that both controllers can access it without it being a public member. For example, make it a protected (or even private) member of your AppController, or if it's doing model-specific stuff, maybe it can be moved to that model's table class.
The solution is pretty simple.
public function _testFunc($params, $auth_usernmae) will do the magic.
In Cakephp, if the function has an underscore as prefix, then it cannot be accessed using URI but can be accessed internally from other functions.
I am learning codeigniter 3
In my config.php:
$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/ci3x/admin/';
In my routes.php:
$route['customer'] = 'customer/index';
In controllers/customer.php:
class Customer extends MY_Controller{
function index(){
// some code here
}
}
When I type: http://localhost/ci3x/admin/customer on brower, it back error 404.
I have no clue to fix, please help me to solve it.
Many thanks
As you are extending a Class and that class does have a constructor, your class needs a constructor that also calls the constructor of the extended class.
Else things won't get up and running correctly.
class Customer extends MY_Controller{
public function __construct() {
parent::__construct(); // Call the MY_Controller constructor
}
function index(){
// some code here
}
}
The same goes for your MY_Controller constructor as it will need to call CI_Controller constructor... It ripples down and everything gets initialised correctly (in simplistic terms) .
Note:
Be careful with your controller and method files names. If you read the user guide it will say that the file names for controllers and methods should start with a capital letter.
So your controllers/customer.php should be controllers/Customer.php. If you are running on Windows it won't care. If you are running on Linux it will definitely matter.
I simply do not mean how to define a global variable/constant in CodeIgniter.
Let me explain:
I have made a theme engine which is select-able from the current logged in user's control panel. This engine is not very complicated, but a simple folder. anyway, what I do across the application, is that I write one line of code to get the current theme selected by the user. I use a one line of code to get the name, and then store it in a variable:
$theme_name = $this->theme->get_theme_with_slash(false);
And then, I user $theme_name like this to get the proper view:
$this->load->view($theme_name.'result', $data);
And in all of my controllers that loads view I should repeat this process. What I need, is to call the function which gets the theme_name and store in the variable and then use the variable/session/function across the application. My approach currently is the helper's function which is a little less convenient compared to session/variable.
I got this from the manual and this what I have at the top of my config/config.php file: (i have a custom config set to paypal testing)
// HOW TO USE - For example if there's $config['foo'] = 'bar';
// in the config
// using $this- >config->item('foo') will be 'bar'.
// example for my paypal testing:
$config['paypaltest']=0;
http://ellislab.com/codeigniter%20/user-guide/libraries/config.html
and how to access in a controller:
$paypaltest = $this->config->item('paypaltest');
Create A core controller, since your process requires logical operations then you need a method for that.
application/core/MY_Controller.php
class MY_Controller Extends CI_Controller
{
protected $default_theme = 'theme';
public function __construct()
{
parent::__construct();
}
public function get_theme()
{
//your code for selecting the current theme selected from
//the database
$theme_from_db = '';
return $theme_from_db == NULL ? $this->default_theme : $theme_from_db;
}
}
Your Controller must extend MY_Controller
application/controller/view.php
class view extends MY_Controller
{
public function index()
{
$this->load->view($this->get_theme().'result', $data);
}
}
in code igniter global constants can be defined in
config->constants.php
even you no need to load it,it automatically autoloaded by CI automatically.
In Codeigniter all constant is defined inside application/config/constant.php.
like: define("CONSTANTNAME","value");
Constant degined here is accessible throughout all pages, ie; controllers, models and views
I have been using CI for two years now. One thing that really annoys me is the use of &get_instance(). Although it is halpful while we are inside library , helper , presenters , model etc. But everytime loading it is cumborsome. If you forget loading it somewhere and simply use $this->blah->blah() instead of $CI->blah->blah() this makes too much trouble and if you are working online you face the client who is complaining that he sees the error. I have seen in the laravel that you does not need to load the instance anywhere throughout the application. This is because laravel is autoloading all the libraries and models and both are available anywhere in the application. But this seems to me disadvantage why loading classes that are not required in some particular places. This tells me Codeigniter is flexible but still i want an alternative where i dont want to use &get_instance(). Any idea or suggestion ? Please.
In your model or Core model or library
//class MY_Model extends CI_Model
//class SomeLibrary
class Some_model extends CI_Model {
private $_CI;
public function __construct() {
parent::__construct(); //for model or core model
$this->_CI =& get_instance();
}
//if you called attributs who does not exist in that class or parent class
public function __get($key)
{
return $this->_CI->$key;
}
//if you called methods who does not exist in that class or parent class
public function __call($method, $arguments)
{
call_user_func_array(array($this->_CI, $method), $arguments );
}
public function test() {
var_dump($this->some_controller_key);
var_dump($this->some_lib_loaded);
}
}
*NOT TESTED YET
Inspired by an piece of code from the awesome Flexi Auth
//from a Model to keep access of CI_Controller attributs
public function &__get($key)
{
$CI =& get_instance();
return $CI->$key;
}
I was shocked when I saw that ^^
To explain the &__get, i think when you will call this magic method a second time PHP will do not execute it again, but will take his result from the first call.
I have taken over a project written in CodeIgniter, which I have never used before. I have added a new file to views/pages called features.php, and have read on the internet that to make it accessible, I need to create a function in the controller file that will render the page.
I have tried the following:
public function features()
{
$this->render('template', 'pages/features');
}
However, when I try to open features.php, it gives me 404. How can I fix that?
Update 1 - Class
Here is the controller's class code:
class Pages extends MY_Controller {
function __construct()
{
parent::__construct();
$this->load->model('setting_model', 'setting');
$this->load->model('order_model', 'order');
$this->load->model('page_model', 'page');
$this->load->library('form_validation');
$this->load->helper(array('inflector', 'string'));
}
public function index()
{
$settings = $this->setting->get_settings();
$data['document_price'] = $settings->document_price;
$this->render('template', 'pages/index', $data);
}
//This works fine
public function about_us()
{
$this->render('template', 'pages/about_us');
}
//Here is the problem, although it follows the same pattern as about_us()
public function features()
{
$this->render('template', 'pages/features');
}
}
As you are using $this->render I guess you are using the template library. I think you should be using:
public function features()
{
$this->template->set_template('template');
$this->template->write_view('pages/features');
$this->template->render();
}
The php files contained in /views are not directly accessible by typing in some URL. CodeIgniter is an MVC framework. That means that your URLs are mapped to your controllers and the controllers call the views.
What is the name of the class that this function is encapsulated in? Please post the entire class and not just the features() function and we can help you out. If you're working locally, the default mapping to call controllers is: http://localhost/appname/controller/function/param1/param2/etc.
The $this->render() function is not vanilla CodeIgniter syntax, you either inherited a project that is using a templating library, or, there is a sibling render() function inside the controller class.
Check your config/routes.php file as well and consider posting it.
If you want to diagnose the issue, try pinpointing by removing the call to $this->render() and instead using CodeIgniter's native $this->load->view('pages/features') function. If this works, we can be sure it's the library or render() call.