Sunday, May 10, 2009

Creating CodeIgniter Controller [ Step 3]

Any application you develop with CodeIgniter is going to minimally contain controllers and views. So lets build a controller. When you name your file It's must be the same name as the class of the controller with a php extension. I call this one blog so I can use this in next tutorial.
Create file blog.php in Controller folder with such code inside
class Blog extends Controller
{
Function Index()
{
echo 'Hello World ';
}
}

Who is mister "controller"?

A controller simply a php class, one thing you need to remember, when you name your controller it's need to be capitalize. Remember that a class and file name must match, but the class name must be capitalize and file name will not. The second thing is that must extend the parent controller class, the system controller by extending the main controller class you allow your local class to inherent all property, methods and resources the CodeIgniter makes available to your.
We got a simple function that I call Index, index always will be a default function within your class and I show your how that work in a moment.

Understanding CodeIgniter URL's.

In a model-view-controller approach the first segment correlates to a class name you wish to invoke and the second segment correlates to a function name within the class , I can accomplish the same thing on web page by typing index www.YouHostName.com/CodeIgniter/index.php/blog/index.php as the second segment and explicitly call that function , but the index function is always call by default. Now you going to a browser and type a file name in to a first segment of the URI www.DomainOnWhichYouInstallCodeIgniter.com/CodeIgniter/index.php/blog , your can see that we know getting a "Hello world " statement.
I should also mention that index.php file in our URL can easily be removed with .htaccess file, so if you like clean URL's you can easily accomplish this.

Set up default controller.

If I want reload page using only the front controller again you see I still get a 404 page because by even with a made of controller we hadn't told CodeIgniter to show anything by default.
There is no assumption made by CodeIgniter that a particular controller is what your want show by default we can do that by going into a config folder and opening the routes.php file
$route['default_controller'] = "welcome";
$route['scaffolding_trigger'] = "";
This file help us creates mapping instructor's for a URL and amount of other things allow us to specify a default controller, if I change this
$route['default_controller'] = "welcome";
to
$route['default_controller'] = "blog";
a controller that I just create and than reload a page , it's know serving our controller Blog up as a default.

No comments:

Post a Comment