So basically I want to have an Object Class with a bunch of setters that I can manipulate and then convert straight to JSON. In the past I was using an already existing JSON as model(json->object->json). Now I want to just have object->json.
But at the moment I get an empty array when I try to use json_encode.
Also had some trouble with my $index that I'm using because I can have multiple numerical indexes inside "items"
PHP:
<?php
namespace ProjectApi\Models;
use ArrayObject;
use stdClass;
class MagentoInvoice
{
public $capture = true;
public $notify = true;
public function __construct()
{
}
public function setCapture($capture)
{
$this->capture = $capture;
}
public function getCapture()
{
return $this->capture;
}
public function setNotify($notify)
{
$this->notify = $notify;
}
public function getNotify()
{
return $this->notify;
}
public function setItems($itemsCount)
{
$i = 0;
while($i < $itemsCount)
{
$this->items = new stdClass();
$i++;
}
}
public function getItems()
{
return $this->items;
}
public function setProductQty($index, $qty)
{
$this->items->$index->qty = $qty;
}
public function getProductQty($index)
{
return $this->items->$index->qty;
}
public function setProductOrderItemId($index, $id)
{
$this->items->$index->order_item_id = $id;
}
public function getProductOrderItemId($index)
{
return $this->items->$index->order_item_id;
}
}
JSON
{"capture":true,"items":[{"order_item_id":123,"qty":1},{"order_item_id":321,"qty":1}],"notify":true}
$body = new MagentoInvoice();
$body->setCapture(true);
$body->setNotify(true);
if($firstProductId != null && $secondProductId != null)
{
$body->setItems(2);
$body->setProductQty(0, 1);
$body->setProductOrderItemId(0, $firstProductId);
$body->setProductQty(1, 1);
$body->setProductOrderItemId(1, $secondProductId);
}
print_r(json_encode($body));
Related
I have this class,
class Player {
protected static $volume;
protected static $instance = null;
protected function __construct()
{
self::$volume = 5;
$this->maxVolume = 20;
}
protected function __clone() {}
public static function getInstance() {
if (!isset(static::$instance)) {
static::$instance = new static;
}
return static::$instance;
}
public function volumeUp() {
if (self::$volume < $this->maxVolume) {
self::$volume = self::$volume + 1;
}
return static::$volume;
}
public function volumeDown () {
if (self::$volume > 0) {
self::$volume = self::$volume - 1;
}
return static::$volume;
}
}
I wanted to change object values dynamically by calling the method volumeUp or volumeDown.
$player = \Player\Player::getInstance();
if (isset($data['volume']) && isset($data['down'])) {
echo $player->volumeDown();
}
if (isset($data['volume']) && isset($data['up'])) {
echo $player->volumeUp();
}
When I call those methods object act like new instance and gives me always the same result.
Where I make wrong move?
getclass.php
public $set;
//dont need to care here the code is right , here is where it final result
default;
$this->actual_device = "desktop";
echo $this->issetValueNull($this->actual_device);
public function issetValueNull($mixed)
{
$this->set = $mixed;
}
getdata.php
require_once "getclass.php";
$check_detect_device = new detect_device();
if($check_detect_device->issetValueNull->set1 = "desktop"){
"<script>console.log('desktop');</script>";
}
i need to get the data from getclass.php to getdata.php and check the final result at getdata.php , some like below;
//this data return from getclass.php
if(isset($_GET['desktop'])){
"<script>console.log('desktop');</script>";
}
but i dont know how to return the data from getclass , can any one give me some advice ?
Im not sure is this what you are trying to do, but check my example:
<?php
class getClass
{
public $actualDevice;
public function __construct()
{
$this->actualDevice = "desktop";
}
public function setActualDevice($actualDevice)
{
$this->actualDevice = $actualDevice;
return $this;
}
public function getActualDevice()
{
return $this->actualDevice;
}
public function issetActualDevice()
{
return isset($this->actualDevice);
}
}
class getData
{
public $getClass;
public function __construct(getClass $getClass)
{
$this->getClass = $getClass;
}
public function checkDetectDevice($device)
{
if ($this->getClass->getActualDevice() == $device) {
return true;
}
return false;
}
}
$getClass = new getClass();
$getData = new getData($getClass);
if ($getData->checkDetectDevice($_GET['desktop'])) {
echo "<script>console.log('desktop');</script>";
}
I have currently two classes.
the ArrayCompare class:
<?php
namespace App\Tools\RegexExtract;
class ArrayCompare
{
public function compare(Array $arrayToCompare)
{
$elementData = new ElementMetaData();
$metaData = $elementData->extract($arrayToCompare[0], [], $initial=true);
foreach ($arrayToCompare as $currentElement) {
$metaData = $elementData->extract($currentElement, $metaData);
}
return $metaData;
}
}
which uses the ElementMetaData class
<?php
/**
* A class for extracting meta data from an element.
*/
namespace App\Tools\RegexExtract;
class ElementMetaData
{
public function extract($element, $metaDataToCompare = [], $initial = false)
{
if ($initial == true) {
$this->isInteger($element) ? $returnMetaData['isInteger'] = $this->isInteger($element) : null;
$returnMetaData['length'] = $this->length($element);
}
else {
$returnMetaData=$metaDataToCompare;
if ($returnMetaData != []) {
if (isset ($returnMetaData['isInteger']) && !$this->isInteger($element)) {
unset($returnMetaData['isInteger']);
}
if (isset ($returnMetaData['length']) && $this->length($element) != $returnMetaData['length']) {
unset($returnMetaData['length']);
}
}
}
return $returnMetaData;
}
private function isInteger($element)
{
return is_int($element);
}
private function length($element)
{
return strlen($element);
}
}
the basic functionality is:
given I have an array
$arr=[1,2,3];
I want to get the "similarities" between ALL Elements. According to a an array i Predefine...so this would deliver this result:
$metaArray=['isInteger'=>true,'length'=>1];
and this would deliver just length as similarity:
$arr=[1,2,'D'];
$metaArray=['length'=>1];
While this array would deliver an empty result []
$arr=[1,2,'3D']; // result is [] since not all integers or not all of same length.
Now my solution does not use recursive functions...but I am sure it can be used somehow.
Also, I want to add more "criteria"....So "isEmailAdress", "beginswithA"....etc....and this would make my if statements a horror....so what is the best strategy/design pattern to follow here?
#deceze beat me to it by fair margin... but I'll still post my solution that works basically with the same principles.
abstract class abstractComparer
{
private $array;
private $result = true;
protected $name;
public function compareArray($array)
{
$current = null;
foreach ($array as $index => $value)
{
$this->result = $this->result && $this->compareValues($index, $current, $value);
$current = $value;
}
}
public function getResult()
{
return $this->result;
}
public function getName()
{
return $this->name;
}
public abstract function compareValues($index, $value1, $value2);
public abstract function getSuccessValue();
}
class intComparer extends abstractComparer
{
protected $name = "isInteger";
public function compareValues($index, $value1, $value2)
{
return is_int($value2);
}
public function getSuccessValue()
{
return true;
}
}
class lengthComparer extends abstractComparer
{
protected $name = "length";
protected $length = 0;
public function compareValues($index, $value1, $value2)
{
$this->length = strlen($value2);
return $index == 0 || strlen($value1) == $this->length;
}
public function getSuccessValue()
{
return $this->length;
}
}
And do the actual processing like this:
$temp = [1,2,3];
$comparers = [new intComparer(), new lengthComparer()];
$result = array();
foreach ($comparers as $comparer)
{
$comparer->compareArray($temp);
if ($comparer->getResult())
{
$result[$comparer->getName()] = $comparer->getSuccessValue();
}
}
//var_dump($result);
I don't see any need for recursion here, so I'll just make a suggestion for a design approach:
Implement each criterion as a class:
abstract class Criterion {
protected $valid = true;
abstract public function initialize($value);
abstract public function check($value);
public function isValid() {
return $this->valid;
}
}
class Length extends Criterion {
protected $length;
public function initialize($value) {
$this->length = strlen($value);
}
public function check($value) {
if ($this->length != strlen($value)) {
$this->valid = false;
}
}
}
You then make an array of all your criteria:
$criteria = [new Length, ...];
foreach ($criteria as $criterion) {
$criterion->initialize($values[0]);
}
And slowly whittle them down through your values:
foreach ($values as $value) {
foreach ($criteria as $criterion) {
$criterion->check($value);
}
}
$commonCriteria = array_filter($criteria, function (Criterion $criterion) {
return $criterion->isValid();
});
Is there a way to iterate over an object's keys implementing ArrayAccess and Iterator interfaces? Array access works as a charm but I can't use foreach on those objects which would help me a lot. Is it possible? I have such code so far:
<?php
class IteratorTest implements ArrayAccess, Iterator {
private $pointer = 0;
public function offsetExists($index) {
return isset($this->objects[$index]);
}
public function offsetGet($index) {
return $this->objects[$index];
}
public function offsetSet($index, $newValue) {
$this->objects[$index] = $newValue;
}
public function offsetUnset($index) {
unset($this->objects[$index]);
}
public function key() {
return $this->pointer;
}
public function current() {
return $this->objects[$this -> pointer];
}
public function next() {
$this->pointer++;
}
public function rewind() {
$this->pointer = 0;
}
public function seek($position) {
$this->pointer = $position;
}
public function valid() {
return isset($this->objects[$this -> pointer]);
}
}
$it = new IteratorTest();
$it['one'] = 1;
$it['two'] = 2;
foreach ($it as $k => $v) {
echo "$k: $v\n";
}
// expected result:
// one: 1
// two: 2
Thanks for any help and hints.
I use this to implement iterator. Maybe you can adapt to your code ;)
class ModelList implements Iterator{
public $list;
private $index = 0;
public $nb;
public $nbTotal;
/**
* list navigation
*/
public function rewind(){$this->index = 0;}
public function current(){$k = array_keys($this->list);$var = $this->list[$k[$this->index]];return $var;}
public function key(){$k = array_keys($this->list);$var = $k[$this->index];return $var;}
public function next(){$k = array_keys($this->list);if (isset($k[++$this->index])) {$var = $this->list[$k[$this->index]];return $var;} else {return false;}}
public function valid(){$k = array_keys($this->list);$var = isset($k[$this->index]);return $var;}
/**
*
* Constructor
*/
public function __construct() {
$this->list = array();
$this->nb = 0;
$this->nbTotal = 0;
return $this;
}
}
while ($it->valid()) {
echo $it->key().' '.$it->current();
$it->next();
}
Would be my approach, however, this function looks iffy:
public function next() {
$this->pointer++;
}
Incrementing 'one' isn't likely to give you 'two'. Try the code in the answers to this question to get the next array key:
$keys = array_keys($this->objects);
$position = array_search($this->key(), $keys);
if (isset($keys[$position + 1])) {
$this->pointer = $keys[$position + 1];
} else {
$this->pointer = false;
}
class Contact{
public $name;
public $bgcolor;
public $lgcolor;
public $email;
public $element;
public function __construct($name, $bgcolor, $lgcolor, $email, $element)
{
$this->name = $name;
$this->bgcolor = $bgcolor;
$this->lgcolor = $lgcolor;
$this->email = $email;
$this->element = $element;
}
public static function sortByName(Contact $p1, Contact $p2)
{
return strcmp($p1->name, $p2->name);
}
}
class ContactList implements Iterator, ArrayAccess
{
protected $_label;
protected $_contacts = array();
public function __construct($label)
{
$this->_label = $label;
}
public function getLabel()
{
return $this->_label;
}
public function addContact(Contact $contact)
{
$this->_contacts[] = $contact;
}
public function current()
{
return current($this->_contacts);
}
public function key()
{
return key($this->_contacts);
}
public function next()
{
return next($this->_contacts);
}
public function rewind()
{
return reset($this->_contacts);
}
public function valid()
{
return current($this->_contacts);
}
public function offsetGet($offset)
{
return $this->_contacts[$offset];
}
public function offsetSet($offset, $data)
{
if (!$data instanceof Contact)
throw new InvalidArgumentException('Only Contact objects allowed in a ContactList');
if ($offset == '')
{
$this->_contacts[] = $data;
} else
{
$this->_contacts[$offset] = $data;
}
}
public function offsetUnset($offset)
{
unset($this->_contacts[$offset]);
}
public function offsetExists($offset) {
return isset($this->_contacts[$offset]);
}
public function sort($attribute = 'name')
{
$sortFct = 'sortBy' . ucfirst(strtolower($attribute));
if (!in_array($sortFct, get_class_methods('Contact')))
{
throw new Exception('contact->sort(): Can\'t sort by ' . $attribute);
}
usort($this->contact, 'ContactList::' . $sortFct);
}
}
public function Sort($property, $asc=true)
{
// this is where sorting logic takes place
$_pd = $this->_contact->getProperty($property);
if ($_pd == null)
{
user_error('Property '.$property.' does not exist in class '.$this->_contact->getName(), E_WARNING);
return;
}
// set sortDescriptor
ContactList::$sortProperty = $_pd;
// and apply sorting
usort($this->_array, array('ContactList', ($asc?'USortAsc':'USortDesc')));
}
function getItems(){
return $this->_array;
}
class SortableItem extends ContactList
{
static public $sortProperty;
static function USortAsc($a, $b)
{
/*#var $_pd ReflectionProperty*/
/*
$_pd = self::$sortProperty;
if ($_pd !== null)
{
if ($_pd->getValue($a) === $_pd->getValue($b))
return 0;
else
return (($_pd->getValue($a) < $_pd->getValue($b))?-1:1);
}
return 0;
}
static function USortDesc($a, $b)
{
return -(self::USortAsc($a,$b));
}
}
This approach keeps giving me PHP Warnings: usort() [function.usort]: of all kinds which I can provide later as needed to comment out those methods and definitions in order to test and fix some minor bugs of our program.
**$billy parameters are already defined.
$all -> addContact($billy);
// --> ended up adding each contact manually above
$all->Sort('name',true);
$items = $all->getItems();
foreach($items as $contact)
{
echo $contact->__toString();
}
$all->sort();
The reason for using usort is to re-arrange the order alphabetically by name but somehow is either stating that the function comparison needs to be an array or another errors which obviously I have seemed to pass. Any help would be greatly appreciated, thanks in advance.
It's happening because the variable inside the usort call is not a valid array. You use $this->_contacts everywhere, but your usort line is:
usort($this->contact, 'ContactList::' . $sortFct);
Try changing that to:
usort($this->_contacts, 'ContactList::' . $sortFct);
<?php
class Contact{
public $name;
public $bgcolor;
public $lgcolor;
public $email;
public $element;
public function __construct($name, $bgcolor, $lgcolor, $email, $element)
{
$this->name = $name;
$this->bgcolor = $bgcolor;
$this->lgcolor = $lgcolor;
$this->email = $email;
$this->element = $element;
}
}
class ContactList implements Iterator, ArrayAccess
{
public $_label;
public $_contacts = array();
public function __construct($label)
{
$this->_label = $label;
}
public function getLabel()
{
return $this->_label;
}
public function addContact(Contact $contact)
{
$this->_contacts[] = $contact;
}
public function current()
{
return current($this->_contacts);
}
public function key()
{
return key($this->_contacts);
}
public function next()
{
return next($this->_contacts);
}
public function rewind()
{
return reset($this->_contacts);
}
public function valid()
{
return current($this->_contacts);
}
public function offsetGet($offset)
{
return $this->_contacts[$offset];
}
public function offsetSet($offset, $data)
{
if (!$data instanceof Contact)
throw new InvalidArgumentException('Only Contact objects allowed in a ContactList');
if ($offset == '')
{
$this->_contacts[] = $data;
} else
{
$this->_contacts[$offset] = $data;
}
}
public function offsetUnset($offset)
{
unset($this->_contacts[$offset]);
}
public function offsetExists($offset) {
return isset($this->_contacts[$offset]);
}
/* This is the comparing function to be used with usort to make it alphabetically ordered for All Contacts */
public function sort_by($field, &$arr, $sorting='SORT_DSC', $case_insensitive=true){
if(is_array($arr) && (count($arr)>0) && ( ( is_array($arr[0]) && isset($arr[0][$field]) ) || ( is_object($arr[0]) && isset($arr[0]->$field) ) ) ){
if($case_insensitive==true) $strcmp_fn = "strnatcasecmp";
else $strcmp_fn = "strnatcmp";
if($sorting=='SORT_DSC'){
$fn = create_function('$a,$b', '
if(is_object($a) && is_object($b)){
return '.$strcmp_fn.'($a->'.$field.', $b->'.$field.');
}else if(is_array($a) && is_array($b)){
return '.$strcmp_fn.'($a["'.$field.'"], $b["'.$field.'"]);
}else return 0;
');
}else if($sorting=='SORT_ASC'){
$fn = create_function('$a,$b', '
if(is_object($a) && is_object($b)){
return '.$strcmp_fn.'($b->'.$field.', $a->'.$field.');
}else if(is_array($a) && is_array($b)){
return '.$strcmp_fn.'($b["'.$field.'"], $a["'.$field.'"]);
}else return 0;
');
}
usort($arr, $fn);
return true;
}else{
return false;
}
}
}
?
The call:
$all->sort_by('name',$all->_contacts,'SORT_DSC','false');