Issues with foreach in php to call a function - php

In the following code, the function parseImages is not implemented.
Can someone help me to call the function parseImages in the foreach:
foreach ($listFeatured as &z$product) {
$product['description'] = substr(trim(strip_tags($product['description_short'])), 0, $maxDesc);
$product['price'] = Tools::displayPrice($product['price']);
$product = $this->parseImages($product, $params);
$product = $this->generateImages($product, $params);
}
function parseImages($product, $params) {
global $link;
$isRenderedMainImage = $params->get("cre_main_size", 0);
if (_PS_VERSION_ <= "1.5.0.17") {
$mainImageSize = $params->get("main_img_size", 'thickbox');
} else {
$mainImageSize = $params->get("main_img_size", 'thickbox_default');
}
if ($isRenderedMainImage) {
if ((int) Configuration::get('PS_REWRITING_SETTINGS') == 1) {
$product["mainImge"] = $this->getImageLink($product["link_rewrite"], $product["id_image"]);
} else {
$product["mainImge"] = $link->getImageLink($product["link_rewrite"], $product["id_image"]);
}
} else {
$product["mainImge"] = $link->getImageLink($product["link_rewrite"], $product["id_image"], $mainImageSize);
}
$product["thumbImge"] = $product["mainImge"];
return $product;
}
This is a piece of a module of Prestashop and I want to use it twice.
If solved I will share the solution to all Prestashop users.

You're using as an object method $this->parseImages() but you defined it as a function:
function parseImages($product, $params) {
[...]
}
You can keep this function like this and use parseImages() without the $this-> or if you're inside a class change your function declaration to this:
public function parseImages($product, $params) {
[...]
}
You should read some documentation about OOP

Related

PHP Optional Function Parameter Set to Reference to Existing Object

I don't even know if this is possible but I'm trying to set an optional value to an existing object.
Here is a simplified version of the code I'm trying.
<?php
class configObject {
private $dataContainer = array();
public function set($dataKey, $dataValue) {
$this->dataContainer[$dataKey] = $dataValue;
return TRUE;
}
public function get($dataKey) {
return $this->dataContainer($dataKey);
}
$this->set('someValue', 'foobar');
} //End configObject Class
function getPaginationHTML($c = &$_config) {
$someOption = $c->get('someValue');
// Do other stuff
return $html;
}
$_config = new configObject();
$html = getPaginationHTML();
?>
I'm getting the error:
syntax error, unexpected '&' in
Any help is appreciated, again I'm not sure if it's even possible to do what I'm trying to do so sorry for being a noob.
Thanks
example with the decorator pattern:
class ConfigObject {
private $dataContainer = array();
public function set($dataKey, $dataValue) {
$this->dataContainer[$dataKey] = $dataValue;
return true;
}
public function get($dataKey) {
return $this->dataContainer[$dataKey];
}
}
class ConfigObjectDecorator {
private $_decorated;
public function __construct($pDecorated) {
$this->_decorated = $pDecorated;
}
public function getPaginationHTML($dataKey) {
$someOption = $this->get($dataKey);
// Do other stuff
$html = '<p>' . $someOption . '</p>';
return $html;
}
public function set($dataKey, $dataValue) {
return $this->_decorated->set($dataKey, $dataValue);
}
public function get($dataKey) {
return $this->_decorated->get($dataKey);
}
}
class ConfigFactory {
public static function create () {
$config = new ConfigObject();
return new ConfigObjectDecorator($config);
}
}
$config = ConfigFactory::create();
if ($config->set('mykey', 'myvalue'))
echo $config->getPaginationHTML('mykey');
Note that can easily rewrite ConfigFactory::create() to add a parameter to deals with other types of decoration (or none).

Proper array(&$this) syntax with arguments

Take the following code example:
<?php
class A {
public function aa() {
$output = (array(&$this, 'ab'), $post_id);
return $output;
}
public function ab( $post_id ) {
//do stuff
}
}
?>
What's the correct way to call method ab that contains additional arguments like $post_id?
I know that the $output line doesn't work, but that's the line I'm stuck on.
Thanks.
Just this way:
$output = $this->ab($post_id);
Try this . May be this will help.
<?php
class A {
public function aa() {
$args = func_get_args();
$output = call_user_func_array(array($this,'ab'),$args);
// But this way the "ab" function have to be private
// Or you can simply do $output = $this->ab($post_id)
return $output;
}
public function ab( $post_id ) {
//do stuff
}
}
$a = new A();
$a->aa(162);
?>

PHP class: Unable to access array in another function

