$GLOBALS to store settings?

Asked

Viewed 1,027 times

11

Hi, last week I asked what was the best way to store and read settings for a website, and I got two answers. Of those two answers, there was a lot of speculation, but none really explained why I should use one type and not the other, they just said it was better to do it that way. On the contrary I appreciate the help the staff gave there, and did not want to appear rude. For example in the first answer, I said exclusively to - maintain the exclusive public access configuration - then I blocked it and wondered, if it was physical access or the properties I put in that file ?

On the other hand, one user even commented the following on the different types of settings:

I do not see a security issue but more a matter of practicality for any changes. Yes in my case I use more for practicality. I believe that this kind of need arose for compiled programs, so there is no need to compile the td program once it changes the database configuration (password, user, server address, etc). @Skywalker

I dug deep, and I found an answer in this website, with some significant comparisons, it helped a lot with some doubts that I had, but not all.

After a lot of reading and analysis, I decided to keep the configuration in a file .php, but using a variable global to be able to read them more easily.

$GLOBALS['configuracao'] = array();

Then I can read it anywhere inside my script.

What I got ?

  • A class to read these settings
  • One or more classes that depend on these settings, so they can be used many times (e.g..: mysql,sessoes,cookies and others).

As use ?

  • I’m using OOP to make an old site easier to set up and modify.
  • My reading class only uses these values if I don’t inject another configuration.
  • The method I use to return this value is static.

Because it is a variable global no problem if store my settings in it ? And how specifically I put my configuration data out of public reach ?

  • Have you ever done this? I don’t know if it’ll solve how you’re thinking. I need to leave but I’ll answer when I get back.

  • I’ve done the configuration part, but I don’t know if I leave it that way, because it’s a global variable.

  • This gives a certain fear because it will load in the global variable all the settings and a lot of this data you end up not using all of them in a single page. Do you understand? I’d just be consuming memory. Your application gets heavy and this weighs in your pocket as well because you will need more powerful servers, which cost more. Think of something lean that saves resources. The more you can do with less resources, the better.

  • 3

    The duration of a PHP page is so short that the allocation and displacement in blocks is even more efficient. In PHP, the more direct you go to the point, the greater the use of machine resources. Almost all academic theories are better in programming languages than in script ones, which is the case of PHP (which is not even a common loop, much less persistence of data structures in memory). In this case, you can rest assured, that global will not get in the way of anything. Also, internally, a class is allocated as global. Imagine her members as an array.

  • Thanks for the comment @Bacco.

3 answers

10


In principle it’s okay to do this, I always say, as long as you know what you’re doing. Keep in mind that this will always need to be included in scripts whenever necessary.

The one about software engineering does not recommend the use of global variables, it is a good recommendation, but it is not something mandatory. We need to understand why this recommendation exists, for this there is already a question here that explains the problem. Not knowing why it’s problematic really makes it hard to make decisions, one way or the other. AP is more than right to ask when it has doubts.

PHP

I’m telling you, if you want to apply the best software engineering techniques, don’t use PHP. This is not a language that encourages this, it is very pragmatic and encourages the practicality and flexibility of coding. Of course I’m not talking about throwing everything in the trash and ignoring everything this discipline teaches us, I’m just saying that its use in PHP should be balanced to achieve the language’s goals. Nor am I saying that we can not apply the best engineering techniques in PHP, ssó is not her greatest asset, it shines in other points.

Do like Facebook, change language when you have a very complex code.

On a very large code basis that will be used for a long time, by teams, and that there is an applied methodology that requires a certain discipline, such as the creation and execution of structured tests, it makes a lot of sense to avoid - emphasis on "avoiding" - not just the global state, also the global scope.

But we’re talking about scripts PHP where the code base is usually small, for punctual use and made by a few people, usually just one. And very few people use formal methodologies on these sites, most of them have no idea how to do formal testing, so some reasons to avoid these variables go missing.

Paranoias about memory consumption, data leaks or even abstraction don’t make much sense in something so ephemeral.

