The MVC structure allows you to move your logic code away from the presentation code that produces your page. This helps clean up your template and focus purely on the layout. When you process data in the Controller, you will often want to pass the results through into the view so that it can be displayed on the page. To do this, follow the guide below.
Declaring a variable in the controller
To pass information through from the controller, the data must be in the global scope of the controller. To do this, declare a public variable before the __construct()
function. For example:
In this example, a variable called $my_variable
is available throughout the controller.
Putting data into the variable
Next, you will want to actually put some data into the variable. As it is globally available across the whole file, you can use $this->[variable_name]
to access the variable. As an example, let’s put some text into the string.
The variable now contains the string ‘Hello World!’
Accessing this variable in the frontend
The controller is globalised automatically, you can access it on the page as $ctrl
. To access your custom variable, use $ctrl->[variable_name]
. You can use this within the code or assign this to a variable for use later. For example:
This will produce a paragraph with the text ‘Hello World!’