I tried a lot of search but unable to figure out why array $wordlinks in function DoWordLink is not carrying values from function __construct. PHP class code as below:
<?php
class autolinkkeyword
{
public $wordlinks = array();
public function __construct(){
$query = mysql_query("SELECT keyword FROM library");
while ($row = mysql_fetch_array($query))
{
$this->wordlinks [$row["keyword"]] = $row["keyword"];
}
}
public function linkkeywords ($posts)
{
function DoWordLink($match)
{
$rpl=$match[1];
if(isset($wordlinks[$rpl]))
{
$kword = $this->wordlinks[$rpl];
$rpl="<a class=\"keyword_link\" href=\"#\" onclick=\"popup('popUpDiv');
ajax_loadContent('kword', 'library.php?keyword=$kword')\">$kword</a>";
unset($this->wordlinks[$match[1]]);
}
return $rpl;
}
$wl=array_keys($this->wordlinks);
$pm="/((?<=\s|^)(?:" . implode('|',$wl) .")(?=\.|\!|\?|\,|\'|\s|$))/im";
foreach($posts as $key => $mainbody)
{
$mainbody=preg_replace_callback($pm, 'DoWordLink', $mainbody) ;
echo $mainbody;
}
}
}
?>
You can make it an actual method of that class and call it using this method:
http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback
like:
preg_replace_callback($pm, array($this, 'DoWordLink'), $mainbody);
Change DoWordLink function so it is part of the class like:
class autolinkkeyword
{
function DoWordLink($match)
{
$rpl=$match[1];
if(isset($this->wordlinks[$rpl]))
{
$kword = $this->wordlinks[$rpl];
$rpl="<a class=\"keyword_link\" href=\"#\" onclick=\"popup('popUpDiv');
ajax_loadContent('kword', 'library.php?keyword=$kword')\">$kword</a>";
unset($this->wordlinks[$match[1]]);
}
return $rpl;
}
}
aren't you missing a "this->" construct here? if(isset($this->wordlinks[$rpl]))
Use the $this everywhere you refer to $wordlinks.
$this->wordlinks
You need to access the property in your linkkeywords-method with the object-accessor, too!
public function linkkeywords ($posts)
{
// Here use $this->wordlinks not $wordlinks
}

Call to a member function get_segment() error

