Magento custom cache issue on product view page - magento

We added the custom cache for product view page.
We rewrite the view.php file and write below code :
<?php
/**
* Rewriting Product View block
*/
class XXX_YYY_Block_Catalog_Product_View extends Mage_Catalog_Block_Product_View
{
protected function _construct()
{
$this->addData(array(
//'cache_key' =>
//'cache_lifetime' =>
'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_TAG . "_" . $this->getProduct()->getId()),
));
}
public function getCacheKey()
{
if (!$this->hasData('cache_key')) {
//$cacheKey = LAYOUTNAME_STORE+ID_PRODUCT+ID
$cacheKey = $this->getNameInLayout().'_STORE'.Mage::app()->getStore()->getId().'_PRODUCT'.$this->getProduct()->getId();
//.'_'.Mage::getDesign()->getPackageName().'_'.Mage::getDesign()->getTheme('template'). //_PACKAGE_THEME ?
$this->setCacheKey($cacheKey);
}
return $this->getData('cache_key');
}
public function getCacheLifetime()
{ //to prevent sub-blocks caching
if($this->getNameInLayout()!='product.info') return null;
//return false; //false creates default lifetime (7200)
return 9999999999;
}
}
?>
After the rewrite code added the add to cart functionality and global messages not working in product view page.
Help to fix this issue.
Thanks

Related

call another controller from dashboard using template pages

I working on Codeigniter project, I create page template to load header left menu and footer, everything working good, when I try the open link in the menu I want to open another controller. I do it but when the controller view open the variable inside to load database table for each row not working.. but the controller who load the database when I open it without my template its working fine
The Dashboard controller
class Dashboard extends CI_Controller{
protected $data = array();
function __construct()
{
parent::__construct();
$this->data['pagetitle'] = 'Invoices Manager';
}
protected function render($the_view)
{
$this->data['the_view'] = (is_null($the_view)) ? '' : $this->load->view($the_view,$this->data, TRUE);
$this->load->view('templates/master_page', $this->data);
}
public function home() {
// $this->load->view('templates/master_page', $this->data);
$this->render( 'templates/homepage_view');
}
public function dashboard() {
// $this->load->view('templates/master_page', $this->data);
$this->render( 'dashboard/home');
}
public function purchaselist(){
$this->render('purchase/index');
}
}
The purchase controller that working good alone
class Purchase extends CI_Controller{
protected $data = array();
protected $mydata = array();
function __Construct()
{
parent::__Construct ();
$this->load->database(); // load database
$this->load->model('Purchase_model'); // load model
$this->mydata['purchase']=null;
}
public function index()
{
$query = $this->Purchase_model->getPurchaselist();
if($query)
{
$mydata['purchase'] = $query;
}
$this->load->view('purchase/index', $mydata);
// $this->render( 'purchase/index');
}
}
when I call dashboard/purchaselist they say the
Message: Undefined variable: purchase
Filename: purchase/index.php
Line Number: 17
its should load database table inside the template
try using dashboard/index.php/purchaselist or load your modal $this->load->model('Purchase_model'); as global
Please pass null or empty array in purchase if $query is empty
public function index()
{
$query = $this->Purchase_model->getPurchaselist();
if(!empty($query)){
$mydata['purchase'] = $query;
}else{
$mydata['purchase'] = array();
}
$this->load->view('purchase/index', $mydata);
// $this->render( 'purchase/index');
}

URL change issue after form post in Codeigniter

how can i manage url in address bar after posting a form or after loading a page after submission.
Is it possible to manage with routing ?
<?php
public function index(){
$this->load->view('login');
}
public function login_process(){
....... code......
if($login==true){
$this->load->view('dashboard'); // Url is not changing but view is loaded
}else{
$this->load->view('login');
}
}
?>
Hope this will help you :
Use redirect() method from url helper , make sure you load it in controller or in autoload.php
public function login_process()
{
....... code......
if($login === TRUE)
{
redirect('controller_name/dashboard','refresh');
/*$this->load->view('dashboard'); */
}
else
{
redirect('controller_name/index','refresh');
/*$this->load->view('login');*/
}
}
For more :https://www.codeigniter.com/user_guide/helpers/url_helper.html#redirect
You should create another method called dashboard and you should redirect to it like following
class Example_Controller extends CI_Controller {
public function index(){
$this->load->view('login');
}
public function dashboard(){
$this->load->view('dashboard');
}
public function login_process(){
// Your Code
redirect('Example_Controller/' . (($login==true) ? 'dashboard' : 'index'));
}
}
replace Example_Controller with your controller name.
and add following lines in routes.php
$route['login'] = 'Example_Controller/index';
$route['dashboard'] = 'Example_Controller/dashboard';

