Jump to content

Cache no working when add or remove products


okz

Recommended Posts

Hello,

 

I have a problem on my website : www.shin-sekai.fr

I have a custom module who displays specified products of category on home page.

When I add or remove a product, the home page take something like 8, 9 seconds to load !!! But When I check on a catagory page, it's better.

I try a module for cache but the problem is ONLY this module won't update when I add or remove a product on the home page. I have to force in Prestashop clearing the cache...

I think there is something to do to reduce code or else ?

Many thanks. It's a very important problem for me. I can pay if it's a big work.

 

<?php
if (!defined('_PS_VERSION_'))
{
    exit;
}
use PrestaShop\PrestaShop\Adapter\Image\ImageRetriever;
use PrestaShop\PrestaShop\Adapter\Product\PriceFormatter;
use PrestaShop\PrestaShop\Core\Product\ProductListingPresenter;
use PrestaShop\PrestaShop\Adapter\Product\ProductColorsRetriever;
class Featuredcategorywoslider extends Module
{
    protected static $cache_products;
    private $templateFile;
    public function __construct()
    {
        $this->name = 'featuredcategorywoslider';
        $this->tab = 'front_office_features';
        $this->version = '1.0.0';
        $this->author = 'Ishi Technolabs';
        $this->need_instance = 0;
        $this->bootstrap = true;
        parent::__construct();
        $this->displayName = $this->getTranslator()->trans('Featured Category Products without slider', array(), 'Module.FeaturedCategory.Admin');
        $this->description = $this->getTranslator()->trans('Displays specified products of category on home page without slider', array(), 'Module.FeaturedCategory.Admin');
        $this->templateFile = 'module:featuredcategorywoslider/views/templates/hook/featuredcategorywoslider.tpl';
    }
    public function install()
    {
        $this->_clearCache('*');
        Configuration::updateValue('CWOSLIDERFEATURED_ID', '3,6,9');
        if (!parent::install() || !$this->registerHook('header') || !$this->registerHook('addproduct') || !$this->registerHook('updateproduct') || !$this->registerHook('deleteproduct') || !$this->registerHook('categoryUpdate') || !$this->registerHook('displayHomeTab') || !$this->registerHook('displayHomeTabContent') || !$this->registerHook('displayHomeTop') || !$this->registerHook('displayHome') || !$this->registerHook('displayHomeBottom'))
        {
            return false;
        }
        return true;
    }
    public function uninstall()
    {
        $this->_clearCache('*');
        return parent::uninstall();
    }
    public function getContent()
    {
        $output = '';
        $errors = array();
        if (Tools::isSubmit('submitCategoryFeatured'))
        {
            Configuration::updateValue('CWOSLIDERFEATURED_ID', Tools::getValue('CWOSLIDERFEATURED_ID'));
        }
        return $output . $this->renderForm();
    }
    public function prepareBlocksProducts($products)
    {
        $products_for_template = [];
        $assembler = new ProductAssembler($this->context);
        $presenterFactory = new ProductPresenterFactory($this->context);
        $presentationSettings = $presenterFactory->getPresentationSettings();
        $presenter = new ProductListingPresenter(new ImageRetriever($this->context->link), $this->context->link, new PriceFormatter(), new ProductColorsRetriever(), $this->context->getTranslator());
        $products_for_template = [];
        foreach ($products as $rawProduct)
        {
            $products_for_template[] = $presenter->present($presentationSettings, $assembler->assembleProduct($rawProduct), $this->context->language);
        }
        return $products_for_template;
    }
	
	

	
    public function renderWidget($hookName = null, array $configuration = [])
    {
        if (!$this->isCached($this->templateFile, $this->getCacheId('featuredcategorywoslider'))) {
            $variables = $this->getWidgetVariables($hookName, $configuration);

            if (empty($variables)) {
                return false;
            }

            $this->smarty->assign($variables);
        }

        return $this->fetch($this->templateFile, $this->getCacheId('featuredcategorywoslider'));
    }
	
	public function hookdisplayHome($params)
{
    return $this->renderWidget(($params));
}
	
	
	
	
	
