Documentation:Controllers

From TinyMVC

Jump to: navigation, search

What is a controller?

Controller files are what glue the application together. They load models, display views, and tie in the plugins and application library code. They are the content traffic cops, so to speak.

A typical URL to a TinyURL page looks like this:

http://[host]/index.php/[controller]/[action]/[param1]/[param2]/[param3...]

Where controller is the name of the controller file/class, and action is the method name of the controller class you want to access. Values beyond that are used as parameters for your application. So, a real URL might look something like:

http://localhost/index.php/hello/intro/name/joe

Learning by example

Controller files live in the controllers directory. Lets create a controller:

/myapp/
  /controllers/
    hello.php

hello.php:

class Hello_Controller extends TinyMVC_Controller
{
  function index()
  {
    echo "Hello World.";
  }
}

The controller name in the URL is case sensitive, and without the .php extension.
The class name prefix (prefix_Controller) must match the controller file name,
although it can be any case.

Now lets take a look at this. Direct your browser to:

http://localhost/index.php/hello

Be sure to use your installation path to index.php

You should see the text "Hello World." in your browser.

If you do not supply a controller name in the URL, default is assumed.
You can change which controller is default in the /myapp/configs/application.php file.

For brevity, we have echoed output right from the controller. Normally this output would come from a view, which we will cover in the next chapter.

Now, lets, create a new method in the controller class:

hello.php:

class Hello_Controller extends TinyMVC_Controller
{
  function index()
  {
    echo "Hello World.";
  }
  function time()
  {
    echo "The time is now.";
  }
}

Now lets see it in the browser:

http://localhost/index.php/hello/time

As you can see, appending the method name to the URL brings up the corresponding method output from the controller.

If no method name is in the URL, the method index is assumed.

You can get rid of index.php in the URL with the following Apache rewrite rule:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

This goes in an .htaccess file in your document directory, or in your apache config.

Now you can access the hello controller with just http://localhost/hello in the URL.

That will rewrite everything that is not a real file or directory on the server to your index.php. Be sure you create a robots.txt file so that does not get redirected when webcrawlers visit. Also create a favicon.ico file so browsers don't get a redirect when trying to load a favicon.

Personal tools