setMeta не прописывает часть тегов title и description в шаблон
начал изучать php и столкнулся с проблемой, при прописании функций setMeta и getMeta на странице в шаблоне не отображается часть тегов, а точнее title и description , хотя keywords срабатывает отлично. Помогите разобраться!?
<?php
namespace ishop\base;
abstract class Controller{//прописываем базу контроллеров
//Свойства контроллеров
public $route;
public $controller;
public $model;
public $view;
public $prefix;
public $layout;
public $data =[];
public $meta = ['title' => '', 'description' => '', 'keywords' => ''];
//конструктор где заполненяем данные
public function __construct($route){
$this->route = $route;
$this->controller = $route['controller'];
$this->model = $route['controller'];
$this->view = $route['action'];
$this->prefix = $route['prefix'];
}
public function getView(){//получает объект вида и вызывает render
$viewObject = new View($this->route, $this->layout, $this->view, $this->meta);//создаем объекты вида
$viewObject->render($this->data);//создаем объект рендер с помощью data
}
//функция для передачи данных в $data
public function set($data){
$this->data = $data;
}
//функция для мета данных
public function setMeta($title = '', $description = '', $keywords = ''){
$this->meta['title'] = $title;
$this->meta['description'] = $description;
$this->meta['keywords'] = $keywords;
}
}
<?php
namespace ishop\base;
class View{
//Создаем базовый материал для вывода контроллеров при отладки
public $route;
public $controller;
public $model;
public $view;
public $prefix;
public $layout;
public $data =[];
public $meta = [];
public function __construct($route, $layout = '', $view = '', $meta){
$this->route = $route;
$this->controller = $route['controller'];
$this->view = $view;
$this->model = $route['controller'];
$this->prefix = $route['prefix'];
$this->meta = $meta;
if($layout === false){//Проверяем отключен ли Лайаут
$this->layout = false;
}else{
$this->layout = $layout ?: LAYOUT;//если нет то подключаем массив шаблона или шаблон по умолч
}
}
public function render($data){//формиркет страницу для пользователя
$viewFile = APP . "/views/{$this->prefix}{$this->controller}/{$this->view}.php";//из
//формируем путь к Layout
ob_start();//помещаем в буфер
if(is_file($viewFile)){//если существует такой файл
require_once $viewFile;//подключаем его
$content = ob_get_clean();//из буфера в $content и чистим буфер
}else{
throw new \Exception("Не найден вид {$viewFile}", 500);//если нет ошибка 500
}
if(false !== $this->layout){//проверяем не отключен ли шаблон
$layoutFile = APP . "/views/layouts/{$this->layout}.php";//если ок,формируем путь к шаблону
if(is_file($layoutFile)){//выводим шаблон на экран
require_once $layoutFile;
}else{
throw new \Exception("Не найден шаблон {$this->layout}", 500);
}
}
}
public function getMeta(){//метод пердачи инфы из метатэгов
$output = '<title>' . $this->meta['title'] . '</title>' . PHP_EOL;
$output = '<meta name="description" content="' . $this->meta['description'] . '">' . PHP_EOL;
$output = '<meta name="keywords" content="' . $this->meta['keywords'] . '">' . PHP_EOL;
return $output;
}
}
<?php
namespace app\controllers;
class MainController extends AppController{
public function indexAction(){
/* echo __METHOD__ ;*/
$this->setMeta('Главная', 'Описание', 'Клю');
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<?=$this->getMeta();?>
</head>
<body>
<h1>Шаблон DEFAULT</h1>
<?=$content;?>
</body>
</html>
И на деле выходит так
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="keywords" content="Клю">
</head>
<body>
<h1>Шаблон DEFAULT</h1>
<h1> Hello, Urod </h1>
</body>
</html>
Ответы (1 шт):
Автор решения: mepihindeveloper
→ Ссылка
$output = '<title>' . $this->meta['title'] . '</title>' . PHP_EOL;
$output = '<meta name="description" content="' . $this->meta['description'] . '">' . PHP_EOL;
$output = '<meta name="keywords" content="' . $this->meta['keywords'] . '">' . PHP_EOL;
Вы перезаписываете значение $output каждый раз. Следовательно в переменной $output будет только последнее присвоение. Используйте оператор .= для добавления:
$output = '<title>' . $this->meta['title'] . '</title>' . PHP_EOL;
$output .= '<meta name="description" content="' . $this->meta['description'] . '">' . PHP_EOL;
$output .= '<meta name="keywords" content="' . $this->meta['keywords'] . '">' . PHP_EOL;
Для работы с Meta я написал свой класс, можете посмотреть и воспользоваться, если будет актуально: https://github.com/mepihindeveloper/phpframework/blob/develop/kernel/helpers/MetaTag.php