-
Notifications
You must be signed in to change notification settings - Fork 1
Controllers, Actions and Views
The URL pattern in NanoPHP is controller
/action
/param1
/param2
/...
.
For example, if the URL is http://localhost/NanoPHP_Example/home/sampleAction/value1/value2
, then
- Controller name is
home
- Action name is
sampleAction
- The first parameter for
sampleAction
isvalue1
- The second parameter for
sampleAction
isvalue2
Note that /NanoPHP_Example
in the URL is part of the base URL. The base URL needs to be configured in config.php
inside the root directory. See the config.php
of the example application.
Defining a Controller is simple. If you want to create a controller named HelloWorld
, simply create a class named HelloWorld
in a file named helloworld.php
inside the application/controller
directory.
The default controller executed when the root URL is hit must be configured in config.php
.
The public methods in the controller class are its actions. Consider the following code snippet:
class HelloWord {
public function sayHello($firstName, $lastName) {
echo "Hello $firstName $lastName!";
}
}
For the above code, hitting the URL http://localhost/NanoPHP_Example/helloworld/sayHello/Sharafat/Mosharraf
will display the text Hello Sharafat Mosharraf!
.
The default action for a controller when no action name is present in the URL is index
.
Simply put the view file inside the application/view
directory. It's recommended that you define all the view logic and variables at the very top portion of your view file inside the <?php
and ?>
tags. This will make the view HTML look cleaner. See a sample view file.
- If you don't want to return any view from a controller action (e.g., you are sending an attachment to the browser), then simply don't return anything.
- If you want to render a view file, then return the view file name. NanoPHP will automatically prepend the
application/view
path to the view file name returned. - If you want to use model data (i.e., variables) in view file, you need to return the model along with the view file name. So, return an array containing the view file name as the first element and another array as the second element. The latter array will be an associative array containing the mapping of variable names defined in the view and their corresponding value.
- If you want to redirect to another URL, return the url with the 'redirect:' prefix.
See all these view returning logic in the example controller.