Generic Constants File for PHP and JavaScript

How do guys suggest sharing a constant file between PHP and JavaScript so that they don’t repeat the code? Xml file? I assume mixing javascipt inside PHP would not be the right solution !? thanks

+4
source share
3 answers

http://php.net/manual/en/book.json.php

I would say using json. It is native to javascript, and there is a parser library for php.

consider the following:

JSON:

{constants : { var1 : "value 1", var2 : "value 2", var3 : "value 3"}} 

and then read it in php:

 $const = json_decode(json_string); 

This gives you a $ const object with properties such as $ const β†’ {'var1'} that returns a value of "1".

in javascript this will be:

 var const = eval(json_string); 

and will give you const.constants.var1 == "value 1".

The simplest real-world implementation for js:

 <script type="text/javascript" src="json_constants_file.js"></script> 

When you add html output, you instantly have a const object with other objects as its children.

+4
source

The configuration variables that will be used by both PHP and JavaScript can easily be saved as XML, yes. However, JSON may be the best solution, since it requires minimal effort for analysis - JS processes it initially, and PHP turns it into an array with json_decode .

0
source

You can try my approach. I created a generic configuration file for use with php and js files.

Check out this trick:

PHP class configuration file:

 <?php /** Class Start **/ class Config { /********************************/ /* Page Config Info */ /********************************/ // page title const PAGE_TITLE = 'Welcome in Code Era!'; // base url const BASE_URL = 'http://www.myapp.com/'; /********************************/ /* Database Config Info */ /********************************/ // mysql host server const SERVER = '10.102.23.141'; // database user name const USER = 'root'; // database password const PASSWORD = ''; // mysql database name const DATABASE = 'sample'; /********************************/ /* Share Message */ /********************************/ // Facebook Share Message const FB_SHARE_MESSAGE = 'This gonna my share message'; // Facebook Share Title const FB_SHARE_TITLE = 'This gonna my share title'; // Facebook Share Caption const FB_SHARE_CAPTION = 'This gonna my share caption'; } /** Class End **/ ?> 

JavaScript file:

 // global config var var config = {} || '' || null; /** * Get Config data with Ajax Response Data * custom ajax method * return ajax response and use/store as javascript var * extend jQuery Ajax and change it * @param qs -> query string {q:value} * @returns result mix|multitype */ $.extend({ getConfig : function (qs) { var result = null; $.ajax({ url : 'GetConfig.php', type : 'POST', data : qs, dataType : "json", async : false, success : function (data) { result = data; }, error : function ajaxError(jqXHR, exception) { if (jqXHR.status === 0) { alert('Not connected.\nVerify your network.'); } else if (jqXHR.status === 404) { alert('The requested page not found. [404]'); } else if (jqXHR.status === 500) { alert('Internal Server Error [500].'); } else if (exception === 'parsererror') { alert('Requested JSON parse failed.'); } else if (exception === 'timeout') { alert('Time out error.'); } else if (exception === 'abort') { alert('Ajax request aborted.'); } else { alert('Uncaught Error.\n' + jqXHR.responseText); } } }); return result; } }); // Collect all Class Constant data on page load var CONFIG = (function() { var private = $.getConfig({config_item : ''}); return { get: function(name) { return private.data[name]; } }; })(); /** * Facebook Share Content example code * with using class constant */ function fbShare() { var feed = { method : 'feed', link : CONFIG.get('BASE_URL'), name : CONFIG.get('FB_SHARE_TITLE'), caption : CONFIG.get('FB_SHARE_CAPTION') }; function callback(response) { if (response && response.post_id !== undefined) { alert('Thank you for sharing the content.'); } } FB.ui(feed, callback); } 

How to use in JavaScript:

 var fbShareMessage = CONFIG.get('FB_SHARE_MESSAGE'); 

Without an example function CONFIG.get:

 var fbShareMessage = $.getConfig({config_item : 'FB_SHARE_MESSAGE'}).data; 

PHP Code for GetConfig.php File:

 <?php /** * Get Config php file * request a config item from javascript/ajax * return json data */ // check request with ajax only if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { exit; } // include class config require_once '../class/class.config.php'; // get all constant from class config $configConstant = new ReflectionClass('Config'); // store as array in var $configConstantArray = ($configConstant->getConstants()); // safe and private request item $black_list_constant = 'SERVER|USER|PASSWORD|DATABASE'; $black_list_object = explode('|',$black_list_constant); // make return jason format $result = array(); // get action from ajax $action = $_POST['config_item']; switch ($action) { case '': $result["status"]= TRUE; foreach ($black_list_object as $index => $value){ if(array_key_exists($value, $configConstantArray)){ unset($configConstantArray["$value"]); } } $result["data"]= $configConstantArray; $result["msg"]= 'Response 200 OK'; echo json_encode($result); break; default: // check valid action if(array_key_exists($action,$configConstantArray) && in_array($action,$black_list_object)){ $result["status"]= FALSE; $result["data"]= null; $result["msg"]= 'Response 201 FAIL'; echo json_encode($result); }else{ $result["status"]= TRUE; $result["data"]= $configConstantArray["$action"]; $result["msg"]= 'Response 200 OK'; echo json_encode($result); } break; } 

What is it. Hope this helps someone :)

0
source

Source: https://habr.com/ru/post/1308999/


All Articles