magento customize module Log functionality - php

I have created a custom module in Magento. Now I want to log(Debug) my module flow and processing function in Log/Debug file.
I know Mage::Log() function will do this but I want to customize its with my own log file.
So that I can view it another window.
Where should I write the Logger method so that I can access the method in all resource of Module like Module,Block,Controller and Helpers..
Please help me-
-Pravin

You can use method from /app/Mage.php
public static function log($message, $level = null, $file = '', $forceLog = false)
The 3d parameter is file, you can specify it and all log messages will be in it.
Mage::log('Some exseption', Zend_Log::ERR, 'my_module.log');

If I understand your question correctly; the best place to put such a method would be in your module's helper.
app/code/local/My/Module/Helper/Data.php:
class My_Module_Helper_Data extends Mage_Core_Helper_Data
{
public function myLog( $desc, $val, $log = 'my_module.log' ) {
return Mage::log( $desc, $val, $log );
}
}
This way you can call your own log via the module helper class:
Mage::helper('my_module')->myLog( 'A variable: ', $val );
However, I do agree with #viakondratiuk that this might not be a great idea, since it's more complicated that the default Mage::log method.

Related

TYPO3 v8. Override function in Core class

I need to override the function
protected function getLanguageParameter()
{
$states = $this->getBackendUser()->uc['moduleData']['web_view']['States'];
$languages = $this->getPreviewLanguages();
$languageParameter = '';
if (isset($states['languageSelectorValue']) && isset($languages[$states['languageSelectorValue']])) {
$languageParameter = '&L=' . (int)$states['languageSelectorValue'];
}
$languageParameter = '&L=1';
return $languageParameter;
}
in the class TYPO3\CMS\Viewpage\Controller\ViewModuleController. It get called when you are open the View in the backend.
Lets say I would extend the class in my own extension. I already need a Hook that calls the function?
But how can I get that hook?
If the function has no hook yet you can try to insert it: make a patch and wait for it to become merged.
As 8 LTS already receives only 'priority bugfixes' it probably will not get merged.
The other way would be XClassing.

Slim 2 Render Direct HTML

I have an old project I'm working on using Slim version 2. I can not upgrade to 3.
I'm trying to integrate twig into slim 2 while also keeping the old default slim2 renderer.
Currently I have this.
class TwigView extends \Slim\View
{
public function rendertwig($template,$data = array()){
global $twig;
$twigResults = $twig->render($template,array('test' => '1'));
$data = array_merge($this->data->all(), $data);
return $this->render($twigResults, $data);
}
}
$view = new TwigView();
$config['view'] = $view; //#JA - This command overides the default render method.
//#JA - Intialize Slim
$app = new \Slim\Slim($config);
The idea is that I would call this saying $app->view->rendertwig('file.twig') when I need to render the twig templates and use $app->render('template.php') for all the other templates that use the default slim2 method of templating.
However, I get an error because in my rendertwig function $this->render() function requires a template name for the first parameter. Is there a way I can render directly the results from twig into the slim engine without needing a template file?
I'm aware this is bad form to have two templating engines but eventually I will switch everything to Twig but I need this as a temporary solution till I can patch everything over.
When I inspected slim's view object it has this defined as its render method which will explain the issue.
protected function render($template, $data = null)
{
$templatePathname = $this->getTemplatePathname($template);
if (!is_file($templatePathname)) {
throw new \RuntimeException("View cannot render `$template` because the template does not exist");
}
$data = array_merge($this->data->all(), (array) $data);
extract($data);
ob_start();
require $templatePathname;
return ob_get_clean();
}
I don't know if this is bad form but I did this as a temporary solution.
class TwigView extends \Slim\View
{
public function rendertwig($template,$data = array()){
global $twig;
$twigResults = $twig->render($template,array('test' => '1'));
echo $twigResults;
}
}
I saw that all the render method did was just require the template so I figured its safe to just echo the results from the twig templating engine? This seemed to work from my test.

CakePHP3 - Custom page error 404 not working