    public function getWidgetVariables($hookName = null, array $configuration = array())
    {
    	$arr = explode(",", Configuration::get('CWOSLIDERFEATURED_ID'));
    	$categories = array();
        foreach ($arr as $value) {
			$category = new Category($value);
			$cat = array();
			if($category->getProducts((int)Context::getContext()->language->id, 1) != '') {
				$cat['name'] = $category->name[(int)Context::getContext()->language->id];
                $cat['link'] = $category->getLink(null,(int)Context::getContext()->language->id);
				$cat['products'] = $this->prepareBlocksProducts($category->getProducts((int)Context::getContext()->language->id, 1, 30, 'date_add', 'DESC'));
				array_push($categories,$cat);
			}
		}
        return array(
            'categories' => $categories,
        );
    }
    public function hookAddProduct($params)
    {
        $this->_clearCache('*');
    }
    public function hookUpdateProduct($params)
    {
        $this->_clearCache('*');
    }
    public function hookDeleteProduct($params)
    {
        $this->_clearCache('*');
    }
    public function hookCategoryUpdate($params)
    {
        $this->_clearCache('*');
    }
    public function _clearCache($template, $cache_id = null, $compile_id = null)
    {
		parent::_clearCache($this->templateFile);
    }
    public function renderForm()
    {
        $fields_form = array(
            'form' => array(
                'legend' => array(
                    'title' => $this->getTranslator()->trans('Settings', array(), 'Module.FeaturedCategoryWOSlider.Admin'),
                    'icon' => 'icon-cogs'
                ),
                'description' => $this->getTranslator()->trans('Select category of products.', array(), 'Module.FeaturedCategoryWOSlider.Admin'),
                'input' => array(
                    array(
                        'type' => 'text',
                        'label' => $this->getTranslator()->trans('Category ID', array(), 'Module.FeaturedCategoryWOSlider.Admin'),
                        'name' => 'CWOSLIDERFEATURED_ID',
                        'required' => true,
                    ),
                ),
                'submit' => array('title' => $this->getTranslator()->trans('Save', array(), 'Module.FeaturedCategoryWOSlider.Admin'),)
            ),
        );
        $helper = new HelperForm();
        $helper->show_toolbar = false;
        $helper->table = $this->table;
        $lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
        $helper->default_form_language = $lang->id;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
        $this->fields_form = array();
        $helper->id = (int)Tools::getValue('id_carrier');
        $helper->identifier = $this->identifier;
        $helper->submit_action = 'submitCategoryFeatured';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->tpl_vars = array(
            'fields_value' => $this->getConfigFieldsValues(),
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id
        );
        return $helper->generateForm(array($fields_form));
    }
    public function getConfigFieldsValues()
    {
        return array(
            'CWOSLIDERFEATURED_ID' => Tools::getValue('CWOSLIDERFEATURED_ID', Configuration::get('CWOSLIDERFEATURED_ID')),
        );
    }
}

 

Link to comment
Share on other sites

I understand, It working, but I think there is something else because When I add or remove a product, the home page (with the feature product module) is loading in 6 7 seconds !

 

But when I try to load the category page, it's faster.

Link to comment
Share on other sites

I saw this on the php file :

 

			if($category->getProducts((int)Context::getContext()->language->id, 1) != '') {
				$cat['name'] = $category->name[(int)Context::getContext()->language->id];
                $cat['link'] = $category->getLink(null,(int)Context::getContext()->language->id);
				$cat['products'] = $this->prepareBlocksProducts($category->getProducts((int)Context::getContext()->language->id, 1, 30, 'date_add', 'DESC'));
				array_push($categories,$cat);

 

Maybe try a better rule in SQL for ONLY Select the last 30 products instead of every line no ?

Link to comment
Share on other sites

SELECT random 30 products: (I tested and when choosing from 300k products, the running time of the script is 0.08 seconds)

$getRandomProductByCategory = Db::getInstance()->executeS('SELECT id_product FROM '._DB_PREFIX_.'category_product WHERE id_category = '.$id_category.' ORDER BY RAND()
LIMIT 30'); 

$products = array();

foreach ($getRandomProductByCategory as $p){
	products[] = $p['id_product'];
}

$cat['products'] = $products;
Link to comment
Share on other sites

Thanks for your help.

 

Hmm but Why randomly ? and I don't know exactly where I can modify and add your code.

 

If we select 30 prodcut randomly it will be not good

 

actually it's like this

$cat['products'] = $this->prepareBlocksProducts($category->getProducts((int)Context::getContext()->language->id, 1, 30, 'date_add', 'DESC'));

 

 

Edited by okz (see edit history)
Link to comment
Share on other sites

  • razaro changed the title to Cache no working when add or remove products

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...