The block controller class contains a couple of special functions that get automatically called at different points throughout the page load process. You can look into these callbacks to power different functionalities of your block type.
Getting ready
To get started, you will need a block type created and installed. See the previous recipe for a lesson on creating a custom block type. We will be adding some methods to controller.php.
How to do it...
The steps for using block controller callback functions are as follows:
Open your block's controller.php file.
Add a new function called on_start():
public function on_start() {
}
Write a die statement that will get fired when the controller is loaded.
die('hello world');
Refresh any page containing the block type. The page should stop rendering before it is complete with your debug message.
Be sure to remove the die statement, otherwise your block won't work anymore!
How it works...
concrete5 will call the various callback functions at different points during the page load process. The on_start() function is the first to get called. It is a good place to put things that you want to happen before the block is rendered.
The next function that gets called depends on how you are interacting with the block. If you are just viewing it on a page, the view() function gets called. If you are adding or editing the block, then the add() or edit() functions will get called as appropriate. These functions are a good place to send variables to the view, which we will show how to do in the next recipe. The save() and delete() functions also get called automatically at this point, if the block is performing either of those functions.
After that, concrete5 will call the on_before_render() function. This is a good time to add items to the page header and footer, since it is before concrete5 renders the HTML for the page. We will be doing this later on in the chapter.
Finally, the on_page_view() function is called. This is actually run once the page is being rendered, so it is the last place where you have the code executed in your block controller. This is helpful when adding HTML items to the page.
There's more...
The following functions can be added to your controller class and they will get called automatically at different points throughout the block's loading process.
on_start
on_before_render
view
add
edit
on_page_view
save
delete
For a complete list of the callback functions available, check out the source for the block controller library, located in /concrete/core/libraries/block_controller.php.
See also
The Sending variables from the controller to the view recipe
The Adding items to the page header and footer from the block controller recipe