NotionCommotion
Members-
Posts
2,446 -
Joined
-
Last visited
-
Days Won
10
Everything posted by NotionCommotion
-
Creating object only once in a function
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Never knew that. Thanks -
Creating object only once in a function
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Thanks maxxd, dm() is a function, and $logger is an object. The $this->logger->pushHandler(...) was a typo and I meant $logger->pushHandler(...). That wasn't the error, however, but the error was making the object static. Probably a bad design pattern, but still would like to know why it results in the error, and what other approaches there are.. -
Creating object only once in a function
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Testing my theory, but no-go... Any other suggestions? EDIT. Also, why the error? <?php // Debug Message if(!function_exists('dm')) { function dm($msg) { if(getenv('DEBUG')) { $time = date('Y-m-d H:i:s', time()); switch (gettype($msg)) { case 'string': echo $time . ' ' . $msg . PHP_EOL; break; case 'array': echo $time . ' '; print_r($msg); break; default: echo $time . ' '; var_dump($msg); break; } } if(!isset($logger)) { static $logger = new \Monolog\Logger('my_logger'); $this->logger->pushHandler(new \Monolog\Handler\StreamHandler(__DIR__."/../logs/client.log")); } $logger->addInfo('Hello'); } } michael@dev2:/var/www $ php client.php PHP Parse error: syntax error, unexpected 'new' (T_NEW) in /var/www/src/Support/helpers.php on line 26 michael@dev2:/var/www $ -
The following is a global logging function. It is used on a PHP service than runs indefinitely, so I don't want to needlessly use memory. <?php // Debug Message if(!function_exists('dm')) { function dm($msg) { if(getenv('DEBUG')) { $time = date('Y-m-d H:i:s', time()); switch (gettype($msg)) { case 'string': echo $time . ' ' . $msg . PHP_EOL; break; case 'array': echo $time . ' '; print_r($msg); break; default: echo $time . ' '; var_dump($msg); break; } } } } I next wish to add a Monolog to it, and log all times dm() is called. How should I do so so that the $logger object is not created each time, and also without polluting namespace? $logger = new \Monolog\Logger('my_logger'); $logger->pushHandler(new \Monolog\Handler\StreamHandler(__DIR__."/../logs/client.log")); $logger->addInfo('hello'); Humm, as I write this, I wonder if this is a good use of the static keyword?
-
Purpose of second argument to PDO::query()?
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Thanks ginerjm, Yes, I am with you regarding the fetch style when used with the fetch method, but wasn't sure when it came to the query method. Thanks kicken, I haven't ever depended upon PDO::setAttribute with PDO::ATTR_DEFAULT_FETCH_MODE, however, I always specify the fetch style with my fetch() or fetchAll() (but not fetchColumn) methods, and I guess that is why I didn't recognize it. -
I am looking at some old code I wrote, and I have no idea why I did it. What is the purpose of second argument to PDO::query()? Looking at http://php.net/manual/en/pdo.query.php, it doesn't even appear that PDO::FETCH_OBJ is valid. foreach($this->db->query('SELECT id, name FROM points',PDO::FETCH_OBJ) as $point) { // ... }
-
Recommended directory structure when Composer is used?
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
I had looked for a PSR, but didn't find one at http://www.php-fig.org/. I really need to standardize on one approach, and guess if I am not doing so, not much hope for the industry. -
How would you recommend structuring your project directory. For instance, where should vendor go? What about public folder, and what do you call it (html, public, etc). Should "src" be used, and what for? What should be ignored in Git (i.e. vendor and logs)? Should public js/css files be directly in the public directory, or should they be located in the code directory and a symbolic link used? Is there some sort of psr standard? My hopes are to be consistent with the industry. Thanks
-
Thanks Jacques1 PS. We all agree it should be "Clinton High School", and not another name?
-
Just to beat this to death. Would this be wrong? +------------------------+-----------------+-------+ | School Name | Class President | Grade | +------------------------+-----------------+-------+ | Washington High School | Linda Smith | INPUT | | Clinton High School | Bob Reed | INPUT | | Lincoln High School | John Lee | INPUT | +------------------------+-----------------+-------+
-
Looks like tabular data to me. Of course, you need to imagine that some parent actually named their child "Student1". +-------------+--------------+-------------+ | School Name | Student Name | Class Level | +-------------+--------------+-------------+ | School1 | Student1 | Class1 | | School2 | Student2 | Class2 | | School3 | Student3 | Class3 | +-------------+--------------+-------------+
-
I am not saying tables should ever be used for layout. Or am I? . So, I am assuming we agree the following is acceptable as it is being used solely for tabular data? What if I wanted the same thing, but also wish each of the data elements to be a link? Still okay? Or not a link, but each is inline editable? Or inputs as the OP showed? Are they not all being used for tabular content? <table> <tr> <td>School1</td> <td>Student1</td> <td>Class1</td> </tr> <tr> <td>School2</td> <td>Student2</td> <td>Class2</td> </tr> <tr> <td>School3</td> <td>Student3</td> <td>Class3</td> </tr> </table>
-
While I agree that the OP's use of names is not the way to go, and that something like entities[] should be used, I do feel tables still have a good use when a table is desired as shown by the OP.
-
What to do next with reactphp?
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Making a little progress. The following client will send the time to the server ever 5 seconds. When the server gets a request, it will respond with the same time value. My plan is to replace the time with some JSON which contains the task/data which is desired to be accomplished. Instead of having the server only respond when it gets a request from the client, I would like to have the server send data over based on some other event. I believe I can make the server send the data by using $conn->write($data);, and the client will receive this data on the $stream->on('data', function ($data) {} callback. So, how do I initiate the server to send the data? For instance, a web client makes a request to a machine running both Apache and this React server. The Apache script will authenticate, and then needs to somehow make the Request server send it out. Thanks! client.php <?php require '../vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $dnsResolverFactory = new React\Dns\Resolver\Factory(); $dns = $dnsResolverFactory->createCached('8.8.8.8', $loop); $connector = new React\SocketClient\Connector($loop, $dns); $connector->create('127.0.0.1', 1337)->then(function (React\Stream\Stream $stream) use ($loop) { // 5 second loop to poll server $loop->addPeriodicTimer(5, function(React\EventLoop\Timer\Timer $timer) use (&$i, $loop, $stream) { // Do whatever you want $stream->write(time() . PHP_EOL); }); // Respond to data from server $stream->on('data', function ($data) { echo $data; }); }); $loop->run(); server.php <?php require '../vendor/autoload.php'; $loop = React\EventLoop\Factory::create(); $socket = new React\Socket\Server($loop); // This event triggers every time a new connection comes in $socket->on('connection', function ($conn) { // Event listener for incoming data $conn->on('data', function ($data, $conn) { // Write data back to the connection $conn->write($data); // Echo the data into our terminal window echo $data; }); }); // Listen on port 1337 and IP 127.0.0.1 $socket->listen(1337, '127.0.0.1'); $loop->run(); -
What to do next with reactphp?
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
I too first thought the firewall, but no, however, I believe kicken's post addresses it. How can I specify the address? How did you know @kicken about this special 0.0.0.0 address? Is there any documentation? EDIT. Ah, from a depreciated tutorial https://blog.wyrihaximus.net/2014/04/the-reactphp-event-loop-explained-part-1-streams/, I think it is done using $socket->listen(13378, '0.0.0.0'); Does it make sense to run React on both a client and server at the same time? For instance, client initiates connection to server and waits for server to provide something, reacts to it, and repeats? How is the server made to return something (as it doesn't reply upon request but upon some event, right)? Which classes would I use for both sides? Maybe React\SocketClient\Connector for the client? Any example script would be much appreciated. Also, is it possible to have both a React server and Apache or Nginx server on the same machine which listen to the same port? It seems that either some sort of alias would be needed, or React would need to catch all requests and distribute as necessary. Thank you for your help. -
What to do next with reactphp?
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Thanks requinix, Yea, I tried it on another machine (or better yet, tried to access it from another machine), but it returns false. Oh yea, again. Not how do I send it data, but how do I receive it? As seen by my example, I tried those cURL options. Still need to better get my head about the whole asynchronous i/o thing. -
Messing around with http://reactphp.org/. Couple of questions... How can I access the server with any IP other than 127.0.0.1? How can I send data to it? What is different with this than just putting some script in an apache public directory? Kinda still missing the point of this. <?php require 'vendor/autoload.php'; $app = function ($request, $response) { $response->writeHead(200, array('Content-Type' => 'text/plain')); $response->end('$request=>'.json_encode($request).'$response=>'.json_encode($response)."DONE\n"); }; $loop = React\EventLoop\Factory::create(); $socket = new React\Socket\Server($loop); $http = new React\Http\Server($socket, $loop); $http->on('request', $app); echo "Server running at http://127.0.0.1:1337\n"; $socket->listen(1337); $loop->run(); <?php function test($ip,$data=[]) { $options=[ CURLOPT_URL=>$ip, CURLOPT_RETURNTRANSFER=>true, CURLOPT_PORT=>1337, CURLOPT_POST=>1, CURLOPT_POSTFIELDS=>$data ]; $ch = curl_init(); curl_setopt_array( $ch, $options ); echo("\n\nTest for '$ip'\n"); echo var_dump(curl_exec( $ch )); } test('127.0.0.1'); test('127.0.0.1?x=123'); test('127.0.0.1',[1,2,3]); test('192.168.1.200'); //false test('192.168.1.201'); //false
-
Recommended design pattern for updating name/values
NotionCommotion replied to NotionCommotion's topic in PHP Coding Help
Thanks ginerjm, This is what I ended up doing. See any concerns? public function updateParam($params) { $rs=$this->sanitize($params,['name','value']); if($rs->error) { $rsp=\MyApp\ErrorResponse::missingValue($rs->error); } elseif ($method=$this->getUpdateMethod($rs->data['name'])) { try { $sql="UPDATE $method[table] SET $method[column]=? WHERE id=? AND accounts_id=?"; $stmt = $this->pdo->prepare($sql); $stmt->execute([$rs->data['value'],$this->id,$this->account->id]); $rsp=[null,204]; } catch(\PDOException $e){ switch($e->getCode()) { case 23000: $rsp=\MyApp\ErrorResponse::duplicatedName(); break; default: $rsp=\MyApp\ErrorResponse::customError($e->getMessage()); } } } else { $rsp=\MyApp\ErrorResponse::customError('Invalid column '.$rs->data['name']); } return $rsp; } protected function getUpdateMethod($name) { return [ 'name'=>['column'=>'name','table'=>'items'], 'price'=>['column'=>'unit_price','table'=>'items'], 'code'=>['column'=>'code','table'=>'codes'], ][$name]; } -
I have a bunch of sub classes which extend a base class. In the base class, I was planning on including a method updateValue($name, $value, $primaryKey) which would update the column specified by $name with the value $value for the primary key $primaryKey. Some column names are allowed to be changed for all sub classes, yet others are only allowed to be changed for some of the sub classes. Also, some column names might have unique requirements for all of the sub classes or even just some of them. I will definitely need to whitelist them. Any recommended design patterns to implement this?
-
Thanks kicken, One-way replication is the plan. For the master, I don't understand where the mysqlbinlog would come in. Why wouldn't I use PHP to update some counter whenever it made a change to the DB? I guess the problem with this approach is if the DB was directly changed. To get around this, I can probably use a trigger.
-
Because they have a job to do collecting data regardless of whether the network is up or not. Probably shouldn't be using PHP, but I don't know anything else.
-
Yes! Not directly. I will give instructions to the people who have control over them, but they may make a mistake and not do so correctly. After sleeping on it, I am sure it is impossible for a small hash to be unique for a large input size. As an alternative, I thought of a strong random number (and not worrying about the collisions) or a table in the master with an auto-increment key and using an increment number. You last recommendation is basically my second solution, but yours is more thought out as it checks if the incrementting number is only one operation ahead. Where could I find more details about this "MySQL playbook"? Thank you for your help.
-
Oh, I see. I don't think that will work because that database also houses data which is outside of the data sets which I wish to confirm are the same as the remote data set, and this will cause the SQLite file date to change. Let me explain what I think the workflow should be. Beforehand, a bit on nomenclature. "Master" refers to a server which will among other things, store the desired data in a MySQL database of multiple distributed databases. "Distributed" refers to multiple computers which will use a SQLite database. Okay, here goes... Master receives Ajax request to change one of the distributed database. Records in master database are updated for the particular distributed database. I was thinking of storing either a hash of the new data or a time stamp at this time for the particular distributed DB. A command is sent out by the master to update the particular distributed database either using Redis along with long polling or maybe sockets. If the time stamp approach is taken, then this time stamp will also need to be sent. Particular distributed database hopefully gets the command and updates its database and either hashes the new data and saves it, or saves the received time stamp. There seems to be too many things that could happen which will get the master data set and one of the distributed data sets out of whack. The distributed computers also periodically send data to the master. To ensure the data sets are not out of sync for a long time, I was thinking of the following. When distributed computer sends the data to the master, it also sends either the hash or time stamp. When master receives the data, it checks to see if the hash or time stamp is valid. If so, it replies okay. If not, it sends what should be the distributed computers data set. If I am using Redis as a queue, I will need to somehow deal with cancelling the queue for the particular distributed computer as the distributed data set will now be up to date. So assuming that my approach is not just completely wrong, I need an approach to concisely make a fingerprint of the the data set. As I see it, my options are either hashing the data, or using microtime() to save when it was changed. The hash seems (I don't know why) more appropriate, however, I don't know how hashing works if the input is large (say 60,000 bytes). Did I confuse you? Hopefully, not too much. Thanks
-
I don't understand. How would this work?
-
I am okay with not know what was changed, only whether it was changed. The only time I expect the data to be out of sync is if network is temporarily disrupted, and expect this to be fairly rare. If they are out of sync, I will implement some script to find the differences. What would you recommend to just tell if something was changed?