Welcome to TinyMVC, the tiny PHP Framework.

Integrating a Template Engine

Although a template engine is not necessary, you may wish to integrate a template engine you like to use. In the following example, we'll demonstrate how to integrate Smarty as the view layer. We do this by loading the Smarty class as a library.

Learning by example

First, we'll show the quick and dirty method, with everything in the controller.

Install Smarty with Composer (composer require smarty/smarty) and create its working directories. Smarty 5 requires PHP 7.2 or later. For our example, we put it here:

/var/smarty/
  /vendor/
    autoload.php
    ...
  /templates/
  /templates_c/
  /configs/
  /cache/

myapp/controllers/hello.php

class Hello_Controller extends TinyMVC_Controller
{
  function index()
  {
    // load the Composer autoloader for Smarty
    require_once('/var/smarty/vendor/autoload.php');
    // instantiate Smarty
    $this->smarty = new \Smarty\Smarty();
    // configure Smarty
    $this->smarty->setTemplateDir('/var/smarty/templates/');
    $this->smarty->setCompileDir('/var/smarty/templates_c/');
    $this->smarty->setConfigDir('/var/smarty/configs/');
    $this->smarty->setCacheDir('/var/smarty/cache/');
 
    // now just use smarty for the view layer
    $this->smarty->assign('foo','bar');
    $this->smarty->display('hello_view.tpl');
  }
}


The Composer autoloader and the TinyMVC autoloader work side by side, so no extra setup is needed.

Now this is a lot of code in the controller, and you will probably want to use Smarty elsewhere. So the more flexible solution is to create a library wrapper:

myapp/plugins/tinymvc_library_smarty_wrapper.php

// load the Composer autoloader for Smarty
require_once('/var/smarty/vendor/autoload.php');
 
class TinyMVC_Library_Smarty_Wrapper extends \Smarty\Smarty
{
  function __construct()
  {
    parent::__construct();
    $this->setTemplateDir('/var/smarty/templates/');
    $this->setCompileDir('/var/smarty/templates_c/');
    $this->setConfigDir('/var/smarty/configs/');
    $this->setCacheDir('/var/smarty/cache/');
  }
}

myapp/controllers/hello.php

class Hello_Controller extends TinyMVC_Controller
{
  function index()
  {
    $this->load->library('Smarty_Wrapper','smarty');
    // now just use smarty for the view layer
    $this->smarty->assign('foo','bar');
    $this->smarty->display('hello_view.tpl');
  }
}

Now you can load and use Smarty with one line of code in your controller. Optionally, you can autoload the Smarty_Wrapper library in the /myapp/configs/config_autoload.php file.

TinyMVC is licensed under the GNU LGPL license.
This page was rendered in 0.00030 seconds.