I doing tutorial follow http://book.cakephp.org/3.0/en/development/errors.html#exception-renderer but it is not working and display blank page.
In config/bootstrap.php
use App\Error\AppError;
$errorHandler = new AppError();
$errorHandler->register();
In src/Error/AppError.php
<?php
namespace App\Error;
use Cake\Error\BaseErrorHandler;
class AppError extends BaseErrorHandler
{
public function _displayError($error, $debug)
{
return 'There has been an error!';
}
public function _displayException($exception)
{
return 'There has been an exception!';
}
public function handleFatalError($code, $description, $file, $line)
{
return 'A fatal error has happened';
}
}
I create my_error.ctp in src/Template/Layout/my_error.ctp. And in my src/Template/Error/error404.ctp I change layout to my_error.ctp.
$this->layout = 'my_error';
Finally, In my controller
use Cake\Network\Exception\NotFoundException;
$staff = $this->Staff->find()->where(['Staff.StaffId = '=> $id, 'Staff.PartnerId = ' =>$this->partnerId])->first();
if (empty($staff)) {
throw new NotFoundException(__('Staff not found'));
}
Whenever encountering blank pages, enabled debug mode, visit the URL again, and check your error logs.
However, problem in this case is most likely that the docs are incorrect/misleading, as the example app error won't do anything at all. The _ prefixed methods are ment to be protected, having them return something has no effect, and handleFatalError is ment to return a boolean.
Just look at the source of Cake\Error\BaseErrorHandler and the core error handler Cake\Error\ErrorHandler, the methods that you are overwriting are ment to generate output!
You may want to report that as an issue over at GitHub.
If all you want to do, is create a custom 4xx error page, then all you need to do is to edit the src/Template/Error/error400.ctp template accordingly.
I found my mistake. :(
Because in bootstrap.php I copy below code at the end of file. Therefore Cake cannot understand it. Please close this issue. Thank you for support.
use App\Error\AppError;
$errorHandler = new AppError();
$errorHandler->register();

Override Prestashop Module Changes not Visible

I am attempting to override a module in Prestashop but the changes are just not appearing.
I have overridden a template file and a controller so I have added the following files:
\override\modules\blockwishlist\views\templates\front\mywishlist.tpl
\override\modules\blockwishlist\controllers\front\mywishlist.php
These are very simple changes where I add another column to a table that contains a button. When the button is clicked the controller generates a CSV file.
Any idea why these changes are just not being shown?
Note: I have turned on 'Force Compile' and turned of caching.
Edit:
Re overridding a controller is it:
class BlockWishListMyWishListModuleFrontController extends BlockWishListMyWishListModuleFrontControllerCore // extends ModuleFrontController
or
class BlockWishListMyWishListModuleFrontControllerOverride extends BlockWishListMyWishListModuleFrontController
okay, I did some code research (maybe thre is exists easiest way, not sure), so:
in code Dispatcher class we have
// Dispatch module controller for front office
case self::FC_MODULE :
$module_name = Validate::isModuleName(Tools::getValue('module')) ? Tools::getValue('module') : '';
$module = Module::getInstanceByName($module_name);
$controller_class = 'PageNotFoundController';
if (Validate::isLoadedObject($module) && $module->active) {
$controllers = Dispatcher::getControllers(_PS_MODULE_DIR_.$module_name.'/controllers/front/');
if (isset($controllers[strtolower($this->controller)])) {
include_once(_PS_MODULE_DIR_.$module_name.'/controllers/front/'.$this->controller.'.php');
$controller_class = $module_name.$this->controller.'ModuleFrontController';
}
}
$params_hook_action_dispatcher = array('controller_type' => self::FC_FRONT, 'controller_class' => $controller_class, 'is_module' => 1);
break;
where we see that controllers loaded without overrides, but from other side below in code we see hook execution:
// Loading controller
$controller = Controller::getController($controller_class);
// Execute hook dispatcher
if (isset($params_hook_action_dispatcher)) {
Hook::exec('actionDispatcher', $params_hook_action_dispatcher);
}
so one of possible solution (without overriding core class) :
how to override module and hope you have core version >= 1.6.0.11
in blockwishlist.php in install() method add
this->registerHook('actionDispatcher')
to condition with other hooks, so it will looks like ... !this->registerHook('actionDispatcher') || ... because this hook not registered by default and we can't just place module there.
create method (can't beautify code here)
public function hookActionDispatcher($params)
{
if ('blockwishlistmywishlistModuleFrontController' == $params['controller_class']) {
include_once(_PS_OVERRIDE_DIR_ . 'modules/' . $this->name . '/controllers/front/mywishlist.php');
$controller = Controller::getController('BlockWishListMyWishListModuleFrontControllerOverride');
}
}
you already have override/modules/blockwishlist/controllers/front/mywishlist.php file by this path
reinstall module.
it works!
more about overriding some behaviors in docs
Turns out that to override a module you dont place your files in:
~/overrides/module/MODULE_NAME
Instead you place it in:
~/themes/MY_THEME/modules/MODULE_NAME
Now the changes are exhibiting themselves.
Does anyone know if/when the module is auto-updated, will my changes get lost/overrwritten?

Can't load modules from libraries in CodeIgniter HMVC

I'm having a problem loading modules inside my template library in CodeIgniter HMVC. The reason I want to load a module in the template library is that I wish to use modules for sideboxes and other content boxes in my template.
PS: I am also using the Smarty template parsing system for CodeIgniter, but I doubt it has anything to do with the errors, but if you have reasons to believe otherwise, please, let me know.
What I tried to do
I tried to load the module in two different ways, and both presented with the same errors.
The errors
A PHP Error was encountered
Severity: Notice
Message: Undefined Property CI::$template
File: MX/Loader.php
Line Number: 141
-
A PHP Error was encountered
Severity: Notice
Message: Undefined Property CI::$template
Filename: MX/Controller.php
Line number: 57
-
Fatal error: Call to a member function load_content() on a non-object in E:\Xampp\htdocs\firecms\application\modules\sidebar_login_box\controllers\sidebar_login_box.php on line 7
The undefined "load_content()" function will be explained further down (in Sidebar Controller).
The Error lines
MX/Loader
/*Line 140*/if (isset($this->_ci_classes[$class]) AND $_alias = $this->_ci_classes[$class])
/*Line 141*/ return CI::$APP->$_alias;
MX/Controller
/*Line 56*/public function __get($class) {
/*Line 57*/ return CI::$APP->$class;
How I tried to load the modules
This was my first attempt (loading the file and instancing its class):
class Template {
//[...]
public function load_sidebars()
{
$sidebars = $this->CI->cms_model->get_sidebars();
foreach ($sidebars as $sidebar)
{
if (trim($sidebar["content"]) == "")
{
//An example of sidebar module name is "sidebar:login_box"
//The function below changes the name to "sidebar_login_box" (the
//module's folder and controller name.
$module = str_replace(':', '_', $sidebar["module"]);
$file_path = APPPATH.'modules/'.$module.'/controllers/'.$module.'.php';
require_once $file_path;
$class = ucfirst($module);
$object = new $class();
$module_data = $object->index();
$this->_section_data["sidebars"][]["content"] = $module_data;
}
else
{
$this->_section_data["sidebars"][]["content"] = $sidebar["content"];
}
}
}
//[...]
}
And this was my second attempt (using the loader function):
public function load_sidebars()
{
$sidebars = $this->CI->cms_model->get_sidebars();
foreach ($sidebars as $sidebar)
{
if (trim($sidebar["content"]) == "")
{
$module = str_replace(':', '_', $sidebar["module"]);
$this->CI->load->module($module);
$module_data = $this->CI->$module->index();
$this->_section_data["sidebars"][]["content"] = $module_data;
}
else
{
$this->_section_data["sidebars"][]["content"] = $sidebar["content"];
}
}
}
The sidebar controller
This is how the sidebar controller looks like:
class Sidebar_login_box extends Fire_Controller {
public function index()
{
$view_data = array();
//The load_content function in the template library is used to parse template files
//and return them as a string.
return $this->template->load_content("login_box", $view_data);
}
}
The Fire Controller
The Fire_Controller is my core controller. My core classes' prefix is Fire_ instead of MY_.
This is how the fire controller looks like:
class Fire_Controller extends MX_Controller {
public function __construct()
{
parent::__construct();
//Load configurations from the database.
$this->config->load_db_configs();
//Set the timezone.
date_default_timezone_set(config_item("timezone"));
//Loads the form validation library.
$this->load->library("form_validation");
//Reset the Form Validation CI Object (to fix problems with HMVC CI).
$this->form_validation->CI =& $this;
//To reduce load time, the template library will not be loaded in ajax
//requests.
if ( ! $this->input->is_ajax_request())
{
$this->load->library("template");
}
//Force access via SSL connection (HTTPS) if necessary.
if ((int)config_item('force_https') === 1)
{
force_https();
}
}
Note: This is a very recent project of mine, which means that the framework and all third party extensions are in the most recent stable version as of January 06, 2015.
Thank you for your time,
Best regards.
Fixed.
The sidebars were loaded from the set_defaults() method, which was called by the constructor method in my template library. And since it wasn't fully loaded, the template object was not saved in CI's super object, thus being inaccessible and throwing the errors in the sidebar module.
I have moved the set_defaults() call to the render_page() function of my template library (which are called by the modules' controllers), and now it's working perfectly.
Too bad I added bounty a few hours before finding the solution, hehe.
You need to load the library before you can use it in the sidebar controller. It isn't being passed from the parent. Try this:
class Sidebar_login_box extends Fire_Controller {
public function index()
{
$view_data = array();
$this->load->library('template');
//The load_content function in the template library is used to parse template files
//and return them as a string.
return $this->template->load_content("login_box", $view_data);
}
}
Cheers!

Categories