Controllers

What Are They? Controllers take care of event handle, make queries to Models and finally pass data to Views.

Basic Usage Let's say you want to make a page about yourself. We are going to create a new controller just for that. Create a new PHP file at application/controllers/about.php. This file will be our new controller.

When the web browser requests the page /about (remember inside route array set an element 'about' ⇒ 'about.index'), Salem will load the about.php controller and run the index() function. If the controller or the function is missing then It will display a 404 error page (not found error).

Now in our new controller create the controller class and the index() function.

about.php

<?php
namespace Controller; //Never forget
use Salem\load, Salem\db, Salem\View, Salem\input, Salem\Validate, Salem\Url; //only if you will use some of this core Salem libraries
 
class About {
 
	public function index() {
		echo "This is a page about myself !";	
	}
}
?>

Now if you visit /about in your web browser you should see “This is a page about myself !”.

Arguments URLs can be infinitely long. What that means is that after the controller and function portions on the URL all other portions are just arguments for the controller function. Create a function youSaid() inside about class and remember inside route array set an element 'about/you/:words' ⇒ 'about.youSaid') so it looks like this:

about.php

<?php
namespace Controller; //Never forget
use Salem\load, Salem\db, Salem\View, Salem\input, Salem\Validate, Salem\Url; //only if you will use some of this core Salem libraries
 
class About {
 
	public function index() {
		echo "This is a page about myself !";	
	}
 
        public function youSaid($message)
        {
                echo "You said: ".$message;
        }
}
Now if you visit /about/you/cool it will display “You said: cool”.

Now there is one problem with this. If you where to visit /about/you then you would get a 404 error! This is because you can't just run youSaid(), it has a required argument! If you want people to still be able to visit the page, then you need to make your argument optional:

public function youSaid($message = 'nothing at all')
{
  echo "You said: ".$message;
}
Now visiting /about/you will produce “You said: nothing at all”, althoughthis if you visiting /about/you/cool will still display“You said: cool”.

At this point you should try experimenting around with adding additional controllers, functions, and arguments and see what happens.

Parent Controllers In Salem is possible to make controller classes extend from other controller classes. For example if you want to extend your about.php controller:

extabout.php

<?php
namespace Controller;
use Salem\load;//In this case I use the Load library
 
load::parentController('about');
 
class ExtAbout extends About{
  function index(){
    $this->youSaid("I'm cool!");
  }
}
?>


Go back to Documentation