Web Gear is a free, lightweight open source web development platform written in PHP, aimed at developing fast web applications, based on a well defined MVC structure.

Controllers

Examples

The following example will show you how to write your own controllers. But first of all, a couple of notes are required.

  • The controller source file and the controller class name MUST be identical.
  • The controller class name MUST be suffixed with _Controller (or in case of admin controllers, _Admin_Controller is the required suffix).
  • Controller actions MUST be suffixed with Action.
  • Controller actions MUST be declared as public.

Let's start with the beginning. As said before, all controllers reside into the includes/controllers/ directory. So, let's go into that directory and create a new php file called MyController.php. Now, open the file to declare our controller:

<?php

class MyController_Controller extends Controller
{

}

That's it! You have created your first controller. But it's not really complete yet, since no templates are defined for it. You can try to access http://yoursite.com/index.php/MyController/, but you will get an error saying that the template file for the Index action of the controller was not found. The Index action is inherited from the base controller class, therefore it is automatically executed if you don't specify any action.

Let's create a template for the index action, by going into the templates/ directory and creating a directory named exactly as the controller. Inside it, create a HTML file named exactly as the controller action you want to execute (Index in our case). By now you should have the following structure into your templates/ directory:

templates/
    MyController/
        Index.html

There might be some other files and directories, but we excluded them, so it doesn't get confusing. If you refresh the page you accessed earlier, you should now see the HTML content you wrote into the newly created file.

A global variable called $controller is made available into the templates. This is not a global PHP variable, but a variable accessible from every template file you write. Every public method defined into the controllers base class(includes/controllers/Controller.php) is available from within any template file (check the Overview page).

Also, in controller specific templates (like the Index.html file created earlier), you also have access to the current controller's public methods. So, if you defined a method called myMethod into the controller created earlier (MyController), which had the following definition:

public function myMethod()
{
    return 'my method output';
}

then you could call that method into your Index.html file created earlier, and it would output "my method output":

<p>My method says: <php echo $controller->myMethod(); ?><p>