All Codeigniter controllers seem to start with:
public function index()
{
// stuff
}
Is this a requirement or just good practice? I have an instance where an index may not be needed, for example I have a controller called "Auth" and in it there is a function to register and a function to login - you could argue that the login function is of higher priority but in the interest of naming convention I would rather name my functions. What is best practice here?
It's not a must method. It simply behaves like index.html on apache server.
When there is no html file specified, it automatically goes to index.html.
The same here, when there is no controller method specified index is default.
The index method is simply what's called when the second URL segment is missing. For example:
class Auth extends CI_Controller {
public function index () {
// domain.com/auth
// domain.com/auth/index
}
public function register () {
// domain.com/auth/register
}
}
If you don't need that route, you don't need an index method.
Related
I have a laravel resource controller as follow:
BlogController.php
class AdminBlogController extends BaseController {
public function index()
{
// some code
}
public function create()
{
// some code
}
// etc.....
in route.php I have this :
Route::resource('blog', 'AdminBlogController');
now I understand that when you go to URL /blog , it goes to index() and when you go to /blog/create goes to create() method.
My question is how do I handle missing method? for example when some types /blog/test , I get an error there , how can I redirect back missing methods to /blog?
Thanks
Taken from the Laravel Documentation:
If you are using resource controllers, you should define a __call
magic method on the controller to handle any missing methods.
In your AdminBlogController, add a __call magic method:
public function __call($method,$parameters = array())
{
if (!is_numeric($parameters[0])) {
return Redirect::to('blog');
}
else {
$this->myShow($parameters[0]);
}
}
...and, importantly, you need to rename your show method to something else (myShow in this example). Otherwise, /blog/test will route to show with the expectation that test is an id of a blog that you want to show. You also need to specify, in your __call method, which parameters after blog/ should be considered IDs, and which should be considered missing methods. In this example, I allow any numeric parameter to be treated as an ID, while non-numeric parameters will redirect to Index.
i have one default controller in codeigniter
class Welcome extends CI_Controller {
public function index()
{
$this->load->view('welcome_message');
}
as you know we can call this function
sitename/index.php
or
sitename/
as i have url rewrite in .htaccess
now i want to call same index function with parameter passing like
sitename/seo-services
where seo-services will be paramater passing to index function to load seo-services page.
as default syntax of codeigniter is
example.com/class/function/ID
i want in this formet
example.com/class/ID
where i want to skip the function for default (index) function of class
how can i do this?
Thanks
as you can see i am trying this for seo purpose.
Parameters appended to your url are automatically converted to arguments to your method.
For example if you have a method called index index in your welcome controller, then http://www.example.com/index.php/welcome/index/[parametervalue] will automatically pass [parametervalue] to your method, assuming that you define your function to receive the parameter
class Welcome extends CI_Controller {
public function index($parameterValue=null)
{
//do whatever you need here
//note the default value just in case it is null
}
}
If you want to make things shorter, you will have to define an alias in the config/routes.php file. Also, if you want to get rid of the index.php, you will have to configure your web server accordingly (either through .htaccess if using apache or web.config if using iis)
i have a class called comment and inside i have 3 functions called __construct, index and getComments
Class comment extends CI_Controller
{
public function __construct(){
parent::__construct();
}
public function index($comment_id){
echo $comment_id;
}
public function getComments(){
//do stuff to get comments and print them to screen
}
}
also in my routes folder i have added a new route
$route['comment/(:any)'] = "comment/index/$1";
so when i go to mysite.com/comment/123131313123
it echos the comment id but when i do an ajax call to the getComments() function in the same class it wont work and instead it will show me the word "getComments"
how can i make sure that when i go direct to the index function it will show me the parameter and also be able to do ajax calls without having any other problem with the other functions?
Thanks.
mysite.com/comment/getComments is getting matched to your route
You need to make another route before it which explicitly matches your ajax action
$route['comment/getComments'] = "comment/getComments";
$route['comment/(:any)'] = "comment/index/$1";
Routes are run in the order they are defined.
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
I want to write a new controller file, for example:
aaa.php
class aaa extends CI_Controller
{
public function bbb()
{
// Stuff
}
}
how can i enter aaa.php's bbb(),
The example files are begin with welcome.php's index() function.
how can I change that to begin with my new controller file?
If you provide nothing to the base URL, CI will always assume you want the index action. Like localhost/foo will call foo's index() action. With localhost/foo/bar, you will call foo's bar() action. If you want to call localhost and you want to access foo's index(), you need to check that $route['default_controller'] = 'foo'; is correctly setup in your config.php. (If that's not working, check the .htaccess and the index.php to add it manually)
You want to have a separate function run as the Controller's default function? Why not just call this separate function from index()? Beyond this, I'm not really sure what you're asking...the CodeIgniter user_guide is rather extensive if you haven't looked through it.
If you want to use the bbb function of the aaa controller, you just enter this in the url:
www.mysite.com/aaa/bbb/
As Gsto said, to call bbb function enter the url: mysite.com/aaa/bbb
If you want mysite.com/aaa to call bbb() instead of index() by default, your going to want to create the _remap() function in aaa.php controller to call bbb() instead.
See: CI Controllers - Functions Docs
The way to access your controller's methods in CodeIgniter is by uri. The default routing is:
example.com/controller/function/param1/
So to access aaa's bbb() method, you should access the following uri:
/aaa/bbb
If you want to set aaa's bbb() method as the default page of you application, there is two things to do.
You must first tell CodeIgniter to set aaa as your default controller
/* /application/config/routes.php */
$route['default_controller'] = "aaa";
After that, the aaa's index() method will be call by accessing your base site url. You can't tell CodeIgniter to change de default method index() to something else (without setting some routes), so the easiest way to call bbb() by default would be that:
/* /application/controllers/aaa.php */
class aaa extends CI_Controller
{
public function index()
{
$this->bbb();
}
public function bbb()
{
// Stuff
}
}