SmartyEngine.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\View\Engine;
  4. use Hyperf\View\Engine\EngineInterface;
  5. use Smarty;
  6. use RuntimeException;
  7. class SmartyEngine implements EngineInterface
  8. {
  9. protected Smarty $smarty;
  10. protected array $shared = [];
  11. public function __construct()
  12. {
  13. $this->smarty = new Smarty();
  14. // 基础配置
  15. $this->smarty->setLeftDelimiter('{{');
  16. $this->smarty->setRightDelimiter('}}');
  17. $this->smarty->setCompileDir(BASE_PATH . '/runtime/smarty/compile/');
  18. $this->smarty->setCacheDir(BASE_PATH . '/runtime/smarty/cache/');
  19. $this->smarty->setTemplateDir(BASE_PATH . '/storage/view/');
  20. $this->ensureDirectoryExists($this->smarty->getCompileDir());
  21. $this->ensureDirectoryExists($this->smarty->getCacheDir());
  22. }
  23. protected function ensureDirectoryExists(string $path): void
  24. {
  25. if (!is_dir($path)) {
  26. mkdir($path, 0755, true);
  27. }
  28. }
  29. public function share(string $key, $value): void
  30. {
  31. $this->shared[$key] = $value;
  32. }
  33. public function render(string $template, array $data, array $config): string
  34. {
  35. // 合并共享变量
  36. $data = array_merge($this->shared, $data);
  37. foreach ($data as $key => $value) {
  38. $this->smarty->assign($key, $value);
  39. }
  40. try {
  41. return $this->smarty->fetch($template);
  42. } catch (\SmartyException $e) {
  43. throw new RuntimeException("Smarty render failed: " . $e->getMessage());
  44. }
  45. }
  46. }