12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- <?php
- declare(strict_types=1);
- namespace App\View\Engine;
- use Hyperf\View\Engine\EngineInterface;
- use Smarty;
- use RuntimeException;
- class SmartyEngine implements EngineInterface
- {
- protected Smarty $smarty;
- protected array $shared = [];
- public function __construct()
- {
- $this->smarty = new Smarty();
- // 基础配置
- $this->smarty->setLeftDelimiter('{{');
- $this->smarty->setRightDelimiter('}}');
- $this->smarty->setCompileDir(BASE_PATH . '/runtime/smarty/compile/');
- $this->smarty->setCacheDir(BASE_PATH . '/runtime/smarty/cache/');
- $this->smarty->setTemplateDir(BASE_PATH . '/storage/view/');
- $this->ensureDirectoryExists($this->smarty->getCompileDir());
- $this->ensureDirectoryExists($this->smarty->getCacheDir());
- }
- protected function ensureDirectoryExists(string $path): void
- {
- if (!is_dir($path)) {
- mkdir($path, 0755, true);
- }
- }
- public function share(string $key, $value): void
- {
- $this->shared[$key] = $value;
- }
- public function render(string $template, array $data, array $config): string
- {
- // 合并共享变量
- $data = array_merge($this->shared, $data);
- foreach ($data as $key => $value) {
- $this->smarty->assign($key, $value);
- }
- try {
- return $this->smarty->fetch($template);
- } catch (\SmartyException $e) {
- throw new RuntimeException("Smarty render failed: " . $e->getMessage());
- }
- }
- }
|