Laravel, Singleton - how to send data to all controllers?

I'm doing shopping site. I made Cart Model, which is Singleton. My shopping cart exists in session always ( no matter or User is login or not ). Now I have to invoke every time in every Controllers and actions getInstance to check or there's key "cart".
Is there a possibility to do this automaticly for all views?
Here is code of my Singleton:
class Cart
{
private $cartModel;
private static $instance;
private function __construct()
{
$this->cartModel = new CartModel();
$cart = Session::get('cart');
if ($cart == null) {
Session::put('cart', array());
}
}
private function __clone()
{
}
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new Cart();
}
return self::$instance;
}
public function get(){
return Session::get('cart');
}
}
And here for example how it looks in Controllers and actions:
class StoreController extends Controller
{
public function mainSite()
{
$cart=Cart::getInstance()->get();
return View('zoo');
}
public function showCategory($categoryName)
{
$cart=Cart::getInstance()->get();
$category = new Category();
$categoryId = (int)$category->getCategoryId($categoryName);
$subCategories = Subcategory::where('category_id', $categoryId)->get();
return View('zoo-category', ['subCategories' => $subCategories, 'categoryName' => $categoryName]);
}
public function showSubcategory()
{
$cart=Cart::getInstance()->get();
}
I have to do this all the time: $cart=Cart::getInstance()->get();
Is there a possibility to do this only one time?
You can take advantage of Laravel's dependency injection. Bind your class to the IoC container and you can either access it through the IoC container or you can have Laravel automatically inject this into your controllers in several different ways.
Read more here: https://laravel.com/docs/5.4/container
Add it to base controller's constructor so that it gets called on every controller method.
// app/Http/Controllers/Controller.php
protected $cart;
public function __construct()
{
$this-> cart = Cart::getInstance()->get();
}
But i honestly see no point in your singleton class. All it does is set the cart with an empty array when it's not defined. Also $this->cartModel = new CartModel(); is this ever used?

Using Doctrine in Joomla 1.5

I'm trying to use Doctrine in Joomla 1.5 but have not been able to get anything running.
According to this article: http://magazine.joomla.org/issues/issue-may-2011/item/447-using-doctrine-ORM-in-joomla
I immediately get Fatal error: Class 'Fatal error: Call to undefined method JController::getInstance() in /var/www/html/hosts/joomla/public_html/components/com_bugs/bugs.php on line 13
The bugs.php looks like this:
// no direct access
defined('_JEXEC') or die; // Include dependancies
jimport('joomla.application.component.controller');
//require_once(JPATH_LIBRARIES . '/doctrine/vendor/autoload.php');
require_once(JPATH_LIBRARIES . '/doctrine/bootstrap.php');
require_once(JPATH_LIBRARIES . '/doctrine/JoomlaDoctrineBootstrapper.php');
require_once(JPATH_COMPONENT.DS.'controller.php');
//$controller = new BugsController(JRequest::getVar('task', ''));
$controller = JController::getInstance('Bugs');
Not sure how to implement this, when trying to use the $controller = new BugsController the error is: Fatal error: Class 'JController' not found in
This because I have the autoload on in bugs.php and have /public_html/components/com_bugs/controller.php extend /public_html/libraries/doctrine/JoomlaDoctrineBootstrapper.php the JoomlaDoctrineBootstrapper exends JController but JController cannot be found anymore after composer and the autoload did something.
I'm starting to think that it's not possible to use Joomla with Doctrine since Doctrine has to be installed with composer (didn't find any other documentation on how to download and configure it) and composer seems to want everything in vendor so have to put all the Joomla classes in vendor too?
[UPDATE]
It looks like whatever composer does in /public_html/libraries/doctrine/vendor/autoload.php completely breaks jimport('joomla.application.component.controller')
Not including the autoload however gives me another problem, like none of the Doctrine classes are found: Class 'Doctrine\Common\Cache\ArrayCache' not found
Maybe I'll try and hack /public_html/libraries/doctrine/vendor/composer/autoload_real.php to try and see if that one can load Joomla classes for me.
Either jimport or composer won't work because jimport defines __autoload. Instead of __autoload I'm using spl_autoload_register that only seems to work with PHP version starting from 5.1.2.
Changed loader:
/public_html/libraries/loader.php
class JLoader
{
public static function autoload($class)
{
if(JLoader::load($class)) {
return true;
}
return false;
}
//... other code and comments
function import( $filePath, $base = null, $key = 'libraries.' )
{
static $paths;
if (!isset($paths)) {
$paths = array();
//assuming PHP 5 >= 5.1.2
spl_autoload_register(array('JLoader', 'autoload'), true, true);
}
//remove the __autoload function
The bugs.php looks like this:
/public_html/components/com_bugs/bugs.php
<?php
// no direct access
defined('_JEXEC') or die; // Include dependancies
require_once(JPATH_LIBRARIES . '/doctrine/vendor/autoload.php');
require_once(JPATH_LIBRARIES . '/doctrine/bootstrap.php');
require_once(JPATH_LIBRARIES . '/doctrine/JoomlaDoctrineBootstrapper.php');
require_once(JPATH_COMPONENT.DS.'controller.php');
//using links like /index.php?option=com_bugs&format=text&task=save
// defaults to link so above is same as: http://joomla/index.php?option=com_bugs&format=text&task=save&router=link
$route=JRequest::getVar('router', 'Link');
$controllerName = 'bugsController'.$route;
//include the controller
include_once(dirname(__FILE__) . '/controllers/'.$route.".php");
$controller = new bugsControllerlink(JRequest::getVar('task', ''));
$controller->setEntityManager(bootstrapDoctrine());
$controller->execute(JRequest::getVar('task', ''));
$controller->redirect();
/**
* Initialize doctrine by setting the entities and proxies locaties. Also define
* a default namespace for the proxies.
*/
function bootstrapDoctrine() {
$doctrineProxy = new JoomlaDoctrineBootstrapper(JoomlaDoctrineBootstrapper::APP_MODE_DEVELOPMENT);
$doctrineProxy->setEntityLibrary(dirname(__FILE__) . '/models');
$doctrineProxy->setProxyLibrary(dirname(__FILE__) . '/proxies');
$doctrineProxy->setProxyNamespace('Joomla\Proxies');
$doctrineProxy->setConnectionOptions(getConfigurationOptions());
$doctrineProxy->bootstrap();
return $doctrineProxy->getEntityManager();
}
function getConfigurationOptions() { // Define database configuration options
$joomlaConfig = JFactory::getConfig();
return array('driver' => 'pdo_mysql', 'path' => 'database.mysql'
, 'dbname' => $joomlaConfig->getValue("config.data.db")
, 'user' => $joomlaConfig->getValue("config.data.user")
, 'password' => $joomlaConfig->getValue("config.data.password"));
}
?>
The link controller looks like: (file name has start with a capital L)
/public_html/components/com_bugs/controllers/Link.php
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla controller library (done by composer)
//jimport('joomla.application.component.controller');
class bugsControllerlink extends JoomlaDoctrineBootstrapper{
function __construct()
{
parent::__construct();
$this->registerTask( 'show','show' );
$this->registerTask( 'save','save' );
}
function save(){
$model=$this->getModel('link');
$view = $this->getView('show','text');
$view->setLayout('save');
$model->em=$this->getEntityManager();
$view->data = $model->save();
$view->display();
}
}
Didn't change the boodtrap, that still looks like this:
/public_html/libraries/doctrine/bootstrap.php
<?php
interface JoomlaDoctrineController {
public function setEntityManager(Doctrine\ORM\EntityManager $entityManager);
}
?>
The /public_html/libraries/doctrine/JoomlaDoctrineBootstrapper.php looks like:
<?php
/** * Configuration class to integrate Doctrine into Joomla. *
* #author pderaaij <removed email, check link in question> */
use Composer\Autoload\ClassLoader,
Doctrine\ORM\EntityManager,
Doctrine\ORM\Configuration,
Doctrine\Common\Cache\ArrayCache;
jimport( 'joomla.application.component.controller' );
class JoomlaDoctrineBootstrapper extends JController{
const APP_MODE_DEVELOPMENT = 1;
const APP_MODE_PRODUCTION = 2;
private $applicationMode;
private $cache;
private $entityLibrary;
private $proxyLibrary;
private $proxyNamespace;
private $entityManager;
private $connectionOptions;
public function __construct($applicationMode=1) {
$this->applicationMode = $applicationMode;
$this->_name="bugs";
parent::__construct();
}
public function getConnectionOptions() {
return $this->connectionOptions;
}
public function setConnectionOptions($connectionOptions) {
$this->connectionOptions = $connectionOptions;
}
public function getProxyLibrary() {
return $this->proxyLibrary;
}
public function setProxyLibrary($proxyLibrary) {
$this->proxyLibrary = $proxyLibrary;
}
public function getProxyNamespace() {
return $this->proxyNamespace;
}
public function setProxyNamespace($proxyNamespace) {
$this->proxyNamespace = $proxyNamespace;
}
public function getCache() {
return $this->cache;
}
public function setCache($cache) {
$this->cache = $cache;
}
public function getEntityLibrary() {
return $this->entityLibrary;
}
public function setEntityLibrary($entityLibrary) {
$this->entityLibrary = $entityLibrary;
}
public function getApplicationMode() {
return $this->applicationMode;
}
public function setApplicationMode($applicationMode) {
$this->applicationMode = $applicationMode;
}
public function getEntityManager() {
return $this->entityManager;
}
public function setEntityManager($entityManager) {
$this->entityManager = $entityManager;
}
/** * Bootstrap Doctrine, setting the libraries and namespaces and creating * the entitymanager */
public function bootstrap() {
$this->registerClassLoader(); // Load cache
if ($this->getApplicationMode() == self::APP_MODE_DEVELOPMENT) {
$this->cache = new ArrayCache;
} else {
$this->cache = new ApcCache;
} /** #var $config Doctrine\ORM\Configuration */ $config = new Configuration;
$config->setMetadataCacheImpl($this->cache);
$driverImpl = $config->newDefaultAnnotationDriver($this->getEntityLibrary());
$config->setMetadataDriverImpl($driverImpl);
$config->setQueryCacheImpl($this->cache);
$config->setProxyDir($this->getProxyLibrary());
$config->setProxyNamespace($this->getProxyNamespace());
if ($this->applicationMode == self::APP_MODE_DEVELOPMENT) {
$config->setAutoGenerateProxyClasses(true);
} else {
$config->setAutoGenerateProxyClasses(false);
} $this->entityManager = EntityManager::create($this->getConnectionOptions(), $config);
}
/** * Register the different classloaders for each type. */
private function registerClassLoader() { // Autoloader for all the Doctrine library files
//Doctrine was done by public_html/libraries/doctrine/vendor/autoload.php
// $classLoader = new ClassLoader('Doctrine', dirname(__FILE__) . '/');
// $classLoader->register(); // Autoloader for all Entities
//name of ComposerAutoloader is defined in /public_html/libraries/doctrine/vendor/composer/autoload_real.php
$modelLoader = ComposerAutoloaderInit825f56ea1383e6b7fef7ea99c51fea36::getLoader();
$modelLoader->set("Entities\\",dirname(__FILE__)."/../../components/com_"
//not sure how to do the proxies yet, have to check this with production settings
// $proxiesClassLoader = new ClassLoader('Proxies', $this->getProxyLibrary());
// $proxiesClassLoader->register();
}
}
?>
The Joomla model save function looks something like this (checking received JSON should be done in a controller or helper function):
public function save() {
//a textbox having the name 'json' or xhr post
$link = JRequest::getVar('json',false,'post');
if($link==false){
return;
}
$link = json_decode($link);
$newLink = new Link();
$newLink->setId($link->id);
$newLink->setName($link->name);
foreach($link->categories as $category){
$cat = new Category();
$cat->setId($category->id);
$cat->setName($category->name);
$newLink->addCategorie($cat);
}
$this->em->persist($newLink);
$this->em->flush();
return $link;
}
I guess the code as is will break when using APP_MODE_PRODUCTION in /public_html/components/com_bugs/bugs.php

Laravel: Passing data to default.blade.php from base controller

I have a base controller with a method to return a twitter feed to my view.
I want to move this in the view from the page view to the default blade to reduce redundancy as it will be appearing site wide. How do I pass data from the base controller to blade?
I can send it to my view from the page controller like so:
public function get_index()
{
..................
$this->layout->nest('content', 'home.index', array(
'tweets' => $this->get_tweet()
));
}
and in the view, output it like this:
if ($tweets)
{
foreach ($tweets as $tweet)
{
..............
I want to do all this from within default.blade.php and my Base_Contoller:
<?php
class Base_Controller extends Controller {
/**
* Catch-all method for requests that can't be matched.
*
* #param string $method
* #param array $parameters
* #return Response
*/
public function __call($method, $parameters)
{
return Response::error('404');
}
public function get_tweet()
{
...........
return $tweets;
}
}
How is this possible?
//////////////////////UPDATE/////////////////////////////
application/models/tweets.php
<?php
class Tweets {
public static function get($count = 3)
{
Autoloader::map(array(
'tmhOAuth' => path('app').
'libraries/tmhOAuth-master/tmhOAuth.php',
'tmhUtilities' => path('app').
'libraries/tmhOAuth-master/tmhUtilities.php'
));
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'xxx',
'consumer_secret' => 'xxx',
'user_token' => 'xxxxx',
'user_secret' => 'xxxxx',
'curl_ssl_verifypeer' => false
));
$code = $tmhOAuth->request('GET',
$tmhOAuth->url('1.1/statuses/user_timeline'), array(
'screen_name' => 'xxx',
'count' => $count
));
$response = $tmhOAuth->response['response'];
$tweets = json_decode($response, true);
return $tweets;
}
}
application/views/widgets/tweets.blade.php
#foreach ($tweets)
test
#endforeach
application/views/layouts/default.blade.php
....
{{ $tweets }}
....
application/composers.php
<?php
View::composer('widgets.tweets', function($view)
{
$view->tweets = Tweets::get();
});
View::composer('layouts.default', function($view)
{
$view->nest('tweets', 'widgets.tweets');
});
application/controllers/base.php
<?php
class Base_Controller extends Controller {
/**
* Catch-all method for requests that can't be matched.
*
* #param string $method
* #param array $parameters
* #return Response
*/
public $layout = 'layouts.default';
public function __call($method, $parameters)
{
return Response::error('404');
}
}
application/controllers/home.php
<?php
class Home_Controller extends Base_Controller {
public $layout = 'layouts.default';
public $restful = true;
public function get_index()
{
Asset::add('modernizr', 'js/thirdparty/modernizr.js');
Asset::add('jquery',
'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');
Asset::add('scripts', 'js/scripts.js');
$this->layout->title = 'title';
$this->layout->nest('content', 'home.index', array(
//'data' => $some_data
));
}
}
Is giving me an
Undefined variable: tweets
error
Step 1 - Make a view just for your tweets, let's call it widgets/tweets.blade.php, that will accept your $tweets data. This makes it very easy to cache the tweets view in the future if you want a little more performance. We also want a model that will generate the tweet data for you.
Step 2 - Pass the tweet data into your tweets view, let's use a View Composer for this so the logic is kept with (but outside) the view.
Step 3 - Create your default layout, let's call this layout/default.blade.php. This will accept $content and $tweets. We'll nest the tweets view with another View Composer. You can nest the $content in your controller actions.
Step 4 - Set the $layout on your Base_Controller.
Step 5 - Profit!
Note - If these are your first view composers then you'll need to include them in application/start.php
// application/models/tweets.php
class Tweets {
public static function get($count = 5)
{
// get your tweets and return them
}
}
// application/views/widgets/tweets.blade.php
#foreach ($tweets)
{{-- do something with your tweets --}}
#endforeach
// application/views/layouts/default.blade.php
<section class="main">{{ isset($content) ? $content : '' }}</section>
<aside class="widget widget-tweets">{{ $tweets }}</aside>
// application/composers.php
View::composer('widgets.tweets', function($view)
{
$view->tweets = Tweets::get();
});
View::composer('layouts.default', function($view)
{
$view->nest('tweets', 'widgets.tweets');
});
// application/start.php (at the bottom)
include path('app').'composers.php';
// application/controllers/base.php
class Base_Controller extends Controller {
public $layout = 'layouts.default';
}
// application/controllers/home.php
class Home_Controller extends Base_Controller {
public $restful = true;
public function get_index()
{
$this->layout->nest('content', 'home.welcome');
}
}
View::share('key', 'value');
in you view use (Blade syntax)
{{$key}}
or (PHP syntax)
echo $key;

Resources