I want to display custom image of product on cart page in Magento.
Config.xml file
<checkout>
<rewrite>
<cart_item_renderer>ProductCustomizer_ProductCustomizer_Block_Checkout_Cart_Item_Renderer</cart_item_renderer>
</rewrite>
</checkout>
I have added below code in Block/Checkout/Cart/Item/Renderer.php file
<?php
class ProductCustomizer_ProductCustomizer_Block_Checkout_Cart_Item_Renderer extends Mage_Checkout_Block_Cart_Item_Renderer{
public function getProductThumbnail()
{
$item = $this->_item;
$customize_data = $item->getData('customize_data');
$customize_image = $item->getData('customize_image');
$results_data = $item->getOptionByCode("customizer_data")->getValue();
if(!is_null($results_data)){
$results = unserialize($results_data);
$path = Mage::getBaseDir()."/skin/";
$_product = $item->getProduct()->load();
$customize_image = $this->helper('catalog/image')->init($_product, 'thumbnail',$path.'adminhtml/default/default/images/logo.gif');
//$customize_image = $this->helper('catalog/image')->init($_product, 'thumbnail',$results['image']);
}
if (!empty($customize_image)) {
return $customize_image;
} else {
return parent::getProductThumbnail();
}
}
}
I have tried $customize_image with image "URL", "Path" and "Data (data:image/png;base64,iVBORw0KG....)" but it is not working.
So here is the idea. The init function you are calling is creating the issue for you. Do something like this as you have already done the override of that class.
public function getProductThumbnail1()
{
if (!is_null($this->_productThumbnail)) {
return $this->_productThumbnail;
}
return $this->getSkinUrl('images/jhonson.jpg');
//return $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail');
}
Add this function in that class you have already overridden which is Mage_Checkout_Block_Cart_Item_Renderer. Now in your app/design/frontend/rwd/default/template/checkout/cart/item/default.phtml file or whatever your file is call this function like this echo $this->getProductThumbnail1() rather than this echo $this->getProductThumbnail()->resize(180).
I have found solution. You have override Core class, I have added below class.
Create helper "Customezerimage.php" in Helper in custom module
<?php
class ProductCustomizer_ProductCustomizer_Helper_Customezerimage extends Mage_Catalog_Helper_Image {
public function setCustomeImage($path){
$this->_imageFile = $path;
$this->_setModel(Mage::getModel('productcustomizer/product_image'));
$this->_getModel()->setCustomeBaseFile($this->_imageFile);
return $this;
}
public function __toString() {
try {
$model = $this->_getModel();
$url = $model->getUrl();
} catch (Exception $e) {
$url = Mage::getDesign()->getSkinUrl($this->getPlaceholder());
}
return $url;
}
}
Create Model "Image.php" in Model/Product directory in custom module.
<?php
class ProductCustomizer_ProductCustomizer_Model_Product_Image extends Mage_Catalog_Model_Product_Image{
public function setCustomeBaseFile($baseFile){
if (!file_exists($baseFile)) {
throw new Exception(Mage::helper('catalog')->__('Image file was not found.'));
}
$this->_newFile = $this->_baseFile = $baseFile;
return $this;
}
public function saveCustomeImage($file = ""){
if(empty($file)){
$file = $this->_newFile;
}
Mage::log($file);
$this->getImageProcessor()->save($file);
return ;
}
public function getUrl(){
$baseDir = Mage::getBaseDir();
$path = str_replace($baseDir . DS, "", $this->_newFile);
return Mage::getBaseUrl() . str_replace(DS, '/', $path);
}
}
Now you can set custom image path that you want to display in cart like below
<?php
class ProductCustomizer_ProductCustomizer_Block_Checkout_Cart_Item_Renderer extends Mage_Checkout_Block_Cart_Item_Renderer{
public function getProductThumbnail()
{
$item = $this->_item;
$customize_data = $item->getData('customize_data');
$customize_image = $item->getData('customize_image');
$results_data = $item->getOptionByCode("customizer_data")->getValue();
if(!is_null($results_data)){
$results = unserialize($results_data);
$imagePathFull = $customize_image;
$_product = $item->getProduct();
$image = $imagePathFull;
return $this
->helper('productcustomizer/customezerimage')
->init($_product, 'thumbnail')->setCustomeImage($image);
}else{
return parent::getProductThumbnail();
}
}
}
Related
The following code is my template engine and it works great, with the small exception when a tpl file is not found the page should echo the error message "Error! Can't load the template file $templateFile".
namespace Template;
class Template
{
private $tags = [];
private $template;
public function __construct($templateFile)
{
$this->template = $this->getFile($templateFile);
if (!$this->template) {
return "Error! Can't load the template file $templateFile";
}
}
public function render()
{
$this->replaceTags();
echo $this->template;
}
public function set($tag, $value)
{
$this->tags[$tag] = $value;
}
public function getFile($file)
{
if (file_exists($file)) {
$file = file_get_contents($file);
return $file;
} else {
return false;
}
}
private function replaceTags()
{
foreach ($this->tags as $tag => $value) {
$this->template = str_replace('{'.$tag.'}', $value, $this->template);
}
return true;
}
}
I expect, when a matching .tpl file is not found the page should display "Error! Can't load the template file $templateFile", the actual output is a blank page.
Constructors are void function, Viod function means that can not return anything so you can't use return statement in constructor.
Instead of passing parameter in a constructor, Make a function for it and use return statement in that function
public function checkFile($filename)
{
$this->template = $this->getFile($filename);
if (!$this->template) {
return "Error! Can't load the template file $filename";
}
return true;
}
Make an Object of class and call that function
$obj = new Template;
$filexists = $obj->checkFile($filename);
if(!$filexists){
echo $filexists;
}
i'am not very well OO, and search a few web site to write this class
now my problem is how to use this class just like the Laravel 5.5 build in Storage class
i want use like this
MyStorage::disk('dropbox')
->addDirFilter('(school|travel)')
->addDirFilter('\d{4}-\d{2}-\d{2}')
->addFileFilter('.*\.jpg')
->getMatch();
here is MyStorage class
<?php
namespace App\MySupport;
class MyStorage
{
private $flag;
private $disk;
private $matches;
public function __construct()
{
$this->flag = false;
$this->disk = '';
$this->matches = [];
}
public function disk($disk)
{
$this->disk = $disk;
return $this;
}
public function addDirFilter($filter)
{
if (! $this->flag)
{
$this->flag = true;
$subDirs[] = \Storage::disk($this->disk)->directories();
}
else
{
foreach ($this->matches as $dir)
{
$subDirs[] = \Storage::disk($this->disk)->directories($dir);
}
}
$this->findMatch($subDirs, $filter);
return $this;
}
public function addFileFilter($filter)
{
if (! $this->flag)
{
$this->flag = true;
$subFiles[] = \Storage::disk($this->disk)->files();
}
else
{
foreach ($this->matches as $dir)
{
$subFiles[] = \Storage::disk($this->disk)->files($dir);
}
}
$this->findMatch($subFiles, $filter);
return $this;
}
public function findMatch($subItems, $filter)
{
// set empty before update
$this->matches = [];
// if call this method by addDirFilter() , $subItem contain the Dir path, eg, DirA/DirB
// if call this method by addFileFilter() , $subItem contain the File path, eg, DirX/File.txt
foreach (array_collapse($subItems) as $subItem)
{
// get the last str, eg, DirB OR File.txt
$lastStr = #end(explode('/', $subItem));
if ( preg_match('/^' . $filter . '$/u', $lastStr) )
{
// update new matches
$this->matches[] = $subItem;
}
}
}
public function getMatch()
{
return $this->matches;
}
}
Usage
<?php
namespace App\Http\Controllers;
use App\MySupport\MyStorage;
class TestController extends Controller
{
public function storageTest()
{
$MyStorage = new MyStorage();
// for example in my dropbox disk have
//
// school/2018-01-01/emails.txt
// school/2018-02-02/Peter.jpg
// travel/2017-06-06/TW.jpg
$folders = $MyStorage->disk('dropbox')
->addDirFilter('school')
->addDirFilter('\d{4}-\d{2}-\d{2}')
->getMatch();
// $folders result is:
// school/2018-01-01
// school/2018-02-02
$files = $MyStorage->disk('dropbox')
->addDirFilter('(school|travel)')
->addDirFilter('\d{4}-\d{2}-\d{2}')
->addFileFilter('.*\.jpg')
->getMatch();
// $files result is:
// school/2018-02-02/Peter.jpg
// travel/2017-06-06/TW.jpg
}
}
i tested seems all fine
can anyone point me to the direction, how to use MyStorage class just like Laravel 5.5 build in Storage class, thanks
You should use static function.
Try replace your function as code below.
public static function disk($disk)
{
$instance = new MyStorage();
$instance->disk = $disk;
return $instance;
Furthermore, I would suggest you learn singleton design pattern
Have PHP child classes add items to a shared array which is stored on the parent class.
Then at the end of load, have the parent class access all the items in that array that are added to it from all its child classes.
IN human terms, a Plugin system will allow Plugin classes to extend a parent abstract Plugin class which allows them to add JavaScript files to an array and at the end will load all the JS files from all the plugins into a page.
<?php
class BookmarksPlugin extends Plugins{
public function __construct(){
// add 2 JS files to array property on parent Plugins class
$this->enqueue_js_file('file-key1', 'fdg/dgdfg/jas-file-1.js', 1);
$this->enqueue_js_file('file-key2', 'fdg/dgdfg/js-file-2.js', 7);
//parent::enqueue_js_file('file-key1', 'fdg/dgdfg/jas-file-1.js', 1);
//parent::enqueue_js_file('file-key2', 'fdg/dgdfg/js-file-2.js', 7);
}
}
class SnippetsPlugin extends Plugins{
public function __construct(){
// add 2 JS files to array property on parent Plugins class
$this->enqueue_js_file('file-key3', 'fdg/dgdfg/jas-file-3.js', 1);
$this->enqueue_js_file('file-key4', 'fdg/dgdfg/js-file-4.js', 7);
//parent::enqueue_js_file('file-key3', 'fdg/dgdfg/jas-file-3.js', 1);
//parent::enqueue_js_file('file-key4', 'fdg/dgdfg/js-file-4.js', 7);
}
}
abstract class Plugins{
private $_js_files = array();
public function __construct(){
}
public function load_js_script_files(){
$html = '';
usort($this->_js_files, array($this, 'sortJSFiles'));
foreach ($this->_js_files as $obj => $jsScript) {
//$jsScript->script_key = $script_key;
//$jsScript->file_source = $file_source;
$html .= '<script type="text/javascript" src="'.$jsScript->file_source.'"></script>\n';
$html .= 'script type="text/javascript" src="'.$jsScript->file_source.'"></script>\n';
}
return $html;
}
public function enqueue_js_file($script_key, $file_source, $load_order = 0){
$jsScript = new \stdClass;
$jsScript->load_order = $load_order;
$jsScript->script_key = $script_key;
$jsScript->file_source = $file_source;
$this->_js_files[$script_key] = $jsScript;
}
public function sortJSFiles($a, $b)
{
if ($a->load_order == $b->load_order) {
return 0;
}
return ($a->load_order < $b->load_order) ? -1 : 1;
}
}
$bookmarksPlugin = new BookmarksPlugin;
$snippetsPlugin = new SnippetsPlugin;
// this function is in the core plugin class to include all the JS files that
// are added to the array property from the other plugins.
//
// Of course it doesnt work as it is flawed and that is where I am asking for help
// How can I make all my plugins add JS files to a single shared array and when done
// have it load all those JS files declared by all the plugins?
echo $plugin->load_js_script_files();
?>
How about this using traits or a variant thereof. Basically merge the scripts from each plugin before rendering them.
class JsScript
{
public $name;
public $src;
public $order;
public function __construct($name, $src, $order)
{
$this->name = $name;
$this->src = $src;
$this->order = $order;
}
}
trait JsLoader
{
protected $scripts;
public function getScripts()
{
return $this->_js_scripts;
}
public function enqueJs(JsScript $script)
{
$this->_js_scripts[] = $script;
}
public function renderScripts()
{
usort($this->_js_scripts, array($this, 'sortScripts'));
foreach($this->_js_scripts as $script)
{
echo $script->src;
}
}
protected function sortScripts($a, $b)
{
if ($a->order == $b->order) {
return 0;
}
return ($a->order < $b->order) ? -1 : 1;
}
}
class PluginRenderer
{
use JsLoader
{
renderScripts as jsLoaderRenderScripts;
}
protected $plugins;
public function __construct(array $plugins)
{
$this->plugins = $plugins;
}
public function renderScripts()
{
$scripts = array();
foreach($this->plugins as $plugin) {
$scripts = array_merge($scripts, $plugin->getScripts());
}
$this->_js_scripts = $scripts;
$this->jsLoaderRenderScripts();
}
}
class BookmarkPlugin {
use JsLoader;
}
class SnippetsPlugin {
use JsLoader;
}
Example use:
$bPlugin = new BookmarkPlugin;
$bPlugin->enqueJs(new JsScript('foo', 'foo/bar/baz', 99));
$bPlugin->enqueJs(new JsScript('big', 'big/fat/mama', 2));
$sPlugin = new SnippetsPlugin;
$sPlugin->enqueJs(new JsScript('y', 'y/u/no', 2));
$renderer = new PluginRenderer(array($bPlugin, $sPlugin));
$renderer->renderScripts();
Hello I want to integrate the SEOStats Class with a project in codeigniter , is anyone provide me solution ?
I have tried to make the SEOstats class as a helper and load the helper in the specific controler , but a blank page is showing , I also try to include it via view but the same blank page i am seeing ,
I have included this code in my view file , the SEOstats directory also in the same views directory .
<?php
require_once 'SEOstats/bootstrap.php';
use \SEOstats\Services as SEOstats;
try {
$url = 'http://www.google.com/';
// Create a new SEOstats instance.
$seostats = new \SEOstats\SEOstats;
// Bind the URL to the current SEOstats instance.
if ($seostats->setUrl($url)) {
echo SEOstats\Alexa::getGlobalRank();
echo SEOstats\Google::getPageRank();
}
}
catch (SEOstatsException $e) {
die($e->getMessage());
}
i have also used it as library
<?php
namespace SEOstats;
use SEOstats\Common\SEOstatsException as E;
use SEOstats\Config as Config;
use SEOstats\Helper as Helper;
use SEOstats\Services as Service;
class SEOstats
{
const BUILD_NO = Config\Package::VERSION_CODE;
protected static $_url,
$_host,
$_lastHtml,
$_lastLoadedUrl
= false;
public function __construct($url = false)
{
if (false !== $url) {
self::setUrl($url);
}
}
public function Alexa()
{
return new Service\Alexa;
}
public function Google()
{
return new Service\Google;
}
public function OpenSiteExplorer()
{
return new Service\OpenSiteExplorer;
}
public function SEMRush()
{
return new Service\SemRush;
}
public function Sistrix()
{
return new Service\Sistrix;
}
public function Social()
{
return new Service\Social;
}
public static function getHost()
{
return self::$_host;
}
public static function getLastLoadedHtml()
{
return self::$_lastHtml;
}
public static function getLastLoadedUrl()
{
return self::$_lastLoadedUrl;
}
/**
* Ensure the URL is set, return default otherwise
* #return string
*/
public static function getUrl($url = false)
{
$url = false !== $url ? $url : self::$_url;
return $url;
}
public function setUrl($url)
{
if (false !== Helper\Url::isRfc($url)) {
self::$_url = $url;
self::$_host = Helper\Url::parseHost($url);
}
else {
throw new E('Invalid URL!');
exit();
}
return true;
}
/**
* #return DOMDocument
*/
protected static function _getDOMDocument($html) {
$doc = new \DOMDocument;
#$doc->loadHtml($html);
return $doc;
}
/**
* #return DOMXPath
*/
protected static function _getDOMXPath($doc) {
$xpath = new \DOMXPath($doc);
return $xpath;
}
/**
* #return HTML string
*/
protected static function _getPage($url) {
$url = self::getUrl($url);
if (self::getLastLoadedUrl() == $url) {
return self::getLastLoadedHtml();
}
$html = Helper\HttpRequest::sendRequest($url);
if ($html) {
self::$_lastLoadedUrl = $url;
self::_setHtml($html);
return $html;
}
else {
self::noDataDefaultValue();
}
}
protected static function _setHtml($str)
{
self::$_lastHtml = $str;
}
protected static function noDataDefaultValue()
{
return Config\DefaultSettings::DEFAULT_RETURN_NO_DATA;
}
}
and loaded the library as
$this->load->library('SEOstats');
I know this post is old. But I was looking for a solution as well recently and ended up writing my own and figured I would leave it here in case anyone else was looking for a solution in the future.
Place the following in a library file and autoload if you want.
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class SEOstatistics {
private $seostats;
function __construct() {
require_once( APPPATH . 'third_party/seostats/bootstrap.php' );
$this->seostats = new \SEOstats\SEOstats;
}
private function alexa() {
return new \SEOstats\Services\Alexa;
}
private function google() {
return new \SEOstats\Services\Google;
}
private function moz() {
return new \SEOstats\Services\Mozscape();
}
private function openSiteExplorer() {
return new \SEOstats\Services\OpenSiteExplorer();
}
private function semRush() {
return new \SEOstats\Services\SemRush();
}
private function sistrix() {
return new \SEOstats\Services\Sistrix();
}
private function social() {
return new \SEOstats\Services\Social();
}
public function __call($method, $url) {
if (method_exists($this, $method)) {
if ($this->seostats->setUrl($url[0])) {
return call_user_func_array(array($this, $method),array());
}
return false;
}
}
}
And then an example of using it in a controller or model is:
$google = $this->seostatistics->google($url);
$rank = $google->getPageRank();
This is how I include SEOStats on my Codeigniter website
class Cron extends Frontend_Controller
{
public function get_google_page_rank() {
require_once (APPPATH . 'libraries/SEOstats/bootstrap.php');
try {
$url = 'http://www.google.com/';
// Get the Google PageRank for the given URL.
$pagerank = \SEOstats\Services\Google::getPageRank($url);
echo "The current Google PageRank for {$url} is {$pagerank}." . PHP_EOL;
}
catch(\Exception $e) {
echo 'Caught SEOstatsException: ' . $e->getMessage();
}
}
public function get_alexa_page_rank() {
require_once (APPPATH . 'libraries/SEOstats/bootstrap.php');
//use \SEOstats\Services\Alexa as Alexa;
try {
$url = 'https://www.google.com/';
// Create a new SEOstats instance.
$seostats = new \SEOstats\SEOstats;
// Bind the URL to the current SEOstats instance.
if ($seostats->setUrl($url)) {
/**
* Print HTML code for the 'daily traffic trend'-graph.
*/
echo \SEOstats\Services\Alexa::getTrafficGraph(1);
/**
* Print HTML code for the 'daily pageviews (percent)'-graph.
*/
echo \SEOstats\Services\Alexa::getTrafficGraph(2);
/**
* Print HTML code for the 'daily pageviews per user'-graph.
*/
echo \SEOstats\Services\Alexa::getTrafficGraph(3);
/**
* Print HTML code for the 'time on site (in minutes)'-graph.
*/
echo \SEOstats\Services\Alexa::getTrafficGraph(4);
/**
* Print HTML code for the 'bounce rate (percent)'-graph.
*/
echo \SEOstats\Services\Alexa::getTrafficGraph(5);
/**
* Print HTML code for the 'search visits'-graph, using
* specific graph dimensions of 320*240 px.
*/
echo \SEOstats\Services\Alexa::getTrafficGraph(6, false, 320, 240);
}
}
catch(\Exception $e) {
echo 'Caught SEOstatsException: ' . $e->getMessage();
}
}
}
Hope this helps
PS: Copy SEOstats folder in application/libraries folder
Im busy with an image moving function so im overriding some controller functions, and unfortuantly i required the items id for the image name so i changed form save() to postSaveHook() as i was not able to get the item id in save() but now im facing another problem i cant set form data to the newly renamed image.
Here's the code:
public function postSaveHook($model, $validData){
$item = $model->getItem();
$id = $item->get('id');
$path = JPath::clean(JPATH_SITE. DS ."images". DS ."menu_slider". DS );
$input=JFactory::getApplication()->input;
$input->get('jform', NULL, NULL);
$src_image = $this->moveOriginal($path,$id);
$imageTest = $this->findImages($src_image);
if(!empty($imageTest)){
foreach($imageTest as $images){
$this->createImageSlices($images,$src_image,$path);
}
}else{
echo 'all images are there';
}
/*this part no longer works*/
$data = JRequest::getVar( 'jform', null, 'post', 'array' );
$data['image'] = 'images'.DS.'menu_slider'.DS.'original'.DS.$src_image;
$input->post->set('jform',$data);
return parent::postSaveHook($model, $validData);
}
is there anyway i can save the data from this? or if i revert back to save, how would i get the id?
Any Help Greatly Appreciated.
I tried different ways and the absolute safest way for me was to add the following code in the model
class DPCasesModelCase extends JModelAdmin {
public function save($data) {
new EventHandler(JDispatcher::getInstance(), $this);
return parent::save($data);
}
}
class EventHandler extends JEvent {
private $model = null;
public function __construct(&$subject, $model) {
parent::__construct($subject);
$this->model = $model;
}
public function onContentChangeState($context, $pks, $value) {
if ($context != 'com_dpcases.case' && $context != 'com_dpcases.form') {
return;
}
if (! is_array($pks)) {
$pks = array($pks);
}
foreach ( $pks as $pk ) {
$this->dowork($this->model->getItem($pk), 'edit');
}
}
public function onContentAfterSave($context, $object, $isNew) {
if ($context != 'com_dpcases.case' && $context != 'com_dpcases.form') {
return;
}
$this->dowork($object, $isNew ? 'create' : 'edit');
}
private function dowork($object, $action) {
...
}
}