Ah, don’t confuse code volume with data volume. PHP can handle large data volume, but it’s not so easy to work with code volume. Luckily it is a language applied on the web that runs small scripts and not a huge volume of code simultaneously. The site is a set of small applications that run independently, is not a monolithic executable, is not all interdependent. Here PHP shines bright.

Of course, websites that deal with large volumes of data have simpler code, are more concrete and less abstract. They avoid OOP. As occurs on this site you are using now. After all OOP is not silver bullet, it assists in specific circumstances. In the wrong hands it can even get in the way.

The solution is widely used

Note that the variable $GLOBALS already exists. Entries will be created for it. So there is already a certain scope. It would be bad to create free variables because they could get confused with local variables, this really is a bad thing.

Another technique used is to create a proper global configuration variable, so only one can be confused with the locations, this well documenting will not cause problems. Just like every PHP programmer knows they can’t use a variable called $GLOBALS, or $_POST, etc. Just agree and document. Does not cause scope problems.

In a certain way this is being done by creating a variable level within $GLOBALS. From what I understand will not be created multiple entries in this variable but multiple entries in the input configuracoes who was raised in $GLOBALS. Great technique to avoid conflicts.

The problems that can happen

Can the configuration have more than one instance one day? I don’t think so.

Will you run formal tests? I doubt it. Even if it is done, it will need to be "mockery"? Even if I have to, you can fix this easily.

Will there be competition? In scripts PHP doesn’t usually have it. If so, will it be written in the settings? It doesn’t look like it. Even if you have, writing needs to occur in the file, which gives to make locking easy.

Will this be used instead of passing parameters to carry variable data across the entire application? It seems not.

The data is global

It is a fact that this is a data that is inherently global, it is needed globally.

Any other alternative will only be a more complicated way to get this global. The solutions that can be presented will only encapsulate the data in another way, but the access will take place in a global way. Or will invent a form that even meets the real needs of this software feature.

Note that in the question linked above shows that there are cases for its use, several softwares use, the best known in PHP use without problems, several very large, some do worse.

For example, Wordpress uses constants that are global. But it’s worse because it creates several global symbols. In general does not cause major problems, Wordpress did a proper way and documented this. But if you don’t know what you’re doing, you can create scope chaos. Of course, even very inexperienced programmers can do it right. But wouldn’t it be better if you didn’t create some global symbol, put it all into something that already exists in the language? After all language has its flaws but she created the $GLOBALS because it is useful, it is not to be set aside by a worse solution.

What alternatives?

Reading a file all the time? Much worse.

Put in a class for global access? Which in the background, in PHP, works analogously to $GLOBALS. Yes, PHP maintains all classes in a global symbol table and its members function as the entries of a array associative. It’s just a matter of syntax, it doesn’t change semantics. Anyone who knows the inner workings of PHP knows this.

What is the advantage of this in simple software that will not even be formally tested?

There is no miracle.

I can make several conceptual criticisms to use this form, but none will be pragmatic, none will take into account the actual way the software is probably being developed.

Server consumption

And do not worry about performance or memory consumption, it will not be worse than the alternatives. And even if it was, it will be insignificant. And more, who needs performance and memory saving uses another language. PHP does not value the server economy, it values the development economy. What some programmers subvert by creating expensive and expensive software to run the same way.

If the software is too heavy and has an absurd amount of configurations, you can create a larger granularity. But if the software is that heavy, then you have to rethink everything, then better engineering techniques are necessary, use a more appropriate language will be necessary.

Don’t forget that this $GLOBALS that is in a file should be loaded with #include. Then you can have several files each with a part of the settings. You only upload what you need. This is the nature of a language script, this is your advantage.

But honestly, the gain is tiny. Anyone who knows how the PHP execution environment works knows that it won’t make any difference. Probably won’t even be able to measure gain, and even if it does, it will be only in measure, not in practice, it’s a silly micro optimization.

Security

This is probably in a file .php It should already be protected against external access, right? If it is, then it’s already protected. Files with this extension can only be executed by the PHP engine and not accessed directly. You just have to be careful not to leave it with writing permission. What may eventually be required in some types of software (not those that are already customized) that allow users to change settings by web. There other cares need to be taken. It does not seem to be the case.

