What are the best practices for including external libraries like Smarty in PHP classes?
When including external libraries like Smarty in PHP classes, it is best practice to use namespaces to avoid naming conflicts with other classes. This helps to organize your code and make it easier to maintain. Additionally, it is important to properly autoload the external library using a PSR-4 autoloader to ensure that the classes are loaded only when needed.
<?php
// Autoload the Smarty library using a PSR-4 autoloader
require_once 'vendor/autoload.php';
use Smarty\Smarty;
class MySmartyClass
{
private $smarty;
public function __construct()
{
$this->smarty = new Smarty();
}
public function assign($name, $value)
{
$this->smarty->assign($name, $value);
}
public function display($template)
{
$this->smarty->display($template);
}
}
// Example usage
$smartyClass = new MySmartyClass();
$smartyClass->assign('name', 'John Doe');
$smartyClass->display('template.tpl');