calling a function inside a class from another class php - php

I am very new to oops in php. Can anyone tell me how can i use a function
public static function getCategories($id_lang = false, $active = true,$order = true, $sql_filter = '', $sql_sort = '', $sql_limit = '')
{
if (!Validate::isBool($active))
die(Tools::displayError());
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT *
FROM `' . _DB_PREFIX_ . 'category` c
' . Shop::addSqlAssociation('category', 'c') . '
LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON c.`id_category` = cl.`id_category`' . Shop::addSqlRestrictionOnLang('cl') . '
WHERE 1 ' . $sql_filter . ' ' . ($id_lang ? 'AND `id_lang` = ' . (int)$id_lang : '') . '
' . ($active ? 'AND `active` = 1' : '') . '
' . (!$id_lang ? 'GROUP BY c.id_category' : '') . '
' . ($sql_sort != '' ? $sql_sort : 'ORDER BY c.`level_depth` ASC, category_shop.`position` ASC') . '
' . ($sql_limit != '' ? $sql_limit : '')
);
if (!$order)
return $result;
$categories = array();
foreach ($result as $row)
$categories[$row['id_parent']][$row['id_category']]['infos'] = $row;
return $categories;
}
getCategories() is inside a class named class CategoryCore i want to use this getcategory into a new class totalDiscount in which a function called configure_products();
How can i use getcategory() inside the configure products?

include the class file on the page
You can create a object of the class inside another class
function configure_products(){
$categories = new CategoryCore();
$categories->getcategory();
// use $categories to do stuff
......
.....
}
OR
You can call it directly
function configure_products(){
$categories = CategoryCore::getCategories();
.....
....
}

Your function getCategories() is a static function.
So, it can be called without creating object on teh class CategoryCore.
You can use it as (using scope resolution operator):
$categories = CategoryCore::getCategories(YOUR_ARGUMENTS)
Reference

Related

How can i return an array in php function

I need a return array in function. When i was use that returning this Array ( ):
function menuOlustur($ana_kategoriler){
global $db;
$alt_kategori_durum = '';
$alt_kategori;
foreach ($ana_kategoriler as $kategori) {
$alt_kategori = $db->rawQuery('select * from s_kategoriler where kategori = ' . $kategori['id'] . ' and durum=1 order by sira asc');
}
return $alt_kategori;
}
and i was use this returning one more index in array.
function menuOlustur($ana_kategoriler){
global $db;
$alt_kategori_durum = '';
$alt_kategori;
foreach ($ana_kategoriler as $kategori) {
$alt_kategori[] = $db->rawQuery('select * from s_kategoriler where kategori = ' . $kategori['id'] . ' and durum=1 order by sira asc');
}
return $alt_kategori;
}
My $ana_kategoriler is an array its a calling query like that
$ana_k_cek = $db->rawQuery('select id, kategori, adi_' . $dil . ' as adi,link_' . $dil . ' as link from s_kategoriler where m_id=5 and durum=1 order by sira asc ');
whats can i do ?
EDIT: fixed query, should not be kategori = 1,2,3,4, but kategory IN(1,2,3,4)
I suggest to change your code to:
function menuOlustur($ana_kategoriler){
global $db;
/* first - collect all ids */
$ids = array();
foreach ($ana_kategoriler as $kategori) {
$ids[] = $kategori['id'];
}
/* return empty array if there is no ids, or return result of single query matching all results with given ids */
return count($ids) > 0 ? $db->rawQuery('select * from s_kategoriler where kategori IN( ' . implode(",",$ids) . ') AND durum=1 order by sira asc') : array();
}

TYPO3 8.7.13 - MariaDB QueryBuilder FULLTEXT

