NanoMVC

Plugins

What is a plugin?

Plugins are used to extend the functionality of NanoMVC. There are two main types of plugins:

Both types of plugins are placed in the /myapp/plugins/ directory.

Loading a Library

Let’s create a sample library plugin named demo:

/myapp/
  /plugins/
    nanomvc_library_demo.php

The filename must be lowercase and follow the pattern nanomvc_library_*.php. The class name must match the filename suffix and start with NanoMVC_Library_:

class NanoMVC_Library_Demo {
  public function test() {
    return "This is a test.";
  }
}

To use this plugin in a controller:

class Hello_Controller extends NanoMVC_Controller {
  public NanoMVC_Library_Demo $mydemo;

  function index() {
    $this->load->library('demo', 'mydemo');
    $this->view->assign('output', $this->mydemo->test());
    $this->view->display(​'hello_view');
  }
}

The second argument to load->library() is an alias for the class instance. If not provided, the original name is used.

You now have a variable $output in your view with the result of the test() method.

Loading a Script

Let’s create a script plugin called myhelpers:

/myapp/
  /plugins/
    nanomvc_script_myhelpers.php

The script file must be lowercase and start with nanomvc_script_.

function esc($string) {
  return htmlentities($string);
}

function anchor($url, $text) {
  return "<a href=\"$url\">$text</a>";
}

To load the script in a controller:

class Hello_Controller extends NanoMVC_Controller {
  function index() {
    $this->load->script('myhelpers');
    $this->view->display(​'hello_view');
  }
}

All functions defined in the script become globally available to views and controllers after loading.

Optionally, you may use static classes instead of global functions. For example:

class NanoMVC_Script_MyHelper {
  public static function esc($str) {
    return htmlentities($str);
  }
}

Then use it as follows after loading the script:

// Call statically
echo NanoMVC_Script_MyHelper::esc(​'<div>test</div>');

// Or as an instance (for brevity)
$dh = new NanoMVC_Script_MyHelper();
echo $dh::esc('<div>test</div>');

Libraries and scripts can optionally be autoloaded. See the Autoloading plugins for more details.

← to Models to Custom Database Plugin →

← Back to Documentation