Готовый компонент
Добрый день!
Подскажите, где можно взять готовый компонент "Каталог продукции/товаров", под этот фреймворк.
Или может кто поделится готовым решением.
Спасибо.
Сергей, добрый день, каталог товаров строится на основании связанного дерева, подробнее про деревья можно прочитать тут http://mv-framework.ru/dereviya/
Используются 2 модели: разделы и товары каталога. Ниже представлены базовые примеры, которые можно развить под свои задачи.
Модель категорий
class Catalogs extends Model
{
protected $name = "Разделы каталога";
protected $model_elements = array(
array("Активировать", "bool", "active", array("on_create" => true)),
array("Название", "char", "name", array("required" => true)),
array("Ссылка", "url", "url", array("unique" => true)),
array("Родительский раздел", "parent", "parent", array("parent_for" => "Products", "max_depth" => 3)),
array("Изображение", "image", "image"),
array("Описание", "text", "description", array("rich_text" => true)),
array("Позиция", "order", "order")
);
}
CREATE TABLE IF NOT EXISTS `catalogs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`active` tinyint(1) NOT NULL,
`name` varchar(200) NOT NULL,
`url` varchar(200) NOT NULL,
`order` int(11) NOT NULL,
`parent` int(11) NOT NULL,
`description` text NOT NULL,
`image` varchar(150) NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8;Модель товаров
class Products extends Model
{
protected $name = "Товары каталога";
protected $model_elements = array(
array("Активировать", "bool", "active", array("on_create" => true)),
array("Название", "char", "name", array("required" => true)),
array("Позиция", "order", "order"),
array("Новинка", "bool", "flag_new"),
array("Отображать на главной", "bool", "flag_index"),
array("Артикул", "char", "articul"),
array("Раздел каталога", "enum", "parent", array("foreign_key" => "Catalogs",
"required" => true,
"is_parent" => true,
"show_parent" => true)),
array("Ссылка", "url", "url", array("unique" => true)),
array("Цена", "int", "price", array("required" => true)),
array("Старая цена", "int", "old_price"),
array("Изображения", "multi_images", "images"),
array("Описание", "text", "description", array("rich_text" => true))
);
protected $model_display_params = array(
"fields_groups" => array("Основные параметры" => array("active", "name", "articul", "parent",
"price", "old_price", "quantity", "images"),
"Дополнительные признаки" => array("flag_new", "flag_index", "order", "description"))
);
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
`active` tinyint(1) NOT NULL,
`order` int(11) NOT NULL,
`articul` varchar(100) NOT NULL,
`parent` int(11) NOT NULL,
`url` varchar(200) NOT NULL,
`price` int(11) NOT NULL,
`old_price` int(11) NOT NULL,
`quantity` int(11) NOT NULL,
`flag_new` tinyint(1) NOT NULL,
`flag_index` tinyint(1) NOT NULL,
`description` text NOT NULL,
`images` text NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8;После создания классов моделей, таблиц, и прописывания моделей в config/models.php в админке все должно работать.
Далее для сайта нужно добавить маршруты в config/routes.php и создать вьюхи в папке views.
"catalog/" => "catalog/view-catalog-root.php", "catalog/*/" => "catalog/view-catalog.php", "product/*/" => "catalog/view-product.php",
Чтобы на вьюхах определить раздел каталога и конкретный товар, добавляем в модели следующие методы
//Для модели разделов
public function defineCatalogPage(Router $router)
{
$url_parts = $router -> getUrlParts();
$record = false;
if(count($url_parts) == 2 && $url_parts[0] == "catalog")
if(is_numeric($url_parts[1]))
$record = $this -> findRecord(array("id" => $url_parts[1], "active" => 1));
else
$record = $this -> findRecord(array("url" => $url_parts[1], "active" => 1));
if($record)
$this -> id = $record -> id;
return $record;
}
//Для модели товаров
public function defineProductPage(Router $router)
{
$url_parts = $router -> getUrlParts();
$record = false;
if(count($url_parts) == 2 && $url_parts[0] == "product")
if(is_numeric($url_parts[1]))
$record = $this -> findRecord(array("id" => $url_parts[1], "active" => 1));
else
$record = $this -> findRecord(array("url" => $url_parts[1], "active" => 1));
if($record)
$this -> id = $record -> id;
return $record;
}Также нужны методы для вывода списка разделов и товаров.
Рекурсивный метод ля каталога есть тут http://mv-framework.ru/dereviya/
//Для разделов
public function displayCatalogMenu($parent)
{
$rows = $this -> select(array("parent" => $parent, "active" => 1, "order->asc" => "order"));
$html = "";
$root_path = $this -> root_path."catalog/";
foreach($rows as $row)
{
$url = $root_path.($row['url'] ? $row['url']."/" : $row['id']."/");
$html .= "<li><a href="".$url."">".$row['name']."</a>";
}
return $html;
}
public function display($parent)
{
$rows = $this -> select(array("parent" => $parent, "active" => 1));
foreach($rows as $row)
{
$url = $row['url'] ? $row['url'] : $row['id'];
$html .= "<a class="catalog-image" href="".$this -> root_path."catalog/".$url."/">";
$html .= $this -> resizeImage($this -> getFirstImage($row['image']), 236, 231)."</a>";
...
}
return $html;
}
//Для товаров
public function display($parent)
{
$html = "";
$params = array("active" => 1, "parent" => $parent);
if(isset($this -> pager))
$params["limit->"] = $this -> pager -> getParamsForSelect();
$rows = $this -> select($params);
foreach($rows as $row)
{
...
$url = $this -> root_path."product/".($row['url'] ? $row['url'] : $row['id'])."/";
$image = $this -> cropImage($this -> getFirstImage($row['images']), 250, 250);
$html .= "<a class="product-image" href="".$url."">".$image."</a>";
...
}
return $html;
}В завершении все ранее описанное используется в шаблонах для отображения товаров и разделов
//view-catalog.php
<?
$catalog = $mv -> catalogs -> defineCatalogPage($mv -> router);
$mv -> display404($catalog);
$mv -> seo -> mergeParams($catalog, "name");
$products = $mv -> products -> countRecords(array("active" => 1, "parent" => $catalog -> id));
include $mv -> views_path."main-header.php";
?>
<h1><? echo $catalog -> name; ?></h1>
<?
if(!$products)
echo $mv -> catalogs -> display($catalog -> id);
else if($products)
echo $mv -> products -> display(array("parent" => $catalog -> id));
include $mv -> views_path."main-footer.php";
?>
//view-product.php
<?
$product = $mv -> products -> defineProductPage($mv -> router);
$mv -> display404($product);
$mv -> seo -> mergeParams($product, "name");
include $mv -> views_path."main-header.php";
?>
<h1><? echo $product -> name; ?></h1>
<div class="price"><? echo $product -> price; ?></div>
<? echo $product -> description; ?>
<?
include $mv -> views_path."main-footer.php";
?>