Skip to content

Modules

Jaime A. Rodriguez edited this page Sep 29, 2020 · 10 revisions

Understanding Modules

Table of Contents

Concepts - Actions and Filters

Modules are made up of methods that run at certain times during the program's execution. These "certain times" are called Hooks. There are two types of hooks: Actions and Filters.


Actions are defined points in the code that a module can use to hook in their method. A good example would be an Action called "sleepy_preprocess". This action runs very early in the program's lifecycle allowing you to run code before any templates have been rendered. It can be used to verify that a user has access to a page, or to start pulling content from a web service.

namespace Module\ExampleModule;                     # It's good practice to namespace your module

use \Sleepy\Core\Hook;                              # We need both of these classes 
use \Sleepy\Core\Module;                            # to create a module

class Example1 extends Module                       # All modules must extend the Module class
{
    public $hooks = [
        'sleepy_preprocess' => 'start'              # We are going to use this action -> this method
    ];

    public function start()
    {
        // Check if a user is logged in             # Run some code here... No need to return anything.
    }
}

Hook::register(new Example1());                     # We must register our Modules to the Hook System

Filters are similar to Actions, but they are used to modify data. An example of a filter could be "render_placeholder_title". This is the Filter for the placeholder "title". In this example, we might want to add the string " | Website Name" to the end of the titles for SEO purposes.

namespace Module\ExampleModule;                     # It's good practice to namespace your module

use \Sleepy\Core\Hook;                              # We need both of these classes 
use \Sleepy\Core\Module;                            # to create a module

class Example2 extends Module
{
    public $hooks = [
        'render_placeholder_title' => 'addSite'     # We are going to use this filter -> method
    ];

    public function addSite($str)                   # The filter will get the value of the title placeholder as $str
    {
        return $str + ' | Website Name';            # and we return the modified string to the template for use
    }
}

Hook::register(new Example2());                     # We must register our Modules to the Hook System

The Module Class

The Module class is located in the app/sleepy/core folder.

There are two configurable section in the Module class: hooks and environments

abstract class Module
{
    // A list of hooks and methods. e.g. 'sleepy_preprocess'  => 'startMethod',
    public $hooks = [];

    // The module will only execute on environments that are set to true
    public $environments = [
        'dev'   => true,
        'stage' => true,
        'live'  => true
    ];

    ...
}

The hooks section tells the system which methods should be run on which hook points.

The environments section tells the system if the module should be run in the dev/stage/live environments.

Examples

This example will calculate and display the time it took for the page to be processed and the amount of memory used. It will only run in the development environment:

<?php
/**
 * The Timer class used in the Performance Module to display the execution time and
 * memory usage
 *
 * PHP version 7.0.0
 *
 * @category Performance
 * @package  Module/Performance
 * @author   Jaime Rodriguez <hi.i.am.jaime@gmail.com>
 * @license  https://opensource.org/licenses/MIT MIT
 * @version  GIT: 1.0.0
 * @link     http://sleepymustache.com
 */

namespace Module\Performance;

use Sleepy\Core\Hook;
use Sleepy\Core\Module;

/**
 * Timer Module
 *
 * @category Performance
 * @package  Module/Performance
 * @author   Jaime Rodriguez <hi.i.am.jaime@gmail.com>
 * @license  https://opensource.org/licenses/MIT MIT
 * @link     http://sleepymustache.com
 */
class Timer extends Module
{
    /**
     * Define the hook points
     */
    public $hooks = [
        'sleepy_preprocess'  => 'startTimer',
        'sleepy_postprocess' => 'stopTimer'
    ];

    public function __construct() {
        $this->environments['dev']   = true;
        $this->environments['stage'] = false;
        $this->environments['live']  = false;

        // The parent contructor must be called
        parent::__construct();
    }

    /**
     * Starts the timer when the framework loads.
     *
     * @return void
     */
    public function startTimer()
    {
        $this->startTime =  microtime(true);
    }

    /**
     * When everything is done, append the time and memory usage to the file
     *
     * @return void
     */
    public function stopTimer()
    {
        $this->stopTimer = microtime(true) - $this->startTime;
        echo "\n<!-- Generated in $this->stopTimer seconds using " .
            (memory_get_peak_usage() / 1024) .
            " kb memory, by sleepyMUSTACHE -->";
    } 
}

Hook::register(new Timer());

Built-in Actions and Filters

This is not an exhaustive list of actions and filters. Modules and even you can define actions and filters using the Hook class.

  • [MODULENAME]_preprocess
  • bind_placeholder_[PLACEHOLDER NAME]
  • prerender_template
  • render_placeholder_[PLACEHOLDER NAME]
  • render_template
  • render_template_[TEMPLATE NAME]
  • sleepy_postprocess
  • sleepy_preprocess
  • sleepy_render
  • template_each
  • template_each_[NAME]
  • template_each_array
  • template_start
# Module to get all current placeholders
namespace Module\Debug;

use Sleepy\Core\Hook;
use Sleepy\Core\Module;
use Sleepy\Core\Debug;

class ActionFilters extends Module
{
    public $hooks = [
        'sleepy_postprocess' => 'show'
    ];

    public function show()
    {
        Debug::out(\Sleepy\Core\Hook::$hooks);
    }
}

Hook::register(new ActionFilters());
Clone this wiki locally