Jump to content

NotionCommotion

Members
  • Posts

    2,446
  • Joined

  • Last visited

  • Days Won

    10

Everything posted by NotionCommotion

  1. Ended up keeping it really simple. Just replace the values. Used "{ }" and '{ }' as a deliminator so it is valid JSON. It will not allow a text value to be parsed in without quotes, so maybe I will add. final public function parse($template, array $values) { //return preg_replace_callback('/\{"{\ (\w+)\ \}\"/',function ($matches) use ($values) { $re = <<<RE / "{ (\w+) }" | '{ (\w+) }' /x RE; return preg_replace_callback($re,function ($matches) use ($values) { if(isset($values[$matches[1]])){ if(is_bool($values[$matches[1]])){$new=($values[$matches[1]]?'true':'false');} elseif(is_numeric($values[$matches[1]])){$new=$values[$matches[1]];} else{$new=$values[$matches[1]];} } else{$new=$matches[0];} return $new; }, $template); }
  2. This is going to be more difficult than I thought. Suppose I wish to parse the following JSON where noInvalid is true. { "rules":{ "name":{"required":true,{{ noInvalid?'"noInvalid":true,' }}"maxlength":90,"minlength":2 } } } I am looking for the following, however, my class incorrectly splits on the colon between "noInvalid" and true. Furthermore, the text above is not valid JSON, and is hard to troubleshoot. { "rules":{ "name":{"required":true,"noInvalid":true,"maxlength":90,"minlength":2 } } } I suppose I should either go back to creating it directly from PHP, or maybe get rid of my ternary operator, and go with: { "rules":{ "name":{"required":true,"noInvalid": "{{ noInvalid }}", "maxlength":90,"minlength":2 } } } Problem is to make the original file valid JSON, I need to put quotes around my variables which might cause problems with Boolean values { "rules":{ "name":{"required":true,"noInvalid": "1", "maxlength":90,"minlength":2 } } }
  3. Thanks for your reply QuickOldCar, As for more information, the text will be parsed as described by http://forums.phpfreaks.com/topic/291400-constructive-criticism-on-parsing-text/. So, store a big array in a single file to find all the time stamps? What if there were a million elements? Would checking if a file exists be faster? I suppose I will have problems seeing if one of a million files exists as well??? Why would I need to save the hash somewhere other than as the filename? Wouldn't I just parse and save the file with name $md_filename, and then the next filename/array I get, hash it and check if the file exists? Thanks again $filename="bla bla.txt"; $array=array('a'=>123,'b'=>'Hello'); $string=$filename.serialize($array); $md_filename=md5($string); //Save file using this name
  4. I need to parse some text similar to Twig templates, but MUCH more limited and error detection is not required. My reason for not using Twig is Twig seems overkill. All it needs to do is replace variables and simple ternary operators (unlike Twig, the ternary operators use ! instead of "not"). I would welcome any constructive criticism and/or recommended changes on how I implemented it. Thanks <?php date_default_timezone_set('America/Los_Angeles'); ini_set('display_errors', 1); error_reporting(E_ALL); /* Replaces all values surrounded by {{ }} deliminators. Handles direct variable. Multiple variables can be separated by the ~ symbol. Also does (non-nested) ternary operators: x?y, !x?y, x==1?y, x?'y', x?y:z */ $template=' Test1 Hello {{ firstname }} {{ lastname }}. Call me in {{ days_int }} or {{ days_string }} days.<br> Test2 {{ flag_int?"do this2" }}<br> Test3 {{ flag_int?"do this3":"do that3" }}<br> Test4 {{ value_int==5?"do this4" }}<br> Test5 {{ value_int==5?"do this5":"do that5" }}<br> Test6 {{ value_int==4?"do this6" }}<br> Test7 {{ value_int==4?"do this7":"do that7" }}<br> Test8 {{ value_int!=5?"do this8" }}<br> Test9 {{ value_int!=5?"do this9":"do that9" }}<br> Test10 {{ value_int!=4?"do this10" }}<br> Test11 {{ value_int!=4?"do this11":"do that11" }}<br> Test12 {{ value_int!=4 bla "do this12":"do that12" }}<br> Test13 {{ value_int==5?"do this5 to "~firstname:"do that5 to "~firstname }}<br> Test14 {{ !flag_int?"do this14" }}<br> Test15 Hello {{ firstname~" "~lastname~". How are things" }}.<br> '; $values=array( 'firstname'=>'John', 'lastname'=>'Doe', 'days_int'=>5, 'days_string'=>6, 'flag_int'=>true, 'value_int'=>5 ); $parser=new parser(); echo($parser->parse($template,$values)); class parser { public function parse($template,$values) { return preg_replace_callback('/\{\{\ (.+?)\ \}\}/',function ($matches) use ($values) { $ternary = explode("?", $matches[1]); if(count($ternary)>1) { //Ternary operator. $ternary[0] is the condition and $ternary[1] is the resulting value(s) $conditions=explode("==", $ternary[0]); if(count($conditions)>1){ //Equal Condition $cond=($this->getVal($conditions[0],$values)==$this->getVal($conditions[1],$values)); } else { $conditions=explode("!=", $ternary[0]); if(count($conditions)>1){ //Not Equal Condition $cond=!($this->getVal($conditions[0],$values)==$this->getVal($conditions[1],$values)); } else { //A flag $cond=($conditions[0]== "!") ? !($this->getVal(ltrim($conditions[0],'!'),$values)) : ($this->getVal($conditions[0],$values)); } } $options=(explode(':',$ternary[1])); return $cond?$this->getValues($options[0],$values):(isset($options[1])?$this->getValues($options[1],$values):null); } else {return $this->getValues($matches[1],$values);} }, $template); } private function getVal($s,$values) { return in_array($s[0],array('\'','"'))?substr($s,1,strlen($s)-2):(isset($values[$s])?$values[$s]:$s); } private function getValues($strings, $values){ $s=null; foreach(explode('~',$strings) as $string){ $s.=$this->getVal($string,$values); }; return $s; } } ?>
  5. I have the following script. doThis() is only used for this single use. Should I use an anonymous function instead? Reasons why or why not (i.e. speed, doesn't use up a function name, etc)? How should is it be implemented? Thanks $a=array(10,20,30); for ($x=0; $x<=10; $x++) { $z.=doThis($x,$a[1],50); } function doThis($a,$b,$c) {return $a+$b+$c;}
  6. I learned every one of them the hard way
  7. I have some fairly small text files (2K) which are parsed where certain deliminated fields are replaced with values provided in an associated array. There will typically be less than 5 replaced fields, and I plan on using preg_replace_callback to find and replace them. I am contemplating caching the files after being parsed (note that they will only be accessed by PHP, and not directly by Apache). Do you think doing so will provide any significant performance improvement? If I do go this route, I would like thoughts on how to proceed. I am thinking something like the following: Append the filename along with the serialized value of the array, and hash it using md5(). Store the parsed file using name "file_".$hash Get the modification time of the newly created file using filemtime(), and store the value in a new file called "time_".$hash. bla bla bla When the next request comes in to parse a file, create the hash again. If the file exists for the given hash name, and the time file matches filemtime(), use that file, else parse the original file. Is this a good approach?
  8. I don't want three rule sets, I only want one. I've had a difficult time keeping my client side and server side rules in sync, and wanted only to define them only once and have them apply to both. Is this not a common need, or am I unique? I therefore created a PHP class which accepts a valid JSON file which describes rules, messages, and sanitizing requirements. It has one public method which will create the object required for the jQuery validation plugin (rules and messages only), and a second public method which will server-side sanitize and validate the data, and provide any error messages if applicable. It also has a bunch of private methods which mimic the jQuery validation plugins methods. When the page is displayed, the controller will use the class to get the object required by the jQuery validation plugin, and send it to the client. When the form is submitted, the controller will use the class to sanitize the data and validate it per the rules, and get any error messages. It obviously deals which the rules with callbacks differently as needed. It works as intended. In regards to using "hacks like embedding JavaScript code within strings (which you appearently do). But that's a very poor solution.", okay I can accept that I should be doing something differently. My dilemma is how should I do so?
  9. Hi again, Anyone? I am just trying to utilize server generated client script the "right" way. Really the same question asked in http://forums.phpfreaks.com/topic/291241-how-best-to-send-php-data-to-a-javascript-client/, however, that post did not give any context, and thus the recommended solutions do not work as I indicate in this post (cannot include callbacks in JSON retrieved using Ajax). Thanks
  10. No experience with MVP and Cricket, but do have some general experience, and recommend the following: Spend some time up front to truly determine your user requirements, else you will find yourself going back and changing your database schema. Mocking up your pages will both help with your HTML/CSS as well as allow you to better understand your data requirements. After you fully understand your user requirements, spend some developing your database schema or you will find your self going back and changing your application. If you really understand "normalization", read up on it. And only after you have a good database schema, start your application. I would recommend a simple MVC design pattern. Don't use someone else's, but just make your own simple one. Use a single entry point into your site (index.php) where additional data is included in the URL or Post. Consider OOP. Use prepared statements and PDO! Strongly consider a template engine. I like Twig. Have fun!
  11. I wish to create validation rules once which are used both on the client and on the server. For instance, I will start off with the following PHP object: stdClass Object ( [rules] => stdClass Object ( [email] => stdClass Object ( [required] => 1 [email] => 1 [remote] => stdClass Object ( [url] => check-email.php [type] => post [data] => stdClass Object ( [username] => function() {return $( '#username' ).val();} ) ) ) ) [messages] => stdClass Object ( [email] => stdClass Object ( [required] => an email is required ) ) ) When the edit page is downloaded to the client, I will include this object in some format suitable to the client. The client will then use the jQuery Validation plugin (http://jqueryvalidation.org/) along with the validation object, and client side validate the page. When the form passes client side validation and is uploaded, PHP will use the same validation object to serverside validate the form (I have this part working as desired). My question is how should I pass this data to the client? Originally, I would just use PHP to write some JavaScript. exit('var myObj='.json_encode($myObj)); Note that when I json_encode the object, the value of $myObj->rules->email->remote->data->username is a string with quotes around it, however, I can easily use PHP to strip these tags before sending it to the client. As Jacques1 pointed out in http://forums.phpfreaks.com/topic/291241-how-best-to-send-php-data-to-a-javascript-client/, I should never ever use PHP to generate JavaScript, and should use AJAX to download the JSON directly. I tried doing the later, but found that a callback function could not be included in the JSON. Please advise on the best way to accomplish this. Thank you
  12. Thanks Jacques1, I see your point. Maybe with great effort I can prevent it, but why bother and just do it right the first time. I definitely crossed outside of the scope of PHP, however, still would appreciate comments on the following scope. How do we know myObj.myProp is defined when someFastScriptWhichAccesses_myObj.myProp.js is executed? <!DOCTYPE html> <html> <head> <title>Example</title> <script type='text/javascript'> var myObj={}; $.get( "someSlowURL.php", function( data ) { myObj.myProp=data; }, "json" ); </script> <script src="someFastScriptWhichAccesses_myObj.myProp.js" type="text/javascript"></script> </head> <body></body> </html>
  13. Yes, I know the nightmare of dynamically generated JavaScript. I remember doing it and thinking I was so smart. I soon learned the error of my ways. The limited dynamically generated JavaScript used to populate a variable has much less of the troubleshooting issues, however, I expected it wasn't best practice thus asked the question. Just curious, on this limited use of just setting a variable, what are the security vulnerabilities? Will Ajax's asynchronous behavior cause problems? I might have script in other files that needs access to the object, thus putting it in a callback will not be so simple.
  14. The client later uses the data to perform various given tasks. For instance, maybe the myObj consists of ten arrays. User clicks the "three" button, and the data in array 3 is displayed. So, my JavaScript needs to be able to access myObj.array3. My thought of doing it this way instead of individual Ajax calls upon each click is that they will be clicked more than once on a given page load, and I want to reduce the calls to the server. header("Content-type: text/javascript"); $myObj=array( 'array1'=>array(1,2,54,213,54), 'array2'=>array(8,4,213,54), 'array3'=>array(4,2,54,213,54), ... 'array10'=>array(77,2,54,23,54) ); exit('var myObj='.json_encode($myObj));
  15. I am successfully doing this, however, I believe I am doing it wrong. I am currently doing the following. How should I be doing this? My thought is getObject.php should return JSON, not JavaScript, but I don't know how to assign the received JSON to the myObj variable. Thanks PS. If there is a special way to do so when using Twigs, please advise. <script type='text/javascript' src='getObject.php?id=123'></script> <script type='text/javascript'> console.log(myObj); </script> getObject.php header("Content-type: text/javascript"); $myObj=array('foo'=>'bar'); //Actually, queries DB using $_GET['id'], and gets a bunch of data exit('var myObj='.json_encode($myObj));
  16. For me, the best teacher is an example. Try out the following script. Submit the form and click the links. See what happens when you follow the name with square brackets. You are correct in your use of GET. Typically, you want to use GET when you are getting something from the server, and POST when you are changing something on the server. <?php $url=htmlspecialchars($_SERVER['PHP_SELF']); echo("GET:<pre>".print_r($_GET,1)."</pre> POST:<pre>".print_r($_POST,1)."</pre> <hr> <form action='{$url}' method='post'> <input name='p1' type='text' value='value for p1' /> <input name='p2' type='text' value='value for p2' /> <input name='p3' type='text' value='value for p3' /> <input name='p_array[]' type='text' value='value for p1_array' /> <input name='p_array[]' type='text' value='value for p2_array' /> <input name='p_array[]' type='text' value='value for p3_array' /> <input name='submit' type='submit' value='SUBMIT' /> </form> <ul> <li><a href='{$url}?g1=123&g2=321'>link 1</li> <li><a href='{$url}?g_array[]=123&g_array[]=321'>link 1</li> </ul>"); ?>
  17. No, I don't insist. Just adapting to a new way of looking at things. In reflect, I agree they shouldn't come from the controller. Again, I am looking at things differently, and it takes a bit of time it to sink in. I am stronly leaning towards templates being a good thing unless you have a site with one million hits per hour in which you have no problems. I posted a related post at http://forums.phpfreaks.com/topic/291199-recommended-application-structure/, and would appreciate any comments. Thanks
  18. I typically structure my applications something like the following. I lump general functionality into a given component. For instance, I might have com_users component which deals with user administration, and implements the ability to view a list of users, view a given user, delete a user, edit a user, etc. This structure was borrowed long ago from my learning PHP Joomla days which I no longer use. index.php figures out which component is being accessed, evokes the controller which gets data from the model and sends the data to the view. The view defined in each component only deals with the central content, and mainTemplate.php deals with the peripheral. First question. Is there anything inherently wrong with this approach? Second question. I am looking to start using Twig. Would this same structure work? I would replace /var/www/html/lib/templates/mainTemplate.php with a Twig file, and replace var/www/components/component1/views/view-1-1.php, etc with Twig files which extends the main Twig template. /var/www/components/component1/controllers/controller-1-1.php /var/www/components/component1/controllers/controller-1-2.php /var/www/components/component1/models/model-1-1.php /var/www/components/component1/views/view-1-1.php /var/www/components/component2/etc/etc /var/www/html/lib/templates/mainTemplate.php /var/www/html/lib/templates/mainCSS.css /var/www/html/lib/js/someJSforAllComponents.js /var/www/html/lib/components/component1/js/someJSForComponent1.js /var/www/html/index.php
  19. Hi Guy, You should learn MySQL. It doesn't take much time to learn the basics. For a totally new subject, I like the In Easy Steps books. They have one for MySQL and PHP, but I don't know if they are out of date. Regardless, you get throught them in a couple of hours, and won't know everything, but will know the basics. If you want to get more into writing queries, the Simple SQL book is good. If you still want to wait, you could always create an array or object which mimics the output of MySQL. For insteand, create the following array. Then use it to practice your loops, etc. $fakeDBoutput=array( array(3,"hello"), array(5,"hello"), array(7,"hello"), array(8,"hello"), );
  20. Thanks again Jacques1, I see your point regarding HTML in the PHP script for a select menu, etc. How do you handle this? Previously, I would pass an array of options along with the selected value, and use a function to create a select menu. Could I and should I do something similar with Twig? Also, what about passing an array of JS/CSS/etc filenames from the controller to the Twig view? While I don't see a way around it, it goes against keeping the controller totally isolated from presentation content.
  21. Thanks Jacques1, Yes, I knew you used Twig, but didn't know whether you just did the backend portion, and had someone else do the frontend template work. Just curious, but do you use Syphony2 as well? I've obviously looked at the Twig documentation, but I haven't found any tutorial describing typical application-wide design patterns. My current thoughts (which might be wrong) are that I should make one general page template which includes the HTML, HEAD, BODY tags and other general content. I would then extend this template to be more specific. I will pass an array listing external JS/CSS/etc resources to the template which would in turn insert them in the HEAD. I am uncertain whether I will use PHP directly to create navigation menu and select option HTML and pass these to the template, or have the template create them from an array, or maybe there is some other approach altogether (thoughts?). I could also use a second general template to render large HTML blocks requested from Ajax on the rare occasions that I don't want to just send back JSON. I would appreciate any comments. Also, if you know of a good article/book/blog/etc, please let me know. Thanks
  22. Quick question for you Jacques1. Do you actually ever use twigs, or do you just work on the backend side?
  23. I've messed around with twig a bit. Haven't made up my mind yet, however, I really do like the inheritance feature.
  24. I'm a little confused. I don't see any PDO, and your script seems to be unrelated to your questions. Normally, you would create a list with a bunch of links. Each link would be something like <a href="index.php?task=getItem&id=123 />Item 123</a>. Your server would then implement the getItem task and use the ID to create the page.
×
×
  • 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.