Jump to content

NotionCommotion

Members
  • Posts

    2,446
  • Joined

  • Last visited

  • Days Won

    10

Everything posted by NotionCommotion

  1. Hello benanamen, I've never used a 3rd party ORM before and have previously used homespun scripts of my own. Have you ever used one, and specifically have you ever used Doctrine? The reason I put my Vehicle/AirVehicle/Rocket example together was primarily so I can get a small simple implementation working before deploying it to a more complicated application. I can successfully create new entities and store them in the database as shown by my previous post, but have not been successful retrieving all entities of a given type nor retrieving a given entity by ID. Do you know what I am doing wrong? Thanks
  2. Looks like something is not right. Any ideas? <?php //use MyNamespace\MyApp; error_reporting(E_ALL); ini_set("log_errors", '1'); ini_set('display_startup_errors', '1'); ini_set('display_errors', '1'); require_once "../bootstrap.php"; function createObj($em, $class) { $cn=explode('\\', $class); $cn=$cn[count($cn)-1]; $entity = new $class(); $entity->setChildItem1("$cn c1"); $entity->setChildItem2("$cn c2"); $entity->setParentItem1("$cn p1"); $entity->setParentItem2("$cn p2"); $entity->setGrandParentItem1("$cn g1"); $entity->setGrandParentItem2("$cn g2"); try{ $em->persist($entity); $em->flush(); echo "Created $class with ID " . $entity->getId() . "\n\n"; } catch(\Exception $e) { echo($class.' - '.$e->getMessage()."\n\n"); } } function displayMember($em, $class, $id) { try{ $member=$em->find($class, $id); echo("Member $id for $class\n\n"); print_r($member); } catch(\Exception $e) { echo($class.' - '.$e->getMessage()."\n\n"); } } function displayAllMembers($em, $class) { $repository = $em->getRepository($class); try{ $members=$repository->findAll(); echo("Members for $class\n\n"); print_r($members); } catch(\Exception $e) { echo($class.' - '.$e->getMessage()."\n\n"); } } $entities=[ 'Vehicle'=>['class'=>'\MyNamespace\MyApp\Vehicle\Vehicle','children'=>[ 'AirVehicle'=>['class'=>'\MyNamespace\MyApp\Vehicle\GroundVehicle\GroundVehicle','children'=>[ 'Train'=>'\MyNamespace\MyApp\Vehicle\GroundVehicle\Train\Train', 'Car'=>'\MyNamespace\MyApp\Vehicle\GroundVehicle\Car\Car' ]], 'GroundVehicle'=>['class'=>'\MyNamespace\MyApp\Vehicle\AirVehicle\AirVehicle','children'=>[ 'Rocket'=>'\MyNamespace\MyApp\Vehicle\AirVehicle\Rocket\Rocket', 'Airplane'=>'\MyNamespace\MyApp\Vehicle\AirVehicle\Airplane\Airplane' ]] ] ], ]; //Creating works correctly foreach($entities as $grandparentName=>$grandparent) { //createObj($em, $grandparent['class']); //Abstract foreach($grandparent['children'] as $parentName=>$parent) { //createObj($em, $parent['class']); //Abstract foreach($parent['children'] as $childName=>$class) { createObj($em, $class); } } } displayMember($em, '\MyNamespace\MyApp\Vehicle\GroundVehicle\Train\Train', 37); displayMember($em, '\MyNamespace\MyApp\Vehicle\GroundVehicle\GroundVehicle', 37); displayMember($em, '\MyNamespace\MyApp\Vehicle\Vehicle', 37); foreach($entities as $grandparentName=>$grandparent) { displayAllMembers($em, $grandparent['class']); foreach($grandparent['children'] as $parentName=>$parent) { displayAllMembers($em, $parent['class']); foreach($parent['children'] as $class) { displayAllMembers($em, $class); } } } Created \MyNamespace\MyApp\Vehicle\GroundVehicle\Train\Train with ID 53 Created \MyNamespace\MyApp\Vehicle\GroundVehicle\Car\Car with ID 54 Created \MyNamespace\MyApp\Vehicle\AirVehicle\Rocket\Rocket with ID 55 Created \MyNamespace\MyApp\Vehicle\AirVehicle\Airplane\Airplane with ID 56 \MyNamespace\MyApp\Vehicle\GroundVehicle\Train\Train - An exception occurred while executing 'SELECT t2.id AS id_3, t2.grandParentItem1 AS grandParentItem1_4, t2.grandParentItem2 AS grandParentItem2_5, t1.parentItem1 AS parentItem1_6, t1.parentItem2 AS parentItem2_7, t0.childItem1 AS childItem1_8, t0.childItem2 AS childItem2_9, t2.dtype FROM train_table t0 INNER JOIN ground_vehicle t1 ON t0.id = t1.id INNER JOIN vehicle_table t2 ON t0.id = t2.id WHERE t2.id = ?' with params [37]: SQLSTATE[42S22]: Column not found: 1054 Unknown column 't2.dtype' in 'field list' \MyNamespace\MyApp\Vehicle\GroundVehicle\GroundVehicle - An exception occurred while executing 'SELECT t1.id AS id_4, t1.grandParentItem1 AS grandParentItem1_5, t1.grandParentItem2 AS grandParentItem2_6, t0.parentItem1 AS parentItem1_7, t0.parentItem2 AS parentItem2_8, t1.dtype, t2.childItem1 AS childItem1_9, t2.childItem2 AS childItem2_10, t3.childItem1 AS childItem1_11, t3.childItem2 AS childItem2_12 FROM ground_vehicle t0 INNER JOIN vehicle_table t1 ON t0.id = t1.id LEFT JOIN train_table t2 ON t0.id = t2.id LEFT JOIN car_table t3 ON t0.id = t3.id WHERE t1.id = ?' with params [37]: SQLSTATE[42S22]: Column not found: 1054 Unknown column 't1.dtype' in 'field list' \MyNamespace\MyApp\Vehicle\Vehicle - The discriminator value "train" is invalid. It must be one of "vehicle", "groundVehicle", "airVehicle". \MyNamespace\MyApp\Vehicle\Vehicle - The discriminator value "airplane" is invalid. It must be one of "vehicle", "groundVehicle", "airVehicle". \MyNamespace\MyApp\Vehicle\GroundVehicle\GroundVehicle - An exception occurred while executing 'SELECT t1.id AS id_4, t1.grandParentItem1 AS grandParentItem1_5, t1.grandParentItem2 AS grandParentItem2_6, t0.parentItem1 AS parentItem1_7, t0.parentItem2 AS parentItem2_8, t1.dtype, t2.childItem1 AS childItem1_9, t2.childItem2 AS childItem2_10, t3.childItem1 AS childItem1_11, t3.childItem2 AS childItem2_12 FROM ground_vehicle t0 INNER JOIN vehicle_table t1 ON t0.id = t1.id LEFT JOIN train_table t2 ON t0.id = t2.id LEFT JOIN car_table t3 ON t0.id = t3.id': SQLSTATE[42S22]: Column not found: 1054 Unknown column 't1.dtype' in 'field list' \MyNamespace\MyApp\Vehicle\GroundVehicle\Train\Train - An exception occurred while executing 'SELECT t2.id AS id_3, t2.grandParentItem1 AS grandParentItem1_4, t2.grandParentItem2 AS grandParentItem2_5, t1.parentItem1 AS parentItem1_6, t1.parentItem2 AS parentItem2_7, t0.childItem1 AS childItem1_8, t0.childItem2 AS childItem2_9, t2.dtype FROM train_table t0 INNER JOIN ground_vehicle t1 ON t0.id = t1.id INNER JOIN vehicle_table t2 ON t0.id = t2.id': SQLSTATE[42S22]: Column not found: 1054 Unknown column 't2.dtype' in 'field list' \MyNamespace\MyApp\Vehicle\GroundVehicle\Car\Car - An exception occurred while executing 'SELECT t2.id AS id_3, t2.grandParentItem1 AS grandParentItem1_4, t2.grandParentItem2 AS grandParentItem2_5, t1.parentItem1 AS parentItem1_6, t1.parentItem2 AS parentItem2_7, t0.childItem1 AS childItem1_8, t0.childItem2 AS childItem2_9, t2.dtype FROM car_table t0 INNER JOIN ground_vehicle t1 ON t0.id = t1.id INNER JOIN vehicle_table t2 ON t0.id = t2.id': SQLSTATE[42S22]: Column not found: 1054 Unknown column 't2.dtype' in 'field list' \MyNamespace\MyApp\Vehicle\AirVehicle\AirVehicle - An exception occurred while executing 'SELECT t1.id AS id_4, t1.grandParentItem1 AS grandParentItem1_5, t1.grandParentItem2 AS grandParentItem2_6, t0.parentItem1 AS parentItem1_7, t0.parentItem2 AS parentItem2_8, t1.dtype, t2.childItem1 AS childItem1_9, t2.childItem2 AS childItem2_10, t3.childItem1 AS childItem1_11, t3.childItem2 AS childItem2_12 FROM air_vehicle t0 INNER JOIN vehicle_table t1 ON t0.id = t1.id LEFT JOIN airplane_table t2 ON t0.id = t2.id LEFT JOIN rocket_table t3 ON t0.id = t3.id': SQLSTATE[42S22]: Column not found: 1054 Unknown column 't1.dtype' in 'field list' \MyNamespace\MyApp\Vehicle\AirVehicle\Rocket\Rocket - An exception occurred while executing 'SELECT t2.id AS id_3, t2.grandParentItem1 AS grandParentItem1_4, t2.grandParentItem2 AS grandParentItem2_5, t1.parentItem1 AS parentItem1_6, t1.parentItem2 AS parentItem2_7, t0.childItem1 AS childItem1_8, t0.childItem2 AS childItem2_9, t2.dtype FROM rocket_table t0 INNER JOIN air_vehicle t1 ON t0.id = t1.id INNER JOIN vehicle_table t2 ON t0.id = t2.id': SQLSTATE[42S22]: Column not found: 1054 Unknown column 't2.dtype' in 'field list' \MyNamespace\MyApp\Vehicle\AirVehicle\Airplane\Airplane - An exception occurred while executing 'SELECT t2.id AS id_3, t2.grandParentItem1 AS grandParentItem1_4, t2.grandParentItem2 AS grandParentItem2_5, t1.parentItem1 AS parentItem1_6, t1.parentItem2 AS parentItem2_7, t0.childItem1 AS childItem1_8, t0.childItem2 AS childItem2_9, t2.dtype FROM airplane_table t0 INNER JOIN air_vehicle t1 ON t0.id = t1.id INNER JOIN vehicle_table t2 ON t0.id = t2.id': SQLSTATE[42S22]: Column not found: 1054 Unknown column 't2.dtype' in 'field list'
  3. I think I am close, but not sure if I am quite there. Am I doing this correctly? I have several entity classes which will use class type inheritance: MyNamespace\MyApp\Vehicle\Vehicle MyNamespace\MyApp\Vehicle\AirVehicle\AirVehicle MyNamespace\MyApp\Vehicle\AirVehicle\Airplane\Airplane MyNamespace\MyApp\Vehicle\AirVehicle\Rocket\Rocket MyNamespace\MyApp\Vehicle\GroundVehicle\GroundVehicle MyNamespace\MyApp\Vehicle\GroundVehicle\Car\Car MyNamespace\MyApp\Vehicle\GroundVehicle\Train\Train The entity meta data is as follows: #MyNamespace.MyApp.Vehicle.Vehicle.dcm.yml MyNamespace\MyApp\Vehicle\Vehicle: type: entity table: vehicle_table inheritanceType: JOINED discriminatorColumn: name: discriminator_column type: string discriminatorMap: vehicle: Vehicle groundVehicle: MyNamespace\MyApp\Vehicle\GroundVehicle\GroundVehicle airVehicle: MyNamespace\MyApp\Vehicle\AirVehicle\AirVehicle repositoryClass: Vehicle id: id: type: integer generator: strategy: AUTO fields: grandParentItem1: type: string grandParentItem2: type: string #MyNamespace.MyApp.Vehicle.AirVehicle.AirVehicle.dcm.yml MyNamespace\MyApp\Vehicle\AirVehicle\AirVehicle: type: entity table: air_vehicle extends: MyNamespace\MyApp\Vehicle\Vehicle inheritanceType: JOINED discriminatorMap: airVehicle: AirVehicle airplane: MyNamespace\MyApp\Vehicle\AirVehicle\Airplane\Airplane rocket: MyNamespace\MyApp\Vehicle\AirVehicle\Rocket\Rocket repositoryClass: AirVehicle id: id: associationKey: true fields: parentItem1: type: string parentItem2: type: string #MyNamespace.MyApp.Vehicle.AirVehicle.Rocket.Rocket.dcm.yml MyNamespace\MyApp\Vehicle\AirVehicle\Rocket\Rocket: extends: MyNamespace\MyApp\Vehicle\AirVehicle\AirVehicle type: entity table: rocket_table id: id: associationKey: true repositoryClass: Rocket fields: childItem1: type: string childItem2: type: string I haven't shown GroundVehicle or Train, Car, and Airplane, but they are almost identical to AirVehicle and Rocket, respectively. I've discovered that the barebone entities need to be manually created prior to using orm:generate-entities else I get class not found errors, and have created them as shown below. inheritance_src/MyNamespace/MyApp/Vehicle/Vehicle.php inheritance_src/MyNamespace/MyApp/Vehicle/AirVehicle/AirVehicle.php inheritance_src/MyNamespace/MyApp/Vehicle/AirVehicle/Airplane/Airplane.php inheritance_src/MyNamespace/MyApp/Vehicle/AirVehicle/Rocket/Rocket.php inheritance_src/MyNamespace/MyApp/Vehicle/GroundVehicle/GroundVehicle.php inheritance_src/MyNamespace/MyApp/Vehicle/GroundVehicle/Car/Car.php inheritance_src/MyNamespace/MyApp/Vehicle/GroundVehicle/Train/Train.php [michael@devserver doctrine]$ find inheritance_src -name "*.php" -exec cat {} \; <?php namespace MyNamespace\MyApp\Vehicle\AirVehicle\Airplane; class Airplane extends \MyNamespace\MyApp\Vehicle\AirVehicle\AirVehicle{} <?php namespace MyNamespace\MyApp\Vehicle\AirVehicle\Rocket; class Rocket extends \MyNamespace\MyApp\Vehicle\AirVehicle\AirVehicle{} <?php namespace MyNamespace\MyApp\Vehicle\AirVehicle; abstract class AirVehicle extends \MyNamespace\MyApp\Vehicle\Vehicle{} <?php namespace MyNamespace\MyApp\Vehicle\GroundVehicle\Car; class Car extends \MyNamespace\MyApp\Vehicle\GroundVehicle\GroundVehicle{} <?php namespace MyNamespace\MyApp\Vehicle\GroundVehicle\Train; class Train extends \MyNamespace\MyApp\Vehicle\GroundVehicle\GroundVehicle{} <?php namespace MyNamespace\MyApp\Vehicle\GroundVehicle; abstract class GroundVehicle extends \MyNamespace\MyApp\Vehicle\Vehicle{} <?php namespace MyNamespace\MyApp\Vehicle; abstract class Vehicle{} I then am able to successfully create the entities using orm:generate-entities, schema using orm:schema-tool:create, and repositories using orm:generate-repositories. Does everything seem correct? A couple of issues which I have my doubts: Locating the classes in inheritance_src/MyNamespace/MyApp instead of inheritance_src/MyApp. I tried to do the later and modify my psr-4 autoloader to use "MyNamespace\\": "inheritance_src/", but could not get it working without first creating the entities, editing them to add the "abstract" and "extend" portions, and then moving them to one directory lower. Needing to manually create the barebone classes in the first place. My meta-data definitions includes "extends: MyNamespace\MyApp\Vehicle\Vehicle", so I would thought it would not be necessary. Locate both the entities and repositories in the same folder. For that matter, I will probably be locating my service in the same folder as well. It seems that most frameworks will locate all the entities in one folder (with of course subdirectories), repositories in another, services in another, etc. The way I am doing seems to be organized domain modules as described by https://mnapoli.fr/organizing-code-into-domain-modules/. Any compelling reasons to do it one way or the other? Thank you
  4. I only use : and ? for prepared statements never use bindValue() or bindParam(). One "trick" I have done when the where statement uses IN is as follows: $list=rtrim(str_repeat('?,',count($d)),','); $sql="SELECT a, b, c FROM my_table WHERE id IN ($list)"; $stmt = $this->pdo->prepare($sql); $stmt->execute($d); Another one for non-complicated inserts with a bunch of columns is a method which is passed the table name and an associated array where the array keys are used as column names. protected function insertDB($table,array $data) { /* $data is an array who's indexes are table columns and values are validated data to insert */ $columns1=[]; $columns2=[]; foreach($data as $key=>$value) { $columns1[]=$key; $columns2[]=':'.$key; } $columns1=implode(',',$columns1); $columns2=implode(',',$columns2); $stmt = $this->pdo->prepare("INSERT INTO $table ($columns1) VALUES($columns2)"); return $stmt->execute($data); } Recently, when using this method, one of the values in the array was Boolean, and the associated SQL column was BOOL, and the query failed. Am I living dangerously not using one of the bind methods all the time? What are the particular circumstances that I should be concerned? Can my insertDB() method be adapted to do so? I am thinking that thee foreach loop can check the type of the array value, and bind accordingly. But then again, PHP is so loose that maybe doing so is not smart. Thanks
  5. I believe it is relevant to me. I've gone back and forth on what approach is "best", and it has been a futile endeavor. That is why I specifically did not ask what approach is best. I do believe, however, it is important to be consistent, and to my determinant, I have not been in this regard. I've even changed code because on that given day, I felt my style should be one way or the other. I've witnessed very good programmers on this forum using one style or the other, but unlike me, they consistently use the same style. My desire is to identify the style of the majority of programmers, and adapt that style as my own.
  6. I am not asking whether one approach is better than the other, or what you do for more obscure cases such as closure. Only for defining normal methods (and I assume normal functions as well). Assuming you were starting the code off from scratch, what would you do? Thank you public function myFunction() { // } public function myFunction() { // }
  7. Consider the following. Is it possible to do so database vendor agnostic? <?php function testException($pdo,$sql,$data) { try { $stmt=$pdo->prepare($sql); $stmt->execute($data); echo("NO ERROR FOR $sql\n"); } catch (PDOException $e) { $error = $stmt->errorInfo(); echo("SQL: $sql\n"); if($error[0]==23000 && $error[1]==1062) { echo("Do something for: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry\n\n"); } elseif($error[0]==23000 && $error[1]==1451) { echo("Do something for: SQLSTATESQLSTATE[23000]: Integrity constraint violation: 1451 foreign key constraint fails\n\n"); } else { throw $e; } } } $db=parse_ini_file('../../config.ini',true)['mysql']; $pdo = new \PDO("mysql:host={$db['host']};dbname={$db['dbname']};charset={$db['charset']}",$db['username'],$db['password'],array(\PDO::ATTR_EMULATE_PREPARES=>false,\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=>true,\PDO::ATTR_ERRMODE=>\PDO::ERRMODE_EXCEPTION,\PDO::ATTR_DEFAULT_FETCH_MODE=>\PDO::FETCH_OBJ)); $sql='INSERT INTO sources_type(type,name) VALUES(?,?)'; $data=['client','my name']; testException($pdo,$sql,$data); $sql='DELETE FROM sources_type WHERE type=?'; $data=['client']; testException($pdo,$sql,$data);
  8. Do you know about http://php.net/manual/en/book.pdo.php? If not learn. It is not difficult, and will make things much easier for you. Ask questions as needed. $stmt=$pdo->prepare('SELECT Name, Gender FROM your_table WHERE Country=?'); $stmt->execute([$_GET['Country']]); $stmt->fetchAll();
  9. I am building a client which will continuously attempt to connect to a server of a given IP. After connected, messages will be sent and received via JSON RPC over TCP/IP socket streams. If the client sends a confirming JSON RPC message to the server, and the client does not receive a response within the specified time period, what should the client do? Should the client break the connection, and then go back to attempting to connect? Should it do it after the first incident, or should it be more tolerant and reattempt the request using the same message id several times? If so, are there rules of thumb how many times? http://json-rpc.org/wiki/specification 1.0 section 2.1 JSON-RPC over stream connections states the following. What does this mean? JSONRPC Specification 2.0 is silent on this issue. Thanks
  10. Look into ReactPHP, and try the following. <?php require 'vendor/autoload.php'; $loop = \React\EventLoop\Factory::create(); $socket = new \React\Socket\Server($loop); $socket->on('connection', function (\React\Socket\ConnectionInterface $stream) { $stream->on('data', function($data) use ($stream){ $stream->write("send $data back to client"); }); }); $socket->listen(1337,'0.0.0.0'); $loop->run(); { "require": { "react/socket": "^0.4.4", "react/stream": "^0.4.5", "react/event-loop": "^0.4.2", } }
  11. employee------<employeehadcheckboxs>-------checkboxes employee has pk id and a bunch of other columns. checkboxes has pk id and a bunch of other columns. employeehadcheckboxs has two columns which are the other two tables pk User submits form which includes employeeID and a bunch of checkbox ids. Either delete all records in employeehadcheckboxs for employee and reinsert the new ones, or find out which ones have changed, and update accordingly.
  12. Dang, I am so sorry this happened to you. How can I help?
  13. It seems to me that the models shouldn't communicate between each other, but you should use the controller to perform that logic. That being said, having individual models with presumably only one public method each such as one for creating a record, one for reading a record, one for updating a record, one for deleting a record (what's it spell?) is way to specific. I would say you should have one settings model which does all these tasks. You could and should also extend that model from some likely abstract model which can do tasks common to all models.
  14. I am trying to emit an error and have the server receive it. A couple of issues. Guess I was thinking that $stream->on('error',.. and $client->on('error',... will receive different emits. They don't seem to do so. Does the below code make no sense in the regard, and should I be doing things differently? Maybe just emit "criticalError" and "normalError", and have server's on listen for both? Should the ->on() be on $stream or $client? Is $this->socket->on('error', function($error){ ...}); necessary in LengthPrefixStream()? What does it do if it is there? Thanks <?php $loop = \React\EventLoop\Factory::create(); // Or \React\EventLoop\StreamSelectLoop()? $socket = new \React\Socket\Server($loop); $socket->on('connection', function (\React\Socket\ConnectionInterface $stream) { $client = new LengthPrefixStream($stream); $client->on('data', function($data) use ($client){ syslog(LOG_INFO,"on data"); }); $stream->on('error', function($error, $stream) { //Critical error, disconnect from server syslog(LOG_INFO,"on stream error: ".json_encode($error)); $stream->close(); }); $client->on('error', function($error) use($stream){ //Non-Critical error, Do not disconnect from server syslog(LOG_INFO,"on client error: ".json_encode($error)); }); }); $socket->listen($this->host['port'],$this->host['url']); $loop->run(); <?php class LengthPrefixStream implements EventEmitterInterface { use EventEmitterTrait; private $socket=false; public function __construct(DuplexStreamInterface $socket, $parseJson=1){ $this->parseJson = $parseJson; $this->socket = $socket; $this->socket->on('data', function($data){ //I will parse the stream, but am not showing it for this example $obj=json_decode($data); if (json_last_error() == JSON_ERROR_NONE){ $this->emit('data', [$obj]); } else { syslog(LOG_INFO,"Non-critical error. Do not disconnect from client."); $this->emit('error', ["Bad JSON"]); } }); $this->socket->on('error', function($error){ syslog(LOG_INFO,"Critical error. Disconnect from client."); $this->emit('error', [$error]); }); } }
  15. My bad. I incorrectly read the documents to imply that json_decode() will sometimes return false. <?php function jsondecode($json) { var_dump($json); var_dump(json_decode($json)); var_dump(json_last_error()); } jsondecode('[]'); jsondecode('bad'); jsondecode(true); jsondecode(false); jsondecode(null); string(2) "[]" array(0) { } int(0) string(3) "bad" NULL int(4) bool(true) int(1) int(0) bool(false) NULL int(4) NULL NULL int(4)
  16. Per http://php.net/manual/en/function.json-decode.php: Okay, so NULL represents a bad json string. If I don't care why it is bad, no need to use json_last_error(), right? What does false represent? It is my understanding that the JSON RFC7159 spec requires all true, false, and null to be lower case. Why does the PHP documentation show these as being returned as uppercase?
  17. I asked a similar question a while back. Should exceptions be thrown based on invalid user input? I was told that probably not as exceptions should only be thrown on extreme edge conditions. Let me ask the same question, but limit it to only a REST API using the Slim framework? The framework has error handling used to catch uncaught exceptions and issue PSR7 responses. Specifically for this scenario, is it wrong to throw exceptions for invalid user input? I could use ValidationException for this purpose. I could use built in PDOException, etc for standard exceptions. I could use ErrorException which is thrown by exception_error_handler(). It seems to me that using exceptions simplifies code and better ensures a consistent interface.
  18. Do I need to use two catch blocks, or is there a way to do it all in one? Thanks class BarException extends Exception {} public function foo() { try { $this->pdo->beginTransaction(); $this->doQuery(); $rsp=$this->doMethodWhichThrowsBarExtention(); $this->pdo->commit(); } catch(PDOException $e){ $this->pdo->rollBack(); $rsp=$e->getMessage(); } catch(BarException $e){ $this->pdo->rollBack(); $rsp=$e->getMessage(); } return $rsp; }
  19. I guess technically I could rewind before ftruncate as ftruncate does not change the position and it will remain at zero, but will not do so, and will do as you recommend. Thanks
  20. Why after? Per the documents http://php.net/manual/en/function.ftruncate.php
  21. Thanks kicken, Well, don't know if it was the best answer as Jacques1's regarding +r (rookies mistake on my part) and rewind were pretty good also. But that caching thing was pretty damn frustrating. Ended up using only one rewind($fp) before the ftruncate statement. Thanks all!
  22. No change in results. Do you mind running this script, and see what you get? Thanks <?php $file='myjson.json'; addRecord($file,'hello1'); addRecord($file,'hello2'); addRecord($file,'hello3'); echo(file_get_contents($file)); function addRecord($file,$msg) { $fp = fopen($file, "r+"); if (flock($fp, LOCK_EX)) { //rewind($fp); //rewind 1. Not required since??? 'r+' Open for reading and writing; place the file pointer at the beginning of the file $filesize=filesize($file); $json=$filesize?fread($fp, $filesize):'[]'; rewind($fp); //rewind 2. Where is the pointer now? http://php.net/manual/en/function.fread.php doesn't seem to say. $arr=json_decode($json); $newRow=(object)['name'=>$msg]; $arr[]=$newRow; $new_json=json_encode($arr); ftruncate($fp, 0); rewind($fp); //rewind 3 Per http://php.net/manual/en/function.ftruncate.php, the pointer isn't changed. fwrite($fp, $new_json); //rewind($fp); //rewind 4. Where is the pointer now? http://php.net/manual/en/function.fwrite.php doesn't seem to say. fflush($fp); flock($fp, LOCK_UN); } else{ exit('Could not lock the file!!!'); } fclose($fp); }
  23. It would help if I learned to read... Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  24. Thanks Jacques1, Good news is I am no longer getting the empty space characters. Bad news is I am still not saving the earlier writes. I went a little crazy with the rewinds (however, I also removed some places to check for change in effect). I would expect rewind 1 isn't required because w+ automatically goes to the beginning. I also don't think rewind 2 is required based on my reading of the documents. Rewind 3 normally is required, but since I am truncating to 0, I wouldn't think it was. Also looking at the documents, I didn't see any need of using ftruncate after the fwrite. If starting with an empty myjson.json file, if I run the below script once, I get [{"name":"hello3"}]. If I run it twice, I get [{"name":"hello2"},{"name":"hello3"}], and if I run it again and again, I only get what it produced on the second run. Is this expected? My desired results are [{"name":"hello1"},{"name":"hello2"},{"name":"hello3"}] if I run it once, and [{"name":"hello1"},{"name":"hello2"},{"name":"hello3"},{"name":"hello1"},{"name":"hello2"},{"name":"hello3"}]if I run it twice, and so on. How can this be accomplished? Thanks <?php $file='myjson.json'; addRecord($file,'hello1'); addRecord($file,'hello2'); addRecord($file,'hello3'); echo(file_get_contents($file)); function addRecord($file,$msg) { $fp = fopen($file, "w+"); //$fp = fopen($file, "c+"); if (flock($fp, LOCK_EX)) { rewind($fp); //rewind 1 $filesize=filesize($file); $json=$filesize?fread($fp, $filesize):'[]'; rewind($fp); //rewind 2 $arr=json_decode($json); $newRow=(object)['name'=>$msg]; $arr[]=$newRow; $new_json=json_encode($arr); ftruncate($fp, 0); rewind($fp); //rewind 3 fwrite($fp, $new_json); rewind($fp); //rewind 4 fflush($fp); flock($fp, LOCK_UN); } else{ exit('Could not lock the file!!!'); } fclose($fp); }
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.