MicroFrameWork/kernel/CgView.php

79 lines
1.6 KiB
PHP
Raw Normal View History

2024-07-24 17:22:59 +03:00
<?php
namespace kernel;
2024-09-03 16:29:44 +03:00
use app\helpers\Debug;
2024-07-24 17:22:59 +03:00
class CgView
{
public string $viewPath = '';
2024-09-03 16:29:44 +03:00
public string $layoutPath = '';
public array $varToLayout = [];
2024-07-24 17:22:59 +03:00
public bool|string $layout = false;
public function __construct()
{
}
public function render(string $view, array $data = []): void
{
$content = $this->createContent($view, $data);
echo $content;
}
public function fetch(string $view, array $data = []): false|string
{
$content = $this->createContent($view, $data);
return $content;
}
2024-09-03 16:29:44 +03:00
public function addVarToLayout($key, $value): void
{
$this->varToLayout[$key] = $value;
}
2024-07-24 17:22:59 +03:00
private function createContent(string $view, array $data = []): false|string
{
ob_start();
2024-09-03 16:29:44 +03:00
foreach ($data as $key => $datum) {
2024-07-24 17:22:59 +03:00
${"$key"} = $datum;
}
2024-09-03 16:29:44 +03:00
include($this->viewPath . $view);
2024-07-24 17:22:59 +03:00
$content = ob_get_contents();
2024-09-03 16:29:44 +03:00
ob_end_clean();
2024-07-24 17:22:59 +03:00
ob_start();
2024-09-03 16:29:44 +03:00
2024-07-24 17:22:59 +03:00
$file_content = $content;
2024-09-03 16:29:44 +03:00
$layoutPath = $this->viewPath;
if ($this->layout) {
if ($this->layoutPath !== '') {
$layoutPath = $this->layoutPath;
}
if (file_exists($layoutPath . $this->layout)) {
if ($this->varToLayout){
foreach ($this->varToLayout as $key => $datum) {
${"$key"} = $datum;
}
}
include($layoutPath . $this->layout);
2024-07-24 17:22:59 +03:00
$file_content = ob_get_contents();
}
}
2024-09-03 16:29:44 +03:00
ob_end_clean();
2024-07-24 17:22:59 +03:00
return $file_content;
}
}