Artykuły jmail's software

[PHP] Dane aplikacji [en] Application data in PHP

przez jmail dnia Jan.29, 2010, w PHP / CF / .NET / Java

Everybody who had contact with ColdFusion or ASP.NET knows what is application data, or how usefull they are. Set one variable makes that other users get this variable in the exact same way. All users share data in the same way. If user X set application variable to 1 then all other users will get this var as 1. In this article we try to make the pseudo application data in PHP.


On the beggining we have to anserw one question. For what we will use this?




1. Easy comunication between all requests
2. We don’t want to put everything into the database (or we don’t have data base)
3. Putting into the SESSSION vars grab a lot of disc space on the server when the same amount of the RAM
4. We don’t want to put data into the client computer (in cookies) e.g. license number. Of course we could put the LN on the const variable, but that was only an example. And on other hand changing the const var is not so easy



What conditions our code must meet





1. Give script easy access to the data
2. Easy access to the data from whole script (classes others )
3. Self-saving data
4. Posibility to save data whenever you want


Let’s start!


1. Give script easy access to the data


First we should think about servers without databases. So we shouldn’t put our solution into database. Of course we can do this. That is your own decision, but in our example we’ll use something more flebile. Plain text file! We’ll call this text file application.data. Of course you should give the opportunely rights to access to the file.


2. Easy access to the data from whole script (classes others )


I’ve made some researches and I’ve found out that creation of super-globals vars (like $_SESSION or $_POST) is impossible. Fortunetly PHP gives us some superglobal vars that we could use! $_SESSION var is stored in the data file on the disc and restore when next call to the session comes. That is the problem. We don’t need 100.000 times saved the appdata on the disc if such many users will come.


There is one super-global variable which is created on the script start and removed after the script finished. That is $_ENV variable and we will use it.


3. Self-saving data


There is possible to call php function dynamicly. In futher text I’ll show you how to do this.


4. Posibility to save data whenever you want


Points 3rd and 4th are connected so we will talk about them together


Let’s start from preparing the enviroment


If you could use php_value diractive in .htaccess file put this simply into your’s file

1
2
php_value auto_prepend_file appStart.php
php_value auto_append_file appEnd.php


In appStart.php file we will put everything we need to use our solution, and in the appEnd.php file we will put only the saving of your application data.


If your’s server couldn’t use php_value directive in .htaccess file you must care to include those files into your’s script.


We set two const vars (in php), which will help us in next step

1
2
define('APP_DATA_FILE', 'some/path/application.data');
define('APP_NAME', 'ApplicationName');


Now we will define our application data space

1
$_ENV[APP_NAME] = array();


As we can see the const APP_NAME have been use only for one reason. Initiation of the sub-array in super-global variable $_ENV. Thanks to that we’ve got everything allready done.


Reading of application data

1
2
3
4
5
6
7
8
9
10
11
12
function application_start(){
    if (!file_exists(APP_DATA_FILE)){
        $AppFileHandler = fopen(APP_DATA_FILE, 'w') or die('I can\'t read application data!');
        fclose($AppFileHandler);
    }
    $file = fopen(APP_DATA_FILE, "r");
    if ($file){
        $data = fread($file, filesize(APP_DATA_FILE));
        fclose($file);
    }
    $_ENV[APP_NAME] = unserialize($data);
}


And that’s all! Application data have been set! Now in every place of your script you can use this data in this way

1
$_ENV[APP_NAME]['ApplicationVarName']


You can easily find this solution helpfull. Lets say that application config is written in the file. Of course in standard you will read this file and put the data into the global array config and in every function you need to add on the begining

1
global $config;


If we use this solution we don’t have to do this anymore. No variables wont be putted into the classes, because $_ENV variable is super-global and it is accessible from wherever you want in the script


application_start function we put into the appStart.php file and we are adding in that file also setting of to const variables (which I have mentioned earlier)

1
application_start();


Of course it should be after variables initiation ;)


We have made first two points of our coditions. Now we will make 3rd and 4th point.


I have told earlier about dynamic called functions. It is not a problem to call the function from dynamic name or from variable. Now we need a function which will save our data to the file.


Our function, which will save our application data will look like this:

1
2
3
4
5
6
$data = serialize($_ENV[APP_NAME]);
$file = fopen(APP_DATA_FILE, "w");
if ($file){
    fwrite($file, $data);
    fclose($file);
}


Why I hadn’t but this function in the clause function function_name? Because I would like to make this solution more flexible, and I will put this function into variable to call it whenever I want


Now we fully code our function.

1
2
3
4
5
6
$_ENV['application_func'] = create_function('', '$data = serialize($_ENV[APP_NAME]);
    $file = fopen(APP_DATA_FILE, "w");
    if ($file){
        fwrite($file, $data);
        fclose($file);
    }'
);


So we’ve created the dynamic function. Now it is time to add something to our file appEnd.php. There should be saving our app data to the file, and here you are.

1
$_ENV['application_func']();


Varaibles where saved! What to want more? ;) That is the end of global directive in config passing into the scripts ;)


If you change the application data the best practice is to save them allready after change, calling function which I have shown up from here.


I wish nice work for all developers! I would also like to apologize for my terrible English but I had a long break in using this language ;) I hope you understood everything

:, , ,

3 Komentarze dla tego posta

  • kallosz

    hmm… Ciekawe rozwiązanie ;]
    raczej często nie potrzebujemy stosowania zmiennych globalnych ale na przyszłość – kto wie ;]

  • mateusz93k

    Bardzo ciekawy artykuł. Z pewnością po coś się to kiedyś przyda, jednak na razie nie mam pomysłu na zastosowanie tego gdzieś u siebie :)

  • jmail

    najprostsze wykorzystanie.

    Prosta sytuacja. User Ci zgłasza, ze mu się długo wykonywał skrypt. Nie wiesz kiedy nie wiesz dlaczego i tak dalej ;)

    robisz sobie zmienne

    $_ENV[APP_NAME]['script_time']
    $_ENV[APP_NAME]['script_time_when']

    i dostawiasz do zapisu

    1
    2
    3
    4
    5
    if($script_execution_time > $_ENV[APP_NAME]['script_time']){

    $_ENV[APP_NAME]['script_time'] = $script_execution_time;
    $_ENV[APP_NAME]['script_time_when'] = time();
    }

    i już wiesz kiedy i ile najdłużej wykonywał się skrypt. Teraz możesz z logami porównać co w tym czasie jeszcze się działo na serwerze. Jeżeli do bazy byś chciał to zapisywać to:
    a/ miałbyś dużą tabelę w bazie :F
    b/ zużywałbyś niepotrzebne zasoby na połączenie itd.

Zostaw komentarz

Kalendarz

January 2010
M T W T F S S
« Dec   Feb »
 123
45678910
11121314151617
18192021222324
25262728293031