Completion

Don’t make a 6-lane highway to meet a local need.

Fortunately, AP has already concluded that an INI file is not a good one. The best option is to put it in a PHP source file. The best option is to put in a data collection. Classes should be immutable, so a array is the solution. Should you create a new one or use an existing and documented one? So it’s easy to decide $GLOBALS. AP shows that it can research and make an accurate analysis, although in this case the option is quite obvious.

  • 3

    Now that I have seen that the question has been modified. Be careful with this because it may invalidate answers. The min ha even would be different with the current composition of the question. I think this question was compromised. The ideal would be to have put these changes in another question in more detail, probably putting the code to ask for help on how to handle the settings. This already begins to escape the original purpose of the question. Although I think by editing, is already buying the idea of complication. If you want to make it harder, make it harder.

  • 1

    I chose this answer because it seems that no one else will answer or even edit, and this may be the only one that is still within the context.

  • It was understood that despite the global name this variable only exists if it is loaded at the time of the execution of the script and it is not alive naturally throughout the site? In PHP the global is very restricted, so these organizing techniques do not make much sense.

  • The global I speak is that it is accessible even within functions or classes, I just need to place an require or include of the file where I set my data. I will create another question explaining how the values arrive and how I get access to them.

  • I put it here http://answall.com/questions/102652/vari%C3%a1vel-global-personalized

4

This can vary according to your project and will surely always generate a good discussion.

If you are programming structurally, there are other ways to do it, such as constants or vectors in common variables (see that question), but it’s a lot more work to hide it when you’re doing it this way, not to mention that constants have an extra "weight" in their application compared to other variables.

Somehow I personally wouldn’t wear $GLOBALS for configurations because you have to think about your project always with the possibility to expand and give maintenance in the future, regardless of what language you are using and what size your application is.

If you are working object-oriented, you can take advantage of encapsulation to solve this problem, where you will have a class that will read and set the settings, and through the dependency injection will pass these values only to where you want.

Now let’s have your questions.

Because it is a global variable it is OK to store my settings in it ?

Again I say it depends on what you need. You don’t want others to see these settings, but who would see these settings?

If you work with a small script where your passwords are saved in a file, it is very likely that someone can just open the file and see these settings in the same way, such as giving a var_dump() in the variable and see everything, but in relation to the user, if it is not in the script and does not have vulnerabilities that can reveal the content of this variable, then there would be no problem.

And how specifically I put my configuration data out of public reach ?

If you work at a major project, where there are people who are responsible only for the Layout part and they don’t have to know absolutely anything of what goes on "behind" the project, you could be working with classes, so it could have an instance of a configuration class that would pass the values only to where it was needed, which is not the case of the layout, which will receive everything "processed" and clean, will only display the generated content.

Example: We have a configuration class and a database class, you need to pass the settings to the database, see the classes in an extremely simple way only for learning.

class config
{
    private $cfg;
    
    public function __construct()
    {
        // Aqui será a forma que você irá fazer a leitura de suas configs para a variável $this->cfg;
    }
    
    public function get($sessao,$parametro)
    {
        return $this->cfg[$sessao][$parametro];
    }
}

Let’s assume you need to grab the settings to get the user from the database.

class database_mysql
{
    private $cfg
    private $usuario
    
    public function __construct(config $cfg)
    {
        $this->cfg = $cfg;
    }
    
    public function ler_usuario()
    {
        $this->usuario = $this->cfg->get['database','usuario'];
    }
}

So that’s when the dependency injection is performed.

$minha_config = new config();
$meu_db = new database_mysql($minha_config);

Thus, you can only have access to certain settings objects that have access to the class config, and you inject that dependency into whatever object you need.

Is only worth complicating?

This will significantly complicate your project, so it’s up to you to assess whether you really need it. Any project I do I always think about the possibility of maintaining and expanding one day, it’s much better you spend more time and work to do something well done than think "this is too small to worry about it", for when a maintenance comes up and you have to change your whole system, unless you really have absolutely no need to complicate.

It’s completely optional to work object-oriented in PHP, but think about the advantages you can have when you need to maintain or expand your project.