SELECT name
FROM tx_snippethighlightsyntax_domain_model_snippets
WHERE (MATCH(name, description, code, comment) AGAINST ('css'));
This query works in phpMyAdmin with MariaDB. Now my "problem" is to adapt this in TYPO3 with QueryBuilder. I don't see any MATCH or AGAINST operator.
So far, my function start with this:
private $tx = 'tx_snippethighlightsyntax_domain_model_snippets';
public function ftsSearch()
{
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
$ftsQueryBuilder = $connectionPool->getQueryBuilderForTable($this->tx);
$fts = $ftsQueryBuilder
->select($this->tx . '.name')
->from($this->tx)
->where($ftsQueryBuilder->expr()->eq(
MAGIC HAPPENS HERE ?
)
->execute()
->fetchAll();
return $fts;
}
The extension Indexed Search in the TYPO3 core uses MATCH and AGAINST in queries.
The following code taken from IndexSearchRepository should help you building up your query
$searchBoolean = '';
if ($searchData['searchBoolean']) {
$searchBoolean = ' IN BOOLEAN MODE';
}
$queryBuilder->andWhere(
'MATCH (' . $queryBuilder->quoteIdentifier($searchData['fulltextIndex']) . ')'
. ' AGAINST (' . $queryBuilder->createNamedParameter($searchData['searchString'])
. $searchBoolean
. ')'
);
private $tx = 'tx_snippethighlightsyntax_domain_model_snippets';
public function ftsSearch()
{
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
$ftsQueryBuilder = $connectionPool->getQueryBuilderForTable($this->tx);
$fts = $ftsQueryBuilder
->select($this->tx . '.name')
->from($this->tx)
->where('MATCH('
. $this->tx .'.name,'
. $this->tx .'.description,'
. $this->tx .'.code,'
. $this->tx .'.comment)'
. ' AGAINST(' . $ftsQueryBuilder->createNamedParameter('put_search_here')
. ')')
->execute()
->fetchAll();
return $fts;
}
This one works for me. Thank you !

variable not work in where clause php joomla

I have function and my function works good only I do not understand this:
<?php
// $category output is 23 when I echo $category; and there is no records
->where('d.category_id = ' . (int) $category)
// also this method not work
->where('d.category_id = ' . $category)
// but this method works
->where('d.category_id = 23')
?>
this is full code:
$category = $params->get('title');
//echo $category;
public static function getSuggested($category) {
$db = JFactory::getDBO();
$query = $db->getQuery(true);
//$now = $jdate->toSql();
//$nullDate = $db->quote($db->getNullDate());
$query->select('d.*');
$query->from('#__deals_deals AS d');
$query->select('c.title AS category_title');
$query->join('LEFT', '#__deals_categories AS c ON c.id = d.category_id')
->where('(d.is_market = 0 AND d.state = 1)','AND')
->where('d.category_id = 23')
->order('id DESC');
//$query->where('(d.publish_up = ' . $nullDate . ' OR d.publish_up <= ' . $query->quote($now) . ')');
//$query->where('(d.publish_down = ' . $nullDate . ' OR d.publish_down >= ' . $query->quote($now) . ')');
$db->setQuery($query,0,10);
$results = $db->loadObjectList();
return $results;
}
this function works good only need to get category data.
this is joomla module, and this function is in helper.php file in default.php file I am get some data from this function.
I found solution:
Add in mod_suggested_deals.php
$category = (int) $params->get('fieldvalue');
then:
$results = modsuggested_dealsHelper::getSuggested($category);
I found soluton for this question:
in my function I Add param $category
public static function getSuggested($category) {...}
in mod_suggested_deals.php I add code:
$category = $params->get('title');
then is code (it already was here).
$results = modsuggested_dealsHelper::getSuggested($category);
The mistake you are doing is you are defining a variable value outside a function but calling the variable inside it. If your class is not abstract class you can use $this->category or if your class is an abstract class then use the $category variable inside of the function like this
public static function getSuggested() {
$module = JModuleHelper::getModule('mod_yourmodulename');
$catid = new JRegistry($module->params);
$category = (int) $catid['title'];
$db = JFactory::getDBO();
$query = $db->getQuery(true);
//$now = $jdate->toSql();
//$nullDate = $db->quote($db->getNullDate());
$query->select('d.*');
$query->from('#__deals_deals AS d');
$query->select('c.title AS category_title');
$query->join('LEFT', '#__deals_categories AS c ON c.id = d.category_id')
->where('(d.is_market = 0 AND d.state = 1)','AND')
->where('d.category_id = '.$category)
->order('id DESC');
//$query->where('(d.publish_up = ' . $nullDate . ' OR d.publish_up <= ' . $query->quote($now) . ')');
//$query->where('(d.publish_down = ' . $nullDate . ' OR d.publish_down >= ' . $query->quote($now) . ')');
$db->setQuery($query,0,10);
$results = $db->loadObjectList();
return $results;
}

php Object of class Closure could not be converted to string

I'm creating a search-function for my PHP-based file manager. I'm getting this error: 'Catchable fatal error: Object of class Closure could not be converted to string' on the following line:
if ($data->input_ext)
{
$data_ext = ($begun ? ($data->input_logic ? ' OR ' : ' AND ') :
function ()
{
$begun = true;
return "";
}) . 'ext = "' . $data->input_ext . '"';
$data_string.= $data_ext;
}
That's part of what builds the SQL query. $begun_files simply determines whether or not to put 'OR' or 'AND' at the beginning based on whether or not the user input a name or anything that comes before this to match. I have a feeling that I'm not allowed to include anonymous functions in ternary expressions but what should I do instead?
Thanks!
You can't use anonymous functions for inline flow control; just use a regular if statement and don't shun writing things on multiple lines:
if ($data->input_size) {
if ($begun_files) {
$str .= $data->input_logic ? ' OR ' : ' AND ';
$begun_files = true;
}
$str .= sprintf('size %s "%f"',
$data->input_size_op ? '<=' : '>=',
$data->input_size * pow(1024,$data->input_size_unit)
);
}
Building off of the previous answer I ended up going with this:
if ($data->input_ext) {
if ($begun) { $logic = $data->input_logic ? ' OR ' : ' AND '; } else { $logic = ""; $begun = true; }
$data_ext = $logic.'ext = "'.$data->input_ext.'"'; $data_string .= $data_ext;
}
if ($data->input_size) {
if ($begun) { $logic = $data->input_logic ? ' OR ' : ' AND '; } else { $logic = ""; $begun = true; }
$data_size = $logic.'size '.($data->input_size_op ? '<=' : '>=').' '.($data->input_size * pow(1024,$data->input_size_unit)); $data_string .= $data_size;
}
Thanks!

How to log the calling class infos?

I would like to override the CI_Log class to improve the log lines.
I want to log the name of the calling class, and the method.
Example :
DEBUG - 2011-04-23 09:21:29 - MY_Class - method --> Router Class Initialized
I tried to override the write_log mehod like this :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Log extends CI_Log {
public function write_log($level = 'error', $msg, $php_error = FALSE)
{
[...]
$message .=
$level .
(($level == 'INFO') ? ' - ' : ' - ') .
$this->router->fetch_class() .
' - ' .
$this->router->fetch_method() .
' - ' .
date($this->_date_fmt). ' --> ' .
$msg .
"\n";
[...]
}
}
But it doesn't work, the $this->router is not accessible.
Could you help me?
You can use somewhere in your method:
//$RTR is available from system/core/CodeIgniter.php
global $RTR;
$router_class = $RTR->fetch_class();
$rotuer_method = $RTR->fetch_method();
Ok, I think I got it. Here is my code :
[...]
$message .= $level.(($level == 'INFO') ? ' - ' : ' - ') . date($this->_date_fmt);
$stack = debug_backtrace();
// We are searching for the 2nd element of the $stack array beacause :
// - $stack[0] is always taken by JG_Log->write_log()
// - $stack[1] is always taken by log_message()
if (isset($stack[2]['class'])) {
$message .= ' - ' . $stack[2]['class'] . ' - ' . $stack[2]['function'];
}
$message .= ' --> '.$msg."\n";
[...]
I hope that can help others ! :-)

Categories