I'm having this problem with this piece of PHP code:
class Core {
public function start()
{
require("funk/funks/libraries/uri.php");
$this->uri = new uri();
require("funk/core/loader.php");
$this->load = new loader();
if($this->uri->get_segment(1) != "" and file_exists("funk/pages/".$uri->get_segment(1).".php")){
Only a snippet of the code
The best way I can explain it is that it is a class calling upon another class (uri.php) and i am getting the error: Fatal error: Call to a member function get_segment() on a non-object in /home/eeeee/public_html/private/funkyphp/funk/core/core.php on line 11 (the if($this->uri->get_segment(1) part)
I'm having this problem a lot and it is really bugging me.
the library code is:
<?php
class uri
{
private $server_path_info = '';
private $segment = array();
private $segments = 0;
public function __construct()
{
$segment_temp = array();
$this->server_path_info = preg_replace("/\?/", "", $_SERVER["PATH_INFO"]);
$segment_temp = explode("/", $this->server_path_info);
foreach ($segment_temp as $key => $seg)
{
if (!preg_match("/([a-zA-Z0-9\.\_\-]+)/", $seg) || empty($seg)) unset($segment_temp[$key]);
}
foreach ($segment_temp as $k => $value)
{
$this->segment[] = $value;
}
unset($segment_temp);
$this->segments = count($this->segment);
}
public function segment_exists($id = 0)
{
$id = (int)$id;
if (isset($this->segment[$id])) return true;
else return false;
}
public function get_segment($id = 0)
{
$id--;
$id = (int)$id;
if ($this->segment_exists($id) === true) return $this->segment[$id];
else return false;
}
}
?>
your calls to get_segment() are inconsistent.
In one case you call $this->uri->get_segment(), which is correct according to your previous code. The second time you call $uri->get_segment, which is missing the $this-> and so is not a valid object.

wordpress-like model to view api event system (MVC)

Wordpress has a nice api system. I'm struggling in creating an equal flexible one using a more traditional MVC interpretation. A typical view class could be like this:
class View
{
public function set($name, $value)
{
$this->data[$name] = $value
}
public function __get($name) ... you know how it works
}
A use case would be a controller adding an order contain order lines:
$view->add('order', $orderModel);
Then the template file could have something like
foreach ($this->order->getOrderLines() as $orderLine)
{
?><div><?php echo $orderLine->getItemName(); ?><div><?php
}
At least this is what is commonly seen in many PHP MVC frameworks. I'm open to alternative implementations that solve the question:
How to add an event system like wordpress has? Eg a filter OrderLineItemName.
Okay,
I am not 100% exactly what you want to do, but I have an idea.
Maybe you mean something like this:
class View {
public $hooks = array('getsomeVar');
public $hooks_functions = array();
public $attributes = array();
public function __set($k,$v) {
$this->attributes[$k] = $v;
}
public function __get($k) {
if (isset($this->attributes[$k])){
$hooks = $this->get_functions_by_hook('get' . $k);
if (!empty($hooks)){
foreach ($hooks as $klass=>$methods) {
if (class_exists($klass)){
$class = new $klass();
foreach ($methods as $method) {
if (method_exists($class,$method)){
$this->attributes[$k] = $class->$method($this->attributes[$k]);
}
}
}
}
}
return $this->attributes[$k];
} else {
throw new Exception($k . " is not a view variable");
}
}
public function register_filter($name,$class,$method) {
if (in_array($name,$this->hooks)){
$this->hooks_functions[$name][$class][] = $method;
} else {
throw new Exception($name . ' is not a valid hook');
}
}
public function get_functions_by_hook($name) {
if (array_key_exists($name,$this->hooks_functions)){
return $this->hooks_functions[$name];
}
return array();
}
}
class MyPlugin {
public function fix_string($str) {
return str_replace("ruby",'php',$str);
}
}
$v = new View();
$v->someVar = 'ruby is great';
$v->register_filter('getsomeVar','MyPlugin','fix_string');
echo $v->someVar;
or you can use this method, which is more event like. Again sample code, but you should be able to cannabalize it.
class EventDispatcher {
public static $listeners = array();
public static function registerListener(&$instance) {
if (!in_array($isntance,self::$listeners)){
array_push(self::$listeners,$instance);
}
}
public static function dispatchEvent($name,&$value) {
foreach (self::$listeners as $listener) {
if (method_exists($listener,'interests')){
$funcs = $listener->interests();
if (array_key_exists($name,$funcs)){
foreach ($funcs as $f) {
$value = $listener->$f($value);
}
}
}
}
}
}
class Plugin {
public static function registerPlugin($class_name) {
if (class_exists($class_name)){
EventDispatcher::registerListener(new $class_name());
}
}
}
class Model {
public function __construct() {
EventDispatcher::registerListener($this);
}
public function special($value) {
echo "I got called too!\n\n";
return $value;
}
public function interests() {
return array(
"getsomeVar" => "special",
);
}
}
class View {
public $attributes = array();
public function __set($k,$v) {
$this->attributes[$k] = $v;
}
public function __get($k) {
if (isset($this->attributes[$k])){
EventDispatcher::dispatchEvent('get' . $k,$this->attributes[$k]);
return $this->attributes[$k];
} else {
throw new Exception($k . " is not a view variable");
}
}
}
class MyPlugin {
public function fix_string($str) {
return str_replace("ruby",'php',$str);
}
public function interests() {
return array(
"getsomeVar" => "fix_string",
);
}
}
Plugin::registerPlugin('MyPlugin');
$model = new Model();
$v = new View();
$v->someVar = 'ruby is great';
echo $v->someVar;
This is just some sample code, I don't do it this way at all, but it seems like it may be what you are talking about.
Cheers,
Jason
Addendum:
Most of this stuff is about the WP codebase.
WP accesses variables set in the global scope that are modified like so:
function add_filter($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
global $wp_filter, $merged_filters;
$idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority);
$wp_filter[$tag][$priority][$idx] = array('function' => $function_to_add, 'accepted_args' => $accepted_args);
unset( $merged_filters[ $tag ] );
return true;
}
It has some other functions like, has_filter etc...
function apply_filters($tag, $value) {
global $wp_filter, $merged_filters, $wp_current_filter;
$args = array();
$wp_current_filter[] = $tag;
// Do 'all' actions first
if ( isset($wp_filter['all']) ) {
$args = func_get_args();
_wp_call_all_hook($args);
}
if ( !isset($wp_filter[$tag]) ) {
array_pop($wp_current_filter);
return $value;
}
// Sort
if ( !isset( $merged_filters[ $tag ] ) ) {
ksort($wp_filter[$tag]);
$merged_filters[ $tag ] = true;
}
reset( $wp_filter[ $tag ] );
if ( empty($args) )
$args = func_get_args();
do {
foreach( (array) current($wp_filter[$tag]) as $the_ )
if ( !is_null($the_['function']) ){
$args[1] = $value;
$value = call_user_func_array($the_['function'], array_slice($args, 1, (int) $the_['accepted_args']));
}
} while ( next($wp_filter[$tag]) !== false );
array_pop( $wp_current_filter );
return $value;
}
This is not an event driven system, it's a method lookup table which is just a giant hash that looks up the user defined functions to call.
apply_filters, and all plugin like functions are called procedurally as the code is rendered, here is an example
if ( $prefixed ) {
$value = apply_filters("pre_$field", $value);
$value = apply_filters("${field_no_prefix}_save_pre", $value);
} else {
$value = apply_filters("pre_post_$field", $value);
$value = apply_filters("${field}_pre", $value);
}
Or for actions, in an actual template view like so:
<p class="submit"><input type="submit" class="button" name="submit" value="<?php esc_attr_e('Add Category'); ?>" /></p>
<?php do_action('edit_link_category_form', $category); ?>
</form>

Categories