"The developer is focused on what happens when a user presses a button, while an architect is focused on what happens when ten thousand users press a button. " - Paul R. Allen, Joseph J. Bambara -SCEA

But object orientation in PHP?

Don’t fall for that better language, because the best language is the one that meets the requirements of your project, if you can and can do this in a simple and practical way in PHP, or other language, choose the one that suits you best, do not fall into the fashion, which may be better for others, it may not be for you.

Here’s a little statement from Mailchimp about PHP (source).

We use this architecture to process over thirty million emails sent by tens of thousands of users every day, generating tens of millions of bounces, confirmations, clicks, and unsubscribes that need to be handled in near-real time. We process millions more API requests and millions of applications and confirmations every day. Above all, we handle well over 500 million dynamic page views per month. Our back-end systems perform millions of jobs every day, calculating statistics, searching geographic data, and monitoring everything in search of bad behavior and abuse. This is just getting bigger and bigger as we grow 500% or more each year.

We can also mention the thousands of websites running Wordpress (PHP) and including much of Facebook. (source)

Answer to the question

As you edited your question looked like a "new" question, which basically left almost all the answers out of context.

Your initial problem was whether storing settings in $GLOBALS was bad, your current problem after editing is where you can store these settings.

Storing a website settings safely

It’s a couple of problem/solution, there are some standards you can use to safely store your settings.

Solution 1: You can create an INI file and store outside the public folder of your server, a directory above, so anyone who has access only to the famous part of public_http of your FTP will not have access to this file.

Post: PHP provides native methods for reading INI files.

Against: Cannot change as you probably will not have write option, and even if you do, it will not be safe to leave your file with these attributes.

Solution 2: Read your settings normally through a PHP file in a variable using vectors, play for your class and then set a null value for the previous variable.

Post: You won’t need the $GLOBALS, will not be heavy, and the variables defined in the file will be temporary, since you can play all this for your class and disable the previous variable by setting a null value.

Cons: Basically no counter in this method, you just need to be careful when overriding the variable, in case your class must have read first before setting a null value.

Basically your problem is time to "read" these settings, not how you treat them or how you isolate them, if you are already using OOP, there is absolutely no reason to use $GLOBALS

  • Hi, thanks for the reply, but I’m already using OOP, and already had the classes to read the settings, my problem is even where to store this data. And yes, I’m the only one working on this project, because I’m taking an old job and I’m putting it all in classes so I can use it whenever I want without having to rewrite the functions.

  • My class also already injects configurations.

  • I made changes in the answer, but I confess that really your question was very different from the original, leaving the other questions with the answer half "no point".

2

There is no guideline in which say how we should design the system.

Therefore, we cannot say that it is right or wrong to store such data in the variable $GLOBALS.

However, there is a concern regarding the consumption of unnecessary resources.

Practical example

$GLOBALS = array(
    'foo1' = array(1, 2, 3, 4, 5),
    'foo2' = array(1, 2, 3, 4, 5),
    'foo3' = array(1, 2, 3, 4, 5),
    'foo4' = array(1, 2, 3, 4, 5),
    'foo5' = array(1, 2, 3, 4, 5),
    'foo6' = array(1, 2, 3, 4, 5),
    'foo7' = array(1, 2, 3, 4, 5),
    'foo8' = array(1, 2, 3, 4, 5),
    'foo9' = array(1, 2, 3, 4, 5),
    'foo10' = array(1, 2, 3, 4, 5),
);

Suppose this array is much larger and that’s usually what happens.

Why port on all pages, all this data?

Imagine a page that invokes a function that only needs "foo10". No other data from this immense array will be used. However, they are all there occupying space in memory.

Something more economical is to load the data only when you really need it.

Example

foo10.php

<?php
return array(1, 2, 3, 4, 5);

php page.

<?php
$foo10 = include 'foo10.php';

This is sufficient, organized, simple and light.

It also allows the application to be written in a modular way. That is, it makes possible the re-usability of functions for diverse business logic applications.

Performance

