PHP - Converting Collection Of Objects To Json
I can obtain either one or a collection of objects by executing the following. $product = $entityManager->find('Product', $id); $products = $entityManager->getRepository('Product')->findAll(); All products have many common properties, however, based on the type of product there are some differences. To implement this, I am using class table inheritance (side question - is there any difference between CTI and supertype/subtype modeling?). I will need to convert either a single product to JSON as well as a collection of products to JSON. When converting a collection, only a subset of the product's properties is desired, however, again most of these properties are common to each product type but there are some differences. One solution is to utilize the JsonSerializable interface. A shortcoming, however, is how to deal with both the detail view with all the properties and the collection view with only a subset of properties. To overcome this, I can potentially use jsonSerialize() to provide the detail view, and add another function index() to provide the subset results for the collection. Since this index() function will not recursively incorporate sub-objects, I will need to manually loop over the collection, however, it should not be too big of issue. Or should the entity not be responsible to convert to JSON? I am kind of mixed on this issue, but do agree using a separate class has merit. So, if a separate class is used, how does it deal with each subclass of Product which might have unique properties and getters? I suppose I can have the entities implement an interface which requires them to return their applicable properties, but doing so isn't very flexible and isn't this (almost) the same as having the entity responsible to provide the JSON? I "could" make this other class perform some switch operation based on the class name, but doing so goes against all good OOP principles. What is the "right" way to do this? Thanks Similar TutorialsHi, I have a problem with some code not working. I need it to get the data from a mysql database and then export it as a json array in the format of id , title, author, date, imageUrl, text. (Please not that these are all variables ) PHP CODE: Code: [Select] <?php $link = mysql_connect('localhost', 'root', ''); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; $arr = array(); $rs = ("SELECT `id`, `title`, `author`, `date`, `imageUrl`, `text` FROM `items`"); while($obj = mysql_query($rs)) { $arr[0] = $obj->id; $arr[1] = $obj->title; $arr[2] = $obj->author; $arr[3] = $obj->date; $arr[4] = $obj->imageUrl; $arr[5] = $obj->text; } echo '{"items":'.json_encode($arr).'}'; ?> Thanks For Your Help borden0108 Hello all!
I have this array of objects:
Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => p@yahoo.com [date] => 2014-09-20 07:39:55 [status] => 2 [approval_date] => 2014-09-20 07:40:41 [assessment_id] => 3 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-20 07:41:07 [mainmanger] => 3 ) [2] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )Where "id" = the user ID. If there are two or more entries for a user, I want to remove all but the most recent by the "approval_date",... So for the above example it would return: Array ( [0] => stdClass Object ( [first_name] => test [last_name] => test [title] => test [id] => 34 [type] => 4 [manager] => 4 [email] => piznac@yahoo.com [date] => 2014-09-21 07:23:12 [status] => 2 [approval_date] => 2014-09-21 07:31:10 [assessment_id] => 1 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-21 07:31:27 [mainmanger] => 3 ) [1] => stdClass Object ( [first_name] => jimmy john john [last_name] => john [title] => Lorad and Master [id] => 32 [type] => 4 [manager] => 3 [email] => j@j.com [date] => 2014-09-21 07:38:50 [status] => 2 [approval_date] => 2014-09-19 07:39:25 [assessment_id] => 2 [supervisor_approval] => 1 [manager_approval_date] => 2014-09-19 07:39:25 [mainmanger] => 0 ) )I'm having a hard time wrapping my head around this concept, so I don't have any example code. And I don't really need or expect someone to code this for me,. just a push in the right direction would be awesome. hi, i would like to find out if anyone has any examples of code for a collection class(alternative to array) thanks I have a basic form for collecting data, I have a function for collecting the ip address of the visitors unfortunately I cannot get the ip collection working with the rest of the form once I put the if($_POST['emailaddress']) {.........} in. My aim is once the user has completed the form, data gone to MySQL database that the data will then be printed via the echo statements on to the form as the action sends it back to the same page. Currently my code is <?php /* This script is a form handler, each section is commented as to what it does. 1. connects to the database (see connect.php). 2. it gets the users ip address. 3. Strips tags from the data entered so that no malicious code can be entered and corrupt/cause problems with the database or site. 4. Inserts the relevant data into the database in this case it is the ip, haveemail, emailaddress, browser, otherbrowser, resolution, otherresolution. 5. Sends the data just entered by the user back to the screen so they can see what they entered */ // 1. connection to MySQL require ("php/connect.php"); // if this script is unavailable then the rest of the code is pointless as need a connection to the database. // if fields are completed if($_POST['emailaddress']) { // if this field has had data entered then process the data // 2. collect ip address //$ip = getRealIpAddr(); // 3. Strips tags and POST variables from the form $haveemail = strip_tags($_POST['haveemail']); $emailaddress = strip_tags($_POST['emailaddress']); $browser = strip_tags($_POST['browser']); $otherbrowser = strip_tags($_POST['otherbrowser']); $resolution = strip_tags($_POST['resolution']); $otherresolution = strip_tags($_POST['otherresolution']); // 4. insert data to dbase $query="INSERT INTO datacollection1 (id, ip, haveemail, emailaddress, browser, otherbrowser, resolution, otherresolution) VALUES ('Null', '$ip', '$haveemail', '$emailaddress', '$browser', '$otherbrowser', '$resolution', '$otherresolution')"; // Null is in the id field as this is added automatically in the database as it is set to auto increment upon an entry going in and is primary key. // message to say if database has been updated mysql_query($query) or die (mysql_error()); //echo "<b>Your IP address is: $ip</b> <br />"; /*function getRealIpAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip=$_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; } */ // 5. displays information on form to advise what the user just entered echo '<br/>'."The database has just been updated with the following information: ".'<br/><br/>'; // echo "Your ip address is ".$ip.'<br/>'; echo "You answered ".$haveemail." to having an email address.".'<br/>'; echo "Your email address is ".$emailaddress.'<br/>'; echo "You use ".$browser." to browse the internet".'<br/>'; echo $otherbrowser.'<br/>'; echo "Your screen resolution is set at ".$resolution.'<br/>'; echo $otherresolution.'<br/>'; echo "Now you have completed this form, please follow onto the main form, this form seeks to get your valuable opinion regarding your likes and dislikes of the websites researched."; } mysql_close($db); // closes the database, this is good practice but the database will close once stopped running. ?> I have tried moving the function outside of the if($_POST['emailaddress']) but it still didnt get the ip address. Just as a side note everything else works, the data is written into the database bar the ip address. I would appreciate some help Thanks in advance. Anyone know why the following results in an error? Not a big deal as memory is not an issue and I can (and have) just changed it to create a new array instead of using a generator, but still curious. Thanks <?php foreach($doctrineCollection as $doctrineEntity){ yield new MyWrapper($doctrineEntity); /* After around 4 iterations, results in the following error: syslog Apr 06 15:25:25 myserver.net kernel: php-fpm[42889]: segfault at 7f8156a14100 ip 000055bb1d79acfd sp 00007ffd0b50a968 error 4 in php-fpm[55bb1d47c000+46e000] /var/log/php-fpm/error.log [Mon Apr 06 20:06:38.781360 2020] [proxy_fcgi:error] [pid 1501:tid 140210423629568] (104)Connection reset by peer: [client 12.345.67.890:45574] AH01075: Error dispatching request to : /var/log/httpd/error_log [06-Apr-2020 20:04:52] WARNING: [pool michael] child 5524 exited on signal 11 (SIGSEGV) after 0.138268 seconds from start [06-Apr-2020 20:04:52] NOTICE: [pool michael] child 5526 started */ } class MyWrapper { private $doctrineEntity; public function __construct($doctrineEntity) { $this->doctrineEntity=$doctrineEntity; } }
I have the following three tables (and also delta_point and hist_point which are purposely left out and just mentioned for context). Before going down the Doctrine ORM long curvy road, aggrType was just used to restrict possible values so that I didn't need to use MySQL's ENUM, but now I am thinking there may be value to making it an entity and include some methods (and a second reason because I still can't figure out how to make Doctrine create a FK constraint yet not populate the parent entity with a AggrType object). point -id (int PK) -data -dType /* descriminator. Options are AggregatePoint, DeltaPoint, and HistoricPoint */ aggr_point -id (int PK, FK to point) -aggrType (char FK to aggrType) -data aggrType -type (char PK) /* there are about five types */ I have a service to create a new point based on the provided desired type and user data. I don't like the switch statement to determine which type of point to create, but don't know a better way. Also my entity is responsible to provide the appropriate validation rules for the given point type which might not be considered proper but it seems to work for me. Any constructive criticism is welcomed. <?php namespace NotionCommotion\PointMapper\Api\Point; use NotionCommotion\PointMapper\Domain\Entity\Point; class PointService { public function create(string $type, array $params):integer { $class=[ 'aggr'=>'AggregatePoint', 'delta'=>'DeltaPoint', 'hist'=>'HistoricPoint', ][$type]; //$class='Point\\'.$class; //This doesn't seem to be possible and I needed to use the fully qualifed name without the short cut used namespace. $class='\\Greenbean\Datalogger\Domain\Entity\Point\\'.$class; $point=new $class(); $validator=$this->getValidator($point); $params=$validator->sanitize($params); $validator->validate($params); $point->setAccount($this->account); $point->populate($params, $this->em); //Will be addressed later $this->em->persist($point); $this->em->flush(); $point->setIdPublic($this->em->getRepository(Point\Point::class)->getPublicId($point->getId())); return $point->getIdPublic(); } } Now, this is the part I am struggling with the most. I only have one service to create any type of point, so I do wish to put a bunch of if/thens in it and instead move logic to the individual point type being created. The AggrPoint in question requires a sub-point and I don't think it is appropriate to inject the entity manager into a point entity and as an alternative solution find an existing point which is associated with the account which resides in the new AggrPoint. Maybe not appropriate, but it works. This type of point also has a sub-object AggrType as discussed at the very beginning of this post, so I first attempt to create a new one from scratch, but that doesn't work and I need to set $aggrType with an existing one. As an alternative, I passed the entity the entity manager, but as stated I think this is a bad idea. Any recommendations where to go from here? Thank you namespace NotionCommotion\PointMapper\Domain\Entity\Point; class AggregatePoint extends Point { public function populate(array $params, \Doctrine\ORM\EntityManager $em):\NotionCommotion\PointMapper\Domain\Entity\Entity{ $criteria = \Doctrine\Common\Collections\Criteria::create() ->where(\Doctrine\Common\Collections\Criteria::expr()->eq("id_public", $params['pointId'])); if(!$subpoint = $this->getAccount()->getPoints()->matching($criteria)->current()){ throw new \Exception("Invalid subpoint ID $params[pointId]"); } $this->setSubpoint($subpoint); //This won't work since I must use an existing AggregateType and not create a new one $aggrType=new AggregateType(); $aggrType->setType($params['aggrType']); //This just seems wrong and I shouldn't be passing the entity manager to an entity $aggrType=$em->getRepository(AggregateType::class)->findOneBy(['type'=>$params['aggrType']]); $this->setAggregateType($aggrType); unset($params['pointId'], $params['aggrType']); // parent::populate($params) not shown, but it basically calles appropriate setters based on the property name return parent::populate($params); } public function getValidatorRules():array { return $this->filesToArr(['/point/base.json', '/point/aggr.json']); } }
Hi I am new to PHP and I need to create an array and add both books to the array and than loop through the array this is where I am having trouble if the price of a book is less than $20.00 output the book’s name and price if the book’s title comes after the letter R in the alphabet output the book’s title. I am getting these error:
Notice: Trying to get property 'price' of non-object in C:\xampp\htdocs\PHP objects\books.php on line 45 My code is:
<?php
// Methods
$first_book = new Book();
foreach ($book as $bookItem) { Any help will be very much appreciated Thank you In a relational database, you "link" tables together. For example, Customer (parent) ---> Product (child) How do you do that with Objects? I have a "User" class and an "AddressBook" class. A User can have zero or more Addresses (in their AddressBook). If I create a User object and an AddressBook object, I need a way to link them up similar to how they are linked up in the database. Make sense?! TomTees I took an object, and saved it into a database serialized. Code: [Select] $object_here = serialize($theobject); Then later on, I go and I get that data from a database, and try to unserialize it.. Code: [Select] $objecthere = unserialize($row->theobject) And it throws the following error...any advice? Quote Warning: unserialize() [function.unserialize]: Node no longer exists in /path/to/file on line 20 I found it helpful to configure all my objects in one or several bootstrap scripts. Before doing so, I would often find myself forgetting that I already had written some class which is located deep in some script and recreating it for some other need (granted, composer definitely helped in this regard, but using it wasn't always applicable). <?php $c=new Pimple\Container(getMySettings()); $c['pdo'] = function ($c) { $db = $c['settings']['mysql']; return new \PDO(bla); }; $c['foo'] = function ($c) { return new Foo( $c->get('pdo') ); }; $c['bar'] = function ($c) { return new Bar( $c->get('foo') ); }; It is all good until I find myself needing to create some new instance of some class instead of just passing some common instance to whoever needs it. class Foo { private $pdo; public function __construct(\PDO $pdo) { $this->pdo=$pdo; } public function getSomething():SomeClass { return new SomeClass($this->getAllDataFromDB($GET['id'])); } } class SomeClass { private $arr; public function __construct(array $records) { foreach($records as $record) { $arr[]=new SomeOtherClass($record); } } } I've read that one shouldn't create new objects in a given class's constructor, and while I could instead do so in some class's method and pass the object to the given class's constructor, to me it seems to really be the same thing. The three issues I have with this scenario a Needing to remember that these classes exist as they are hidden deep in some classes. Makes it more difficult to replace one of the classes with some other class in the future. Some duplication of code.Are there other compelling reasons not to do so? Is it worth the effort to do differently? If so, how would you recommend doing so? My thoughts would either to use Pimple's factory() method are create my only factory which also relies on anonymous functions. Maybe something else? $c['someClass'] = $c->factory(function (array $record, Container $c) { return new SomeClass($record); }); Thanks I know it is often frivolous, but sometimes I can't help trying to optimize things, and use the following two methods to create either an object injected with a string or one of a set of objects. For both cases, the class has no setters so there is no chance that the object will later be changed. I first stated doing this in continuously running server applications which I believe makes sense, however, it has leaked over to standard HTTP requests. Please commit good or bad on this approach. Thanks
public static function create(string $unit):self { static $stack=[]; if(!isset($stack[$unit])) { $stack[$unit] = new self($unit); } return $stack[$unit]; } public static function create(string $class):FunctionInterface { static $stack=[]; if(!isset($stack[$class])) { $stack[$class] = new $class; } return $stack[$class]; }
Hi all,
I am working with the following 2 page script: https://github.com/k...hi/php-riot-api. All works well and the data is pulled via the API as intended. However, depending on the data I'm trying to display on screen, the object contains multiple values.
For example:
$r = $test->getSummoner($summoner_id,'name'); print_r($r);outputs their ID and name: {"585897":"TheirName"} Just as the following: $r = $test->getSummonerByName($summoner_name); print_r($r);outputs username, ID, Name, profile icon ID, level, and timestamp: {"theirname":{"id":585897,"name":"TheirName","profileIconId":642,"summonerLevel":30,"revisionDate":1405652924000}} Depending on which function I am calling (on example.php), I would like to be able to split the values so I can echo them throughout a page: Name: <value> ID: <value> Level: <value> etc... Any guidance would be appreciated. Ever since I started using OOP this past week, I have not been able to go back to the old "procedural" methods. HOwever, I seem to be stuck on creating a mysql connection that I can reuse in all of my classes. After I set up a connection to mysql using the mysqli object, I am unable to use the mysqli in other objects. Code: [Select] $mysqli = new mysqli(.....); class new_class { function quickQuery () { $mysqli->query('some query') } } Obviously, this doesn't work, because $mysqli is not defined within that functions scope. One way, is to use global keyword. Code: [Select] global $mysqli However, globals "are the root of all evil" and simply go against the idea of encapsulation in OOP. What's a way around this? HOWEVER: 1) I still want to use the mysqli object 2) I don't want to reference the $link of the db each time I instantiate a new class .... Maybe I'm asking too much? And I've google for the past hour or so. Singleton seems interesting but it requires the creation of a new db connection class. I want to use the mysqli object. Hi all,
I was just wondering is this possible what I'm trying to do?
Models can only store one object at a time...
I'm trying to access multiple objects via one model...
<?php class users extends Model { protected $username; protected $firstname; protected $secondname; protected $age; // There will be more here... public function __construct($id = NULL) { if($id != NULL) { $this->username = $sql->getUsername($id); $this->firstname = $sql->getFirstname($id); $this->secondname = $sql->getSecondname($id); $this->age = $sql->getAge($id); } } public function numOfUsers() { $num = $sql->countAllUsers($query); return $num; } public function getUsername() { return $this->username; } public function getFirstname() { return $this->firstname; } public function getSecondname() { return $this->secondname; } public function getAge() { return $this->age; } }; class UsersView extends View { $users = new users(); for($i = 0; $i < $users->numOfUsers(); $i++) { $user = new users($i); echo "Username: {$user->getUsername()}"; echo "Username: {$user->getFirstname()}"; echo "Username: {$user->getSecondname()}"; echo "Username: {$user->getAge()}"; } }; ?> Hello, Can anyone help me with this. To put it simply. Class foo { protected $bar = new Moo(); How can i use this object (And it's methods) inside the methods of that class. So function whatNot (){ $this->bar->Doesn't work. } } I hope you can get my general meaning. What is the better way, in terms of best practice and also speed of storing PHP objects in a database? Is it: Serialize Code: [Select] $SQL = "INSERT INTO my_table (my_object) VALUES ('" . seralize($php_object). "')"; OR JSON Code: [Select] $SQL = "INSERT INTO my_table (my_object) VALUES ('" . json_encode($php_object). "')"; Any idea which is faster serialize() / unserialize() or json_ecode() / json_decode()? I have a function that receives two datetime values attached to the variables $start and $end. These will be in the format 'Y-m-d H:i:s'. For each of these values, I create a DateTime object to make the handling of them easier: Code: [Select] $startDT = DateTime::createFromFormat('Y-m-d H:i:s', $start); $endDT = DateTime::createFromFormat('Y-m-d H:i:s', $end); What I need to do now is ensure that the seconds of the $startDT value are always set to '00' and the seconds of the $endDT value are always set to '59'. Is there an easy way to do this without having to extract the individual values for hours, minutes and seconds before reapplying them using the setTime function, adjusting the values accordingly? I was told that using a Session will allow me to capture an Object and pass it between pages. I tried following what I read online and what someone sugegsted but it is not working. This is the error I get when running my test application... Quote Catchable fatal error: Argument 1 passed to Microwave::receiveItem() must be an instance of Bowl, instance of __PHP_Incomplete_Class given, called in /Users/user1/Documents/DEV/++htdocs/Soup/cook.php on line 13 and defined in /Users/user1/Documents/DEV/++htdocs/Soup/classes/Soup.class.php on line 31 Call Stack # Time Memory Function Location 1 0.0095 56412 {main}( ) ../cook.php:0 2 0.0101 68272 Microwave->receiveItem( ) ../cook.php:13 I would really appreciate it if someone could look at my code and see where the problem is at. My guess is that it is in cook.php, but who knows?! Attached is a ZIP of my entire directory structure. Thanks, TomTees I have a page in which the print_r ($session) displays the following: Array ( [securityToken] => 23b1f22bffd9f5097878618da57b14a2 [cartID] => [cart] => shoppingCart Object ( [contents] => Array ( ) [total] => 0 [weight] => 0 [cartID] => [content_type] => [free_shipping_item] => 0 [free_shipping_weight] => 0 [free_shipping_price] => 0 ) [navigation] => navigationHistory Object ( [path] => Array ( [0] => Array ( [page] => index [mode] => NONSSL [get] => Array ( [cPath] => 2_9_843_845_852_856_858_863 ) [post] => Array ( ) ) [1] => Array ( [page] => product_info [mode] => NONSSL [get] => Array ( [cPath] => 2_9_843_845_852_856_858_863 [products_id] => 2299 [action] => add_product ) [post] => Array ( ) ) [2] => Array ( [page] => shopping_cart [mode] => NONSSL [get] => [post] => Array ( ) ) [3] => Array ( [page] => checkout_shipping [mode] => NONSSL [get] => [post] => Array ( ) ) [4] => Array ( [page] => checkout_payment [mode] => NONSSL [get] => [post] => Array ( ) ) [5] => Array ( [page] => checkout_confirmation [mode] => NONSSL [get] => [post] => Array ( ) ) [6] => Array ( [page] => checkout_process [mode] => NONSSL [get] => [post] => Array ( ) ) [7] => Array ( [page] => checkout_success [mode] => NONSSL [get] => [post] => Array ( ) ) ) [snapshot] => Array ( ) ) [check_valid] => true [language] => english [languages_id] => 1 [languages_code] => en [currency] => USD [today_is] => 2010-11-26 [updateExpirations] => 1 [session_counter] => 1 [new_products_id_in_cart] => 2299 [valid_to_checkout] => 1 [cart_errors] => [customer_id] => 2 [customer_first_name] => test [customer_default_address_id] => 2 [customer_country_id] => 223 [customer_zone_id] => 2 [customers_authorization] => 0 [messageToStack] => [payment_attempt] => 1 ) What I need to do is loop through the navigationHistory Object , grab the product id, and then get the cPath for that particular product id. I have worked with sessions a lot, but I cannot seem to ever get the session object and loop thing down. At this point I am ripping out my hair trying to figure out what is most likely a simple solution to this - can anyone help me? Hello, i been making a site to learn some PHP. I been always searching about what's the best way of using the PHP functions, classes and objects but i have a small question that i couldnt found the awnser by my self. so far i m inicializing an PHP class like this: 1st case Code: [Select] $themeobj = new theme(); Today i found an tuturial that used an other way of calling an function inside the class: 2nd case Code: [Select] theme::loadTheme; I understand that the way i m doing, your iniciating the variable $themeobj as an object of the class theme and that the theme:loadTheme just calls the function loadTheme inside the theme class (please correct me if i m wrong), but here's where is where i need abit of enlightment. Using the 2nd case will "skip" the loading of the __construct function? when should you use the 1st case or the 2nd case? Every time i needed an function from theme i would use $themeobj->loadTheme($param) its safe to use theme::loadTheme($param)? Thanks in advance |