PHP config include issue

  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8399
  • Loc: USA

Post 3+ Months Ago

I'm not exactly sure what is going on here, but I'm guessing that I'm doing something wrong here.

I have config.php which holds the database values, and in my database access wrapper I'm including it in there so I have access to those values but the script doesn't recognize those values. Here is what I have at the moment.

PHP Code: [ Select ]
// Checking if the config file is an XML or PHP
if(pathinfo(CONFIG_FILE, PATHINFO_EXTENSION) == 'xml')
{
    // It's XML, get the contents as XML
    $ret = $this->get_xml(CONFIG_FILE);
   
    // Setting the database information to the database variables
    $this->user = $ret->user;
    $this->host = $ret->host;
    $this->pass = $ret->pass;
    $this->dbname = ($database) ? $database : $ret->dbname;
    $this->prefix = $ret->table_prefix;
}
else
{
    // Including the database variable page
    $this->get_php(CONFIG_FILE);
   
    // Setting the database information to the database variables
    $this->user = $user;
    $this->host = $host;
    $this->pass = $pass;
    $this->dbname = ($database) ? $database : $dbname;
    $this->prefix = $tbl_pre;
}
 
  1. // Checking if the config file is an XML or PHP
  2. if(pathinfo(CONFIG_FILE, PATHINFO_EXTENSION) == 'xml')
  3. {
  4.     // It's XML, get the contents as XML
  5.     $ret = $this->get_xml(CONFIG_FILE);
  6.    
  7.     // Setting the database information to the database variables
  8.     $this->user = $ret->user;
  9.     $this->host = $ret->host;
  10.     $this->pass = $ret->pass;
  11.     $this->dbname = ($database) ? $database : $ret->dbname;
  12.     $this->prefix = $ret->table_prefix;
  13. }
  14. else
  15. {
  16.     // Including the database variable page
  17.     $this->get_php(CONFIG_FILE);
  18.    
  19.     // Setting the database information to the database variables
  20.     $this->user = $user;
  21.     $this->host = $host;
  22.     $this->pass = $pass;
  23.     $this->dbname = ($database) ? $database : $dbname;
  24.     $this->prefix = $tbl_pre;
  25. }
  26.  

And get_php is simply
PHP Code: [ Select ]
public function get_php($file)
{
    // Checking if the file exists
    if(file_exists($file))
    {
        // Loading the PHP file
        if(!include($file))
        {
            // Throwing the exception
            throw new exception("The file failed to be included. '{$file}'");
           
            // Returning false as this is an error
            return false;
        }
       
        // Returning true
        return true;
    }
       
    // The file doesn't exist
    throw new exception("Error loading file: 404 File Not Found Encountered. Assumed location of file: " . $file);
   
    // Returning false
    return false;
}
  1. public function get_php($file)
  2. {
  3.     // Checking if the file exists
  4.     if(file_exists($file))
  5.     {
  6.         // Loading the PHP file
  7.         if(!include($file))
  8.         {
  9.             // Throwing the exception
  10.             throw new exception("The file failed to be included. '{$file}'");
  11.            
  12.             // Returning false as this is an error
  13.             return false;
  14.         }
  15.        
  16.         // Returning true
  17.         return true;
  18.     }
  19.        
  20.     // The file doesn't exist
  21.     throw new exception("Error loading file: 404 File Not Found Encountered. Assumed location of file: " . $file);
  22.    
  23.     // Returning false
  24.     return false;
  25. }

I'm not exactly sure on why it doesn't work... phpbb3 seems to be doing it the same way and it works there.
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8399
  • Loc: USA

Post 3+ Months Ago

Sorry, this was a silly question indeed. Just after a while of not coding I forgot things!

I have to include the file outside the function and set-up global at the beginning of function.
PHP Code: [ Select ]
function name()
{
    global $var1, $var2, $var3;
   
    // Do the code here
}
  1. function name()
  2. {
  3.     global $var1, $var2, $var3;
  4.    
  5.     // Do the code here
  6. }
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6252
  • Loc: Seattle, WA

Post 3+ Months Ago

Of course, global variables are a pretty bad programming pattern and you'll be passing those variables into the function as arguments. :)
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8399
  • Loc: USA

Post 3+ Months Ago

Many big php projects use globals like that (including phpbb3) so I thought it would be fine. Besides setting the $user object again and again just seems like a lot of extra work, when I could set it in 1 page and just use the global to pass it to other functions in different classes that uses that.

In this particular case I would be able to pass these variables through the function as arguments. In other's I would have to set a new object ($user = new user();) which would run the constructor functions all over again (slowing down the system), reset some data and those values won't be constant per session as I'd like them to be.

Why would globals be a bad programming pattern? Do they cause a security risk?
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6252
  • Loc: Seattle, WA

Post 3+ Months Ago

Wikipedia's pretty spot-on, so I won't try to re-explain it:

Quote:
They are usually considered bad practice precisely because of their non-locality: a global variable can potentially be modified from anywhere (unless they reside in protected memory or are otherwise rendered read-only), and any part of the program may depend on it.[1] A global variable therefore has an unlimited potential for creating mutual dependencies, and adding mutual dependencies increases complexity. See action at a distance. Global variables also make it difficult to integrate modules because software written by others may use the same global names unless names are reserved by agreement, or by naming convention. However, in a few cases, global variables can be suitable for use. For example, they can be used to avoid having to pass frequently-used variables continuously throughout several functions.

http://en.wikipedia.org/wiki/Global_variables

If your use case is related to the last statement above, you may want to consider using a singleton pattern to keep things just a tiny bit more manageable.
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9090
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

Another good example is the company I am working for right now. Some of their programming is really old, and many people over the years have worked on it with global variables all over the place with many different naming schemes. So the effects of this can make things difficult sometimes as if a piece of code changes somewhere, you are not sure how it is going to affect everything else. Having all of your variables local to a function is much better, and allows others to work with your code better. Once your project starts getting big, you are likely going use a variable with the same name somewhere else and that is where you can start running into issues. Of course you could have a good naming scheme to prevent this, but once you start working with multiple developers nobody knows exactly what you have done and it really just turns into a nightmare.
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8399
  • Loc: USA

Post 3+ Months Ago

spork wrote:
If your use case is related to the last statement above, you may want to consider using a singleton pattern to keep things just a tiny bit more manageable.

I also read that singletons are a bad method as well! Well, so far I'm not using globals or anything like that as I have went about a different way about this. I'm probably going to do dependency injection instead... passing objects through the function arguments where I need them... depending on the situation.
  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6252
  • Loc: Seattle, WA

Post 3+ Months Ago

Singletons are bad programming practice, for most of the same reasons that global variables are (a singleton is essentially a global object). The only added benefit here is that it at least encapsulates all your global state into a single class instance.
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8399
  • Loc: USA

Post 3+ Months Ago

Oh... well, I went ahead and followed your advice. Thanks for helping me out! :D
spork wrote:
Of course, global variables are a pretty bad programming pattern and you'll be passing those variables into the function as arguments. :)

If you notice anything else that I'm doing which is considered as bad programming pattern, then feel free to tell me... I'll be happy to learn! :D
  • Rabid Dog
  • Web Master
  • Web Master
  • User avatar
  • Posts: 3245
  • Loc: South Africa

Post 3+ Months Ago

Singletons are a bad practice? Since when? Why are they a bad practice? Are we talking web environments only?

Singletons - if thread safe are perfectly good to use.

In theory your entire page processing is a singleton. Page gets requested -> server fires up thread to process request (including the CGI - php in this case), terminates executing thread and server sends response. There is no state maintained between calls.

If I am writing a desktop application, why wouldn't I want to only create one instance of my repository as opposed to consuming additional processing power to re-instantiate it every time I need to make a call to my repository? Yes garbage collection might ripped it out and dispose of it but that is why the singleton (as spork pointed out) should be encapsulated/abstracted.

Singletons have their place as does everything else BUT global variables, that was just a practical joke - the guys that designed it didn't think anyone would every use them :D.

The excuse that "many big projects are doing it" is not a valid one. Many people drink and drive in SA, doesn't mean it is right. ;) that last line was supposed to be funny, so for the sake of my fragile ego, please laugh a little.
  • Nightslyr
  • Proficient
  • Proficient
  • Nightslyr
  • Posts: 283

Post 3+ Months Ago

Singletons are unnecessary in PHP precisely because scripts (generally) have the lifespan of a single request. Add that fact to the fact that objects are passed by reference by default, and all of these singleton repository/database wrapper classes I see floating around in bad code are useless. There's literally no need for them when you can simply create a single instance and inject it into the classes that need it.

Regarding 'global', it's a major sign of bad code. Full stop. Functions are designed to be black boxes that can be invoked regardless of their surrounding environment. Their signatures (name, argument list, return value(s)) create an explicit contract: function <name> will return <value(s)> when <arguments> are passed in. 'global' nukes that contract by creating implicit requirements within the body of this supposed black box. Now, your function has requirements that aren't immediately known. And heaven help you if your globals are overwritten (which will happen).

It's especially egregious in an OOP setting where encapsulation is one of the cornerstones of the entire paradigm. globals = no encapsulation.

You (the royal you) might not think it's a big deal, but it is, especially if you work with other coders. You no longer have an API - you now need to know the inner workings of all the functions/methods available to you. And editing/debugging code has now become a nightmare because you need to trace where a global was overwritten or never set.

Finally, an appeal to popularity a logical fallacy ("but popular product X uses it"). WordPress is the most ubiquitous package of web software in the world, and it is an utter train wreck under the hood. Moreover, a lot of the more popular systems are based on legacy code from the early-to-mid 2000's. Basing your design decisions on 10 year old code isn't smart.

In PHP, there is never a reason to use a global. If you think you need one, it's a sign that your application design is poor and you've written yourself into a corner.
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8399
  • Loc: USA

Post 3+ Months Ago

What about factories, are they considered as bad practice? Looks to me like it's similar to a singleton (in a way).

Post Information

  • Total Posts in this topic: 12 posts
  • Users browsing this forum: No registered users and 77 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.