Obviously, the cost of performance in low volume access systems is insignificant, but what matters here is that even in a small system, you have an application with organized codes. If it makes no difference in performance, then why not write in a more organized way?

However, the system does not need to reach titanic traffic volume like facebook, youtube, google, among others, to start presenting performance problems.

A small volume of 10 thousand unique accesses per day already makes micro-optimizations perceptible and, the subject we are talking about here has a much greater significance than a micro-optimization.

There is a performance cost in using include as well, which can be even more damaging than if the data were all in an array.

However, we can solve this by creating build cache structures. I’m not talking about using Memcache, APC, and the like. We can build intelligent cache structures using purely the standard native PHP features. Of course it takes a lot of work, but it pays in the end.

Build caches make an app over 800% fast. This means that the performance bottlenecks will be felt when the volume is at 50 or 60 thousand unique accesses per day and, this is a relatively high volume.

The vast majority of system developers do not have this kind of concern for various reasons, but in general it is because they find it unnecessary to worry about optimizations. In the first problem with performance go into despair or, for convenience appeal to loadbalance, cluster, mirrors. Finally, structures that significantly increase the cost of infrastructure and maintenance.

Abandoning the whole structure, switching to another technology is not something very smart unless it is something very outdated, unfeasible to continue using and, this is not the case of PHP.

PHP is as weak and poor as they say?

Always be suspicious when someone says that PHP is not good for high data volume and "this" or "that".

For many years, we PHP programmers have suffered from prejudice, being rated amateurs for using a weakly typed language that "allows total laziness" in application development. Actually the prejudice was quite strong until 2007 and has been decreasing dramatically since then.

This prejudice fell into myth when facebook publicly stated that it still uses PHP and Mysql. Although already exist at the time several other examples of high volume data systems running under PHP.

Instead of changing technology, they just perfected what they were already using.

So avoid believing the myth that big design has to be done with big, expensive and heavy technologies like JAVA and Oracle (just example). These days it’s so beaten that it sounds ridiculous.

Why PHP is the most criticized?

Simply because it is the most popular. It is estimated to be present in more than 85% of web systems worldwide.

There are also malicious criticisms of a commercial nature. A competitor wants to sell his fish and as he can not win on worthy merits, appeals to the low with slanders and spreading untruths.

Common sense

As always, common sense and discernment must prevail.

For example, why use a framework, however small and economical, to simply set up a 3-page static website and a 3-field contact form?

A simple $_POST[] and mail() already solves the job.

Finally, the techniques, tools and concepts should be applied as appropriate.

The final concept depends very much on the level of experience of those involved in the project. This is what differs a senior professional from the amateur in the technical field.

  • 2

    Excellent answer. I was also interested in the "build cache structures" part. Could you provide me with a link where I can read about it? Thank you.

  • 2

    +1 And I think it would be nice for those who voted negative to justify...

  • Look at our questions being denied again for no reason.

  • 1

    Technically, the reason for the negatives may be the extra comment on the use of PHP and Mysql by facebook. I did not mention that Facebook uses a modified version of both for the simple fact that it is known to PHP programmers. I found it unnecessary to put this. Furthermore, I would extend the subject out of focus. But some people who negatively prefer not to comment.

  • The "build cache structures" mentioned would be something like APC usage?

  • @utluiz, in the answer it is described that APC, Memcache and the like are not used for such build cache structures. However, this does not mean that such resources are unnecessary. It just means that it is possible to create build cache using the standard native PHP features, optimizing performance over 500%.

  • @Daniel Hum... so you were referring to saving the opcode? Sorry for the confusion, but given the new question on the subject, I was curious because I never heard the term that way. I wanted to know exactly what it was about.

  • It also makes no use of opcache. It’s really quite simple and when used in conjunction with opcode, memcache, apc, etc., it increases performance even more. The key point of this technique is to eliminate "includes" as much as possible. Of course, that’s not all. It is just an example of the basic logic of this technique. A simple "include" occupies costly processes. I had read about the consumption of includes in an article many years ago, I think nine years ago, and I was curious and tested it. They really consume too many processes. Since then I started to develop techniques using as few resources as possible.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.