开发者

Common constants file for PHP and JavaScript

How do guys suggest to share a constant开发者_JAVA技巧s file between PHP and JavaScript, in order not to repeat code? XML file? I am assuming mixing up javascipt inside PHP would not be the right solution!? Thanks


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

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

consider the following:

json:

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

and then read it into php:

$const = json_decode(json_string);

This gives you the object $const with properties like $const->{'var1'} returning "value 1".

in JavaScript this would be:

var const = eval(json_string);

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

Easiest implementation in real terms for js is:

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

When added the html output you instantly have a constants object with the other objects as its children.


You can try my approach. I have created a common config file to use with php and js file.

Check out this trick:

PHP Class Config 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 CONFIG.get function example:

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;
}

That's it. Hope, it will help to someone :)


Config variables to be shared by both PHP and JavaScript could easily be stored as XML, yes. JSON might be a better solution, though, as it requires minimal effort to parse - JS handles it natively, and PHP turns it into an array with json_decode.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