I am using this to retrieve the database connection atm.
$db = Zend_Db_Table::getDefaultAdapter();
I do set this up in my config like this:
resources.db.adapter = pdo_mysql
resources.db.isDefaultTableAdapter = true
resources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password = password
resources.db.params.dbname = db
resources.db.params.profiler.enabled = true
resources.db.params.profiler.class = Zend_Db_Profiler
I would like to output everything to a sql.log for example. Is this possible to apply on the default adapter? for example through the settings, so I can ignore it in production environment?
Much appriciated.
I did look at: How to enable SQL output to log file with Zend_Db? but it didn't seem to cover my issue.
/Marcus
There is an example of extending Zend_Db_Profiler so you can write the queries to /logs/db-queries.log file.
So you have to do the following:
Create My_Db_Profiler_Log class in the library folder
Add the following lines to the application.ini
resources.db.params.profiler.enabled = true
resources.db.params.profiler.class = My_Db_Profiler_Log
Note: be aware, that the log file will become very big, very soon! So it is a good idea to log only the queries you are interested in. And this example should be considered only as a starting point in implementation of such a logging system.
Here is the code for the custom profiler class:
<?php
class My_Db_Profiler_Log extends Zend_Db_Profiler {
/**
* Zend_Log instance
* #var Zend_Log
*/
protected $_log;
/**
* counter of the total elapsed time
* #var double
*/
protected $_totalElapsedTime;
public function __construct($enabled = false) {
parent::__construct($enabled);
$this->_log = new Zend_Log();
$writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/logs/db-queries.log');
$this->_log->addWriter($writer);
}
/**
* Intercept the query end and log the profiling data.
*
* #param integer $queryId
* #throws Zend_Db_Profiler_Exception
* #return void
*/
public function queryEnd($queryId) {
$state = parent::queryEnd($queryId);
if (!$this->getEnabled() || $state == self::IGNORED) {
return;
}
// get profile of the current query
$profile = $this->getQueryProfile($queryId);
// update totalElapsedTime counter
$this->_totalElapsedTime += $profile->getElapsedSecs();
// create the message to be logged
$message = "\r\nElapsed Secs: " . round($profile->getElapsedSecs(), 5) . "\r\n";
$message .= "Query: " . $profile->getQuery() . "\r\n";
// log the message as INFO message
$this->_log->info($message);
}
}
?>
Extend the Zend_Db_Profiler to write to an SQL.log and attach the profiler to your db adapter
<?php
class File_Profiler extends Zend_Db_Profiler {
/**
* The filename to save the queries
*
* #var string
*/
protected $_filename;
/**
* The file handle
*
* #var resource
*/
protected $_handle = null;
/**
* Class constructor
*
* #param string $filename
*/
public function __construct( $filename ) {
$this->_filename = $filename;
}
/**
* Change the profiler status. If the profiler is not enabled no
* query will be written to the destination file
*
* #param boolean $enabled
*/
public function setEnabled( $enabled ) {
parent::setEnabled($enabled);
if( $this->getEnabled() ) {
if( !$this->_handle ) {
if( !($this->_handle = #fopen($this->_filename, "a")) ) {
throw new Exception("Unable to open filename {$this->_filename} for query profiling");
}
}
}
else {
if( $this->_handle ) {
#fclose($this->_handle);
}
}
}
/**
* Intercept parent::queryEnd to catch the query and write it to a file
*
* #param int $queryId
*/
public function queryEnd($queryId) {
$state = parent::queryEnd($queryId);
if(!$this->getEnabled() || $state == self::IGNORED) {
return;
}
$profile = $this->getQueryProfile($queryId);
#fwrite($this->_handle, round($profile->getElapsedSecs(),5) . " " . $profile->getQuery() . " " . ($params=$profile->getQueryParams())?$params:null);
}
}
Haven't test it, but it should do the trick. Give it a try and let me know.
Btw you do know that you can log all queries on the mysql as well?
this will let you see sql queries to the web page , IT MIGHT BE OFF TOPIC but it helpful
I am highly recommend you to use ZF debug bar , it will give you very handy information
i am using it to see my doctrine queries , and it had support for zend db too
https://github.com/jokkedk/ZFDebug
Related
I have Created a save quote extension for one of my clients every thing is working fine
But when a customer print a pdf Quote its show the POUND symbol instead of showing the quote currency code EURO My code is given below I have tried many ways to add currency code but it is not working
public function __construct(
\Magento\Payment\Helper\Data $paymentData,
\Magento\Framework\Stdlib\StringUtils $string,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\Filesystem $filesystem,
Config $pdfConfig,
\Magento\Sales\Model\Order\Pdf\Total\Factory $pdfTotalFactory,
\Magento\Sales\Model\Order\Pdf\ItemsFactory $pdfItemsFactory,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
\Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
\Magento\Sales\Model\Order\Address\Renderer $addressRenderer,
AddressQuoteRenderer $addressQuoteRenderer,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Store\Model\App\Emulation $appEmulation,
\Magento\Framework\Pricing\Helper\Data $helper,
OrderFactory $orderFactory,
array $data = []
) {
$this->orderFactory = $orderFactory;
$this->addressQuoteRenderer = $addressQuoteRenderer;
$this->helper = $helper;
$this->_appEmulation = $appEmulation;
parent::__construct(
$paymentData,
$string,
$scopeConfig,
$filesystem,
$pdfConfig,
$pdfTotalFactory,
$pdfItemsFactory,
$localeDate,
$inlineTranslation,
$addressRenderer,
$storeManager,
$appEmulation,
$data
);
}
/**
* Return PDF document
*
* #param Collection $quotes
*
* #return \Zend_Pdf
* #throws \Magento\Framework\Exception\LocalizedException
* #throws \Zend_Pdf_Exception
*/
public function getPdf($quotes = [])
{
$this->_beforeGetPdf();
$this->_initRenderer('order');
$pdf = new \Zend_Pdf();
$this->_setPdf($pdf);
$order = $this->orderFactory->create();
foreach ($quotes as $quote) {
if ($quote->getStoreId()) {
$this->_appEmulation->startEnvironmentEmulation($quote->getStoreId());
$this->_storeManager->setCurrentStore($quote->getStoreId());
}
$page = $this->newPage();
$this->_setFontBold($page, 10);
$quote->setQuote($quote);
/* Add image */
$this->insertLogo($page, $quote->getStore());
/* Add address */
$this->insertAddress($page, $quote->getStore());
/* Add head */
$this->insertOrder($page, $quote, false);
/* Add table */
$this->_drawHeader($page);
$this->_initRenderer('default');
/* Add body */
$taxTotal = 0;
foreach ($quote->getAllItems() as $item) {
if ($item->getParentItem()) {
continue;
}
/* Keep it compatible with the invoice */
$item->setQty($item->getQty());
$item->setProductType($item->getProduct()->getTypeId());
$this->_initRenderer($item->getProduct()->getTypeId());
$item->setOrderItem($item);
$taxTotal += $item->getTaxAmount();
/* Draw item */
$this->_drawItem($item, $page, $order);
$page = end($pdf->pages);
}
/* Add totals */
$order->setStoreId($quote->getStoreId());
$order->setSubtotal($quote->getSubtotal());
$order->setGrandTotal($quote->getSubtotal() + $taxTotal);
$order->setShippingAmount($quote->getShippingAddress()->getShippingAmount());
$order->setTaxAmount($taxTotal);
$order->setOrder($order);
$this->insertTotals($page, $order);
if ($quote->getStoreId()) {
$this->_appEmulation->stopEnvironmentEmulation();
}
Please Help and suggest to me where I am wrong I am stuck in this problem
Thanks for your help in advance
I have a problem when I run compile
I get this error
Errors during compilation:
Ortho\Theme\Block\Html\Custommenu
Incorrect dependency in class Ortho\Theme\Block\Html\Custommenu in /var/www/vhosts/domux.eu/dmx/app/code/Ortho/Theme/Block/Html/Custommenu.php
\Magento\Store\Model\StoreManagerInterface already exists in context object
Total Errors Count: 1
Can someone please tell me what code I have to remove or modify from this php file ?
public function __construct(
Template\Context $context,
NodeFactory $nodeFactory,
TreeFactory $treeFactory,
CategoryFactory $categoryFactory,
\Magento\Cms\Model\Template\FilterProvider $filterProvider,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Cms\Model\BlockFactory $blockFactory,
Registry $registry,
\Ortho\Theme\Helper\Data $dataHelper,
array $data = []
) {
parent::__construct($context,$nodeFactory,$treeFactory, $data);
$this->categoryFactory = $categoryFactory;
$this->_filterProvider = $filterProvider;
$this->_storeManager = $storeManager;
$this->_blockFactory = $blockFactory;
$this->coreRegistry = $registry;
// $this->dataHelper = $dataHelper;
//$this->_menu = $this->getMenu();
$this->nodeFactory = $nodeFactory;
$this->treeFactory = $treeFactory;
}
/**
* Get block cache life time
*
* #return int
*/
protected function getCacheLifetime()
{
return parent::getCacheLifetime() ?: 3600;
}
Thank you a lot.
best regards
Please see https://magento.stackexchange.com/questions/172655/magento-2-1-errors-during-compilation-incorrect-dependency-in-class.
You have here all explanation and how to solve it.
I am trying to read the username of a front end user whose uid is known. I tried this in my controller's showAction method:
$objectManger = t3lib_div::makeInstance('Tx_Extbase_Object_ObjectManager');
// get repository
$repository = $objectManger->get('Tx_Extbase_Domain_Repository_FrontendUserRepository ');
$newObject = $repository->findByUid($coupon->getCreator()); //this is the uid of whoever was loggin in
print_r($newObject);
echo $newObject->getUsername(); die;
but when that code runs I get:
Oops, an error occured!
"Tx_Extbase_Domain_Repository_FrontendUserRepository " is not a valid cache entry identifier.
It turns out that $repository is empty, so how do I get fe_user data?
I am using typo3 v4.5 with extbase.
Thanks
Update to show complete answer.
This is the code (it goes in my CouponController) that worked (plus the typoscript mentioned):
/**
* #var Tx_Extbase_Domain_Repository_FrontendUserRepository
*/
protected $userRepository;
/**
* Inject the user repository
* #param Tx_Extbase_Domain_Repository_FrontendUserRepository $userRepository
* #return void */
public function injectFrontendUserRepository(Tx_Extbase_Domain_Repository_FrontendUserRepository $userRepository) {
$this->userRepository = $userRepository;
}
public function showAction(Tx_Coupons_Domain_Model_Coupon $coupon) {
$userRepository = $this->objectManager->get("Tx_Extbase_Domain_Repository_FrontendUserRepository");
$newObject = $userRepository->findByUid($coupon->getCreator());
$this->view->assign('coupon', $coupon);
$this->view->assign('creatorname', $newObject->getUsername() );
}
If you are using extbase yourself you dont have to call makeInstance for your objectManager, it's already there ($this->objectManager).
anyway, you should inject this repository (see my answer here: TYPO3 - Call another repository)
Clear the Cache after the Injection.
You maybe have to disable the recordtype extbase sets for its FrontendUser:
config.tx_extbase.persistence.classes.Tx_Extbase_Domain_Model_FrontendUser.mapping.recordType >
Set the source storage pid where the repository fetches the data from:
/** #var Tx_Extbase_Domain_Repository_FrontendUserRepository $repos */
$repos = $this->objectManager->get("Tx_Extbase_Domain_Repository_FrontendUserRepository");
$querySettings = $repos->createQuery()->getQuerySettings();
$querySettings->setStoragePageIds(array(123, 567));
$repos->setDefaultQuerySettings($querySettings);
$user = $repos->findByUid(56); // Queries for user 56 in storages 123 and 567
Duplicate of this question
I'm trying to create a web service with Zend_Soap_Server in wsdl autodiscovery mode, but I obtain very strange effects... here the code:
server:
<?php
require_once('Zend/Soap/AutoDiscover.php');
require_once('Zend/Soap/Server.php');
require_once('Zend/Soap/Wsdl.php');
require_once('library/SoapActions.php');
$wsdl = new Zend_Soap_Autodiscover();
$wsdl->setClass('SoapActions');
if (isset($_GET['wsdl'])) {
$wsdl->handle();
} else {
$server = new Zend_Soap_Server('http://localhost:8083/server.php?wsdl');
$server->setClass('SoapActions');
$server->setEncoding('ISO-8859-1');
$server->handle();
}
SoapActions class:
class SoapActions {
/**
* Test function
*
* #param String $a
* #param String $b
* #return String
*/
public function test1($a, $b) {
return "you passed me ".$a." ".$b;
}
/**
* Test function 2
*
* #param String $a
* #param String $b
* #return String
*/
public function test2($a, $b) {
return "you passed me ".$a." ".$b;
}
}
I tried to use the function test1 and test2 using the Zend_Soap_Client class, here the code:
require_once('Zend/Soap/Client.php');
$client = new Zend_Soap_Client("http://localhost:8083/server.php?wsdl");
try {
echo $client->test2("foo","bar"); //this works!
} catch (Exception $e) {
echo $e;
}
try {
echo $client->test1("foo","bar"); //this doesn't work!
} catch (Exception $e) {
echo $e;
}
I cannot understand because the test2 function works as expected, the test1 function return the following exception:
SoapFault exception: [Sender] Function
("test1") is not a valid method for
this service in
/usr/local/zend/share/ZendFramework/library/Zend/Soap/Client.php:1121
Stack trace:
0 /usr/local/zend/share/ZendFramework/library/Zend/Soap/Client.php(1121):
SoapClient->__soapCall('test1', Array,
NULL, NULL, Array)
1 /usr/local/zend/apache2/htdocs/webservice/client.php(6):
Zend_Soap_Client->__call('test1',
Array)
2 /usr/local/zend/apache2/htdocs/webservice/client.php(6):
Zend_Soap_Client->test1('foo', 'bar')
3 {main}
I tried to invert the functions name... the result is incredible, works only test2! I'm getting crazy, it seems that somewhere on server side it save the function name...
Can someone help me?
SOLVED! The problem was this setting in the php.ini file:
soap.wsdl_cache_enabled=1
I set this to 0 and now it works fine!
If you don't want change your php.ini:
// WSDL_CACHE_NONE; /* 0 Pas de cache */
// WSDL_CACHE_DISK; /* 1 Sur le disque supprimer le fichier pour le réinitialiser */
// WSDL_CACHE_MEMORY; /* 2 En mémoire => redémarrer Apache pour le réinitialiser */
// WSDL_CACHE_BOTH; /* 3 En mémoire et sur le disque */
$options = array();
$options['cache_wsdl'] = WSDL_CACHE_NONE;
$client = new Zend_Soap_Client("http://localhost:8083/server.php?wsdl", $options);
So you can use something like this:
$query = $db->select();
$query->from('pages', array('url'));
echo $query->__toString();
to examine the sql that the Zend Db Framework is going to use for that SELECT query. Is there an equivilent way to view the SQL for an update?
$data = array(
'content' => stripslashes(htmlspecialchars_decode($content))
);
$n = $db->update('pages', $data, "url = '".$content."'");
??
Use Zend_Db_Profiler to capture and report SQL statements:
$db->getProfiler()->setEnabled(true);
$db->update( ... );
print $db->getProfiler()->getLastQueryProfile()->getQuery();
print_r($db->getProfiler()->getLastQueryProfile()->getQueryParams());
$db->getProfiler()->setEnabled(false);
Remember to turn the profiler off if you don't need it! I talked to one fellow who thought he had a memory leak, but it was the profiler instantiating a few PHP objects for each of the millions of SQL queries he was running.
PS: You should use quoteInto() in that query:
$n = $db->update('pages', $data, $db->quoteInto("url = ?", $content));
No, not directly, since Zend Framework builds and executes the SQL inside the adapter method Zend_Db_Adapter_Abstract::update:
/**
* Updates table rows with specified data based on a WHERE clause.
*
* #param mixed $table The table to update.
* #param array $bind Column-value pairs.
* #param mixed $where UPDATE WHERE clause(s).
* #return int The number of affected rows.
*/
public function update($table, array $bind, $where = '')
{
/**
* Build "col = ?" pairs for the statement,
* except for Zend_Db_Expr which is treated literally.
*/
$set = array();
foreach ($bind as $col => $val) {
if ($val instanceof Zend_Db_Expr) {
$val = $val->__toString();
unset($bind[$col]);
} else {
$val = '?';
}
$set[] = $this->quoteIdentifier($col, true) . ' = ' . $val;
}
$where = $this->_whereExpr($where);
/**
* Build the UPDATE statement
*/
$sql = "UPDATE "
. $this->quoteIdentifier($table, true)
. ' SET ' . implode(', ', $set)
. (($where) ? " WHERE $where" : '');
/**
* Execute the statement and return the number of affected rows
*/
$stmt = $this->query($sql, array_values($bind));
$result = $stmt->rowCount();
return $result;
}
You can, temporarily, insert a var_dump and exit inside this method to inspect the sql to ensure that it is correct:
/**
* Build the UPDATE statement
*/
$sql = "UPDATE "
. $this->quoteIdentifier($table, true)
. ' SET ' . implode(', ', $set)
. (($where) ? " WHERE $where" : '');
var_dump($sql); exit;
I quess another way is to log the actual SQL query, rather than changing the ZF library code, by combining the profiler data.
$db->getProfiler()->setEnabled(true);
$db->update( ... );
$query = $db->getProfiler()->getLastQueryProfile()->getQuery();
$queryParams = $db->getProfiler()->getLastQueryProfile()->getQueryParams();
$logger->log('SQL: ' . $db->quoteInto($query, $queryParams), Zend_Log::DEBUG);
$db->getProfiler()->setEnabled(false);
Recently came across this looking for a way to debug a zend_db_statement. If anyone else comes across this with the same search, you can use the following function.
Just replace "self::getDefaultAdapter()" with your method of getting a DB connection or adapter.
/**
* replace any named parameters with placeholders
* #param string $sql sql string with placeholders, e.g. :theKey
* #param array $bind array keyed on placeholders, e.g. array('theKey', 'THEVALUE')
*
* #return String sql statement with the placeholders replaced
*/
public static function debugNamedParamsSql($sql, array $bind) {
$sqlDebug = $sql;
foreach($bind as $needle => $replace) {
$sqlDebug = str_replace(
':' . $needle,
self::getDefaultAdapter()->quote($replace),
$sqlDebug
);
}
return $sqlDebug;
}