<pedrocorreia.net ⁄>
corner
<mySearch ⁄> <mySearch ⁄>

corner
 
corner
<mySnippets order="rand" ⁄> <mySnippets order="rand" ⁄>

corner
 
corner
<myContacts ⁄> <myContacts ⁄>

<email ⁄>


pc@pedrocorreia.net

<windows live messenger ⁄>


pedrojacorreia@hotmail.com

<myCurriculum type="pdf" ⁄>


Download
corner
 
corner
<myBlog show="last" ⁄> <myBlog show="last" ⁄>

corner
 
corner
<myNews show="rand" ⁄> <myNews show="rand" ⁄>

corner
 
corner
<myNews type="cat" ⁄> <myNews type="cat" ⁄>

corner
 
corner
<myQuote order="random" ⁄> <myQuote order="random" ⁄>

corner
 
corner
<myPhoto order="random" ⁄> <myPhoto order="random" ⁄>

<pedrocorreia.net ⁄>
corner
 
corner
<myAdSense ⁄> <myAdSense ⁄>

corner
 
corner
<myVisitorsMap ⁄> <myVisitorsMap ⁄>

corner
 
 

<Export class Constant and Static properties to, but not only, Javascript ⁄ >




clicks: 17829 17829 2010-12-28 2010-12-28 goto mySnippets mySnippets php  Download  Bookmark This Bookmark This



Here's a quick snippet to show a simple way to export a specific class Constant and Static properties.

For instance it will allow us to use in JavaScript some PHP values. Let's just suppose you have, in PHP, a configuration Class.

That Class will have settings such as: Language Strings; folders; pagination settings; and so on; and so on; basically it will hold what configuration Class's for.


So you have all those settings in a server-side file and you want to use all (or partial) those settings in client-side. You have at least two ways to achieve that:

  • Auto-generate the JavaScript file;

  • Use Ajax and load the settings;


I'll focus the first option, in this snippet.



class.ConfigurationSettings.php. Here's a rather simple configuration setting file. In here I mixed Static and Constant properties
  1. <?php
  2. /**
  3. * Configuration Settings example file
  4. *
  5. * Contains static and constants
  6. *
  7. * @author pedrocorreia.net
  8. */
  9. class ConfigurationSettings{
  10.  
  11. const LANG_ADD_RECORD = "Add Record";
  12. const LANG_REMOVE_RECORD = "Remove Record";
  13. const LANG_UPDATE_RECORD = "Update Record";
  14.  
  15. const TBL_WORKERS_DATA = "workers_data";
  16. const TBL_WORKERS_DATA_PK = "pk_worker";
  17.  
  18. static $_SIGNUP_LIMIT = "2012-01-01";
  19. static $_SIGNUP_MAX_SEATS = 500;
  20. }
  21. ?>





Events.js, this file's responsible for events management, that is, our page has elements and those elements will react to events/ triggers, with this class we'll be able to add or remove events, such as onchange, onload, etc, etc.
  1. /**
  2. * Manage Events
  3. *
  4. * @see http://ejohn.org/projects/flexible-javascript-events/
  5. */
  6. var Events = function(){
  7. var
  8. _add = function(obj, type, fn) {
  9. if ( obj.attachEvent ) {
  10. obj['e'+type+fn] = fn;
  11. obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
  12. obj.attachEvent( 'on'+type, obj[type+fn] );
  13. }
  14. else{ obj.addEventListener( type, fn, false ); }
  15. },
  16. _remove = function(obj, type, fn){
  17. if ( obj.detachEvent ) {
  18. obj.detachEvent( 'on'+type, obj[type+fn] );
  19. obj[type+fn] = null;
  20. }
  21. else{ obj.removeEventListener( type, fn, false ); }
  22. };
  23. return {Add: _add, Remove: _remove}
  24. }();












class.ExportSettings.php, our main class. It will allow export all the info that we want, for example, we'll be able to only export Static and/or Constant properties and based in a prefix, ie, let's just export settings started with "LANG"; it will also gives the chance to get the values in an Array or Json format;
  1. <?php
  2. /**
  3. * Export a given Class, Constants and/ or Static properties
  4. *
  5. * @author pedrocorreia.net
  6. */
  7. class ExportSettings{
  8.  
  9. private static $_allowed_prefix = array();
  10.  
  11. /**
  12. * Export settings to an Array
  13. *
  14. * @param Object Class
  15. * @param Integer Type: { 1: Constants and Static (default); 2: Only Constants; 3: Only Static }
  16. * @param Optional Array Restrict allowed prefixes to export
  17. * @return Array
  18. */
  19. public static function ToArray($class, $type = 1, $allowed_prefix = null){
  20. $self = new ReflectionClass($class);
  21.  
  22. $allowed_prefix = ($allowed_prefix && !is_array($allowed_prefix)) ? array($allowed_prefix) : $allowed_prefix;
  23. $type = (!$type || !is_numeric($type)) ? 1 : $type;
  24. self::$_allowed_prefix = $allowed_prefix;
  25.  
  26. switch ($type){
  27. case 1: //export constants and static properties
  28. $arrProperties = array_merge($self->getConstants(), $self->getStaticProperties());
  29. break;
  30. case 2: //export only constants
  31. $arrProperties = $self->getConstants();
  32. break;
  33. case 3: //export only static properties
  34. $arrProperties = $self->getStaticProperties();
  35. break;
  36. }
  37.  
  38. return array_intersect_key(
  39. $arrProperties,
  40. array_flip(
  41. array_filter(
  42. array_keys($arrProperties), array("self", "filter_array_by_key"))
  43. )
  44. );
  45. }
  46.  
  47. /**
  48. * Export settings to json format
  49. *
  50. * @param Object Class
  51. * @param Optional Integer Type: { 1: Constants and Static (default); 2: Only Constants; 3: Only Static }
  52. * @param Optional Array Restrict allowed prefixes to export
  53. * @return Object Json
  54. */
  55. public static function ToJson($export_class, $type = 1, $allowed_prefix = null){
  56. return json_encode(self::ToArray($export_class, $type, $allowed_prefix));
  57. }
  58.  
  59. /**
  60. * Export settings to json format, allowing it to declare a Javascript variable
  61. *
  62. * @param Object Class
  63. * @param String Json variable name
  64. * @param Integer Type: { 1: Constants and Static (default); 2: Only Constants; 3: Only Static }
  65. * @param Array Restrict allowed prefixes to export
  66. * @return String Json javascript variable declaration
  67. */
  68. public static function ToJsonVariable($export_class, $json_var, $type = 1, $allowed_prefix = null){
  69. return sprintf("var %s = %s;", $json_var, self::ToJson($export_class, $type, $allowed_prefix));
  70. }
  71.  
  72. /**
  73. * Filter key prefixes
  74. *
  75. * @param String Filter
  76. * @uses self::$_allowed_prefix
  77. * @return Boolean
  78. */
  79. private static function filter_array_by_key($key){
  80. $found = false;
  81. if(is_array(self::$_allowed_prefix)){
  82. for ($i=0, $count=sizeof(self::$_allowed_prefix); $i<$count; $i++){
  83. if(substr_compare(self::$_allowed_prefix[$i], $key, 0, strlen($key))===0){
  84. $found = true;
  85. break;
  86. }
  87. }
  88. }
  89. else { //no filter was specified, therefore, all keys are valid
  90. $found = true;
  91. }
  92.  
  93. return $found;
  94. }
  95. }
  96. ?>





Now let's just really build the script to export and read those entire settings



export_settings.php, let's generate the JavaScript file. Then we'll just have to load it in a <script type="text/javascript" src="..." /> tag
  1. <?php
  2. /**
  3. * Generate javascript file using Json format
  4. * @author: pedrocorreia.net
  5. */
  6. require_once("../../_Class_/class.ExportSettings.php");
  7. require_once("../../_Class_/class.ConfigurationSettings.php");
  8.  
  9. echo
  10. ExportSettings::ToJsonVariable(ConfigurationSettings, "settings_all", 1),
  11. "\r\n\r\n",
  12. ExportSettings::ToJsonVariable(ConfigurationSettings, "settings_constants", 2),
  13. "\r\n\r\n",
  14. ExportSettings::ToJsonVariable(ConfigurationSettings, "settings_static", 3);
  15. ?>



Based on class.ConfigurationSettings.php, this will be the code generated by export_settings.php (as you can easily see, in Json format):

var settings_all = {
  "LANG_ADD_RECORD":"Add Record",
  "LANG_REMOVE_RECORD":"Remove Record",
  "LANG_UPDATE_RECORD":"Update Record",
  "TBL_WORKERS_DATA":"workers_data",
  "TBL_WORKERS_DATA_PK":"pk_worker",
  "_SIGNUP_LIMIT":"2012-01-01",
  "_SIGNUP_MAX_SEATS":500
};

var settings_constants = {
  "LANG_ADD_RECORD":"Add Record",
  "LANG_REMOVE_RECORD":"Remove Record",
  "LANG_UPDATE_RECORD":"Update Record",
  "TBL_WORKERS_DATA":"workers_data",
  "TBL_WORKERS_DATA_PK":"pk_worker"
};

var settings_static = {"_SIGNUP_LIMIT":"2012-01-01","_SIGNUP_MAX_SEATS":500};






Init.js, an example showing how to use the Json generated in export_settings.php
  1. /**
  2. * Read json object, in this example we'll only output it to a html div,
  3. * but you can use it, just like a regular json object
  4. *
  5. * @author: pedrocorreia.net
  6. */
  7. Events.Add(window, "load", function(){
  8. var _output = [];
  9.  
  10. _output.push("settings_all.LANG_ADD_RECORD = " + settings_all.LANG_ADD_RECORD);
  11. _output.push("<br/>settings_all._SIGNUP_LIMIT = " + settings_all._SIGNUP_LIMIT);
  12.  
  13. _output.push("<br/><br/>settings_constants.LANG_ADD_RECORD = " + settings_constants.LANG_UPDATE_RECORD);
  14. _output.push("<br/>settings_constants.TBL_WORKERS_DATA = " + settings_constants.TBL_WORKERS_DATA);
  15.  
  16. _output.push("<br/><br/>settings_static._SIGNUP_MAX_SEATS = " + settings_static._SIGNUP_MAX_SEATS);
  17. _output.push("<br/>settings_static._SIGNUP_LIMIT = " + settings_static._SIGNUP_LIMIT);
  18.  
  19. _output.push("<br/><br/> <b>All Values in \"settings_all\"</b><br/>");
  20. for(key in settings_all){ _output.push("settings_all." + key + " = " + settings_all[key] + "<br/>"); }
  21.  
  22. document.getElementById("javascript_console").innerHTML = _output.join("");
  23. });










We already saw a way to use the configuration settings in JavaScript (I can say that this was the main goal), but we can use it in PHP also.

In the following example we'll use all the previous files. We'll include the export_settings.php (that will generate the settings file in JavaScript format); Init.js that will output JavaScript variables.


There will be two placeholders in this example, on which will show the JavaScript settings; and another that will output the PHP values.


example script
  1. <?php
  2. require_once("_Class_/class.ExportSettings.php");
  3. require_once("_Class_/class.ConfigurationSettings.php");
  4. ?>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  6. <html xmlns="http://www.w3.org/1999/xhtml" >
  7. <head>
  8. <title></title>
  9. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  10. <script type="text/javascript" src="_Assets_/Javascript/export_settings.php"></script>
  11. <script type="text/javascript" src="_Assets_/Javascript/Events.js"></script>
  12. <script type="text/javascript" src="_Assets_/Javascript/Init.js"></script>
  13. </head>
  14. <body>
  15. <strong>Javascript Console</strong><br/>
  16. <div id="javascript_console"></div>
  17.  
  18. <br/><br/>
  19. <strong>PHP output Console</strong><br/><br/>
  20. <div id="php_console">
  21. <?php
  22. echo
  23. "<strong>Export <u>All</u> object properties, with prefix \"LANG\"</strong>",
  24. "<pre>", print_r(ExportSettings::ToJson(ConfigurationSettings, 1, "LANG"), 1), "</pre>",
  25.  
  26. "<br/><strong>Export only <u>Static</u> properties with prefix \"_SIGNUP\" and/or \"TBL\"</strong>",
  27. " (in this case \"TBL\" properties are Constants, ie, won't be exported)",
  28. "<pre>", print_r(ExportSettings::ToJson(ConfigurationSettings, 3, array("_SIGNUP", "TBL")), 1), "</pre>",
  29.  
  30. "<br/><strong>Export Array with <u>All</u> settings</strong>",
  31. "<pre>", print_r(ExportSettings::ToArray(ConfigurationSettings), 1), "</pre>";
  32. ?>
  33. </div>
  34. </body>
  35. </html>




This will be the output:



Javascript Console
settings_all.LANG_ADD_RECORD = Add Record
settings_all._SIGNUP_LIMIT = 2012-01-01

settings_constants.LANG_ADD_RECORD = Update Record
settings_constants.TBL_WORKERS_DATA = workers_data

settings_static._SIGNUP_MAX_SEATS = 500
settings_static._SIGNUP_LIMIT = 2012-01-01

All Values in "settings_all"
settings_all.LANG_ADD_RECORD = Add Record
settings_all.LANG_REMOVE_RECORD = Remove Record
settings_all.LANG_UPDATE_RECORD = Update Record
settings_all.TBL_WORKERS_DATA = workers_data
settings_all.TBL_WORKERS_DATA_PK = pk_worker
settings_all._SIGNUP_LIMIT = 2012-01-01
settings_all._SIGNUP_MAX_SEATS = 500


PHP output Console

Export All object properties, with prefix "LANG"

{"LANG_ADD_RECORD":"Add Record","LANG_REMOVE_RECORD":"Remove Record","LANG_UPDATE_RECORD":"Update Record"}


Export only Static properties with prefix "_SIGNUP" and/or "TBL" (in this case "TBL" properties are Constants, ie, won't be exported)

{"_SIGNUP_LIMIT":"2012-01-01","_SIGNUP_MAX_SEATS":500}


Export Array with All settings

Array
(
      [LANG_ADD_RECORD] => Add Record
      [LANG_REMOVE_RECORD] => Remove Record
      [LANG_UPDATE_RECORD] => Update Record
      [TBL_WORKERS_DATA] => workers_data
      [TBL_WORKERS_DATA_PK] => pk_worker
      [_SIGNUP_LIMIT] => 2012-01-01
      [_SIGNUP_MAX_SEATS] => 500
)





If you have any doubt or found any error, please drop me an email.









clicks: 17829 17829 2010-12-28 2010-12-28 goto mySnippets mySnippets php  Download  Bookmark This Bookmark This