PHP: is read file at every page load too heavy

PHPwebsite-performance

In F3 Framework Controller I wrote a function checking whether MySql data are saved in a file, otherwise loading a form to ask users for that data (similar to WordPress Installation).

This function is loaded every time that a page / method is called:

abstract class Controller
{

    /* F3 */
    protected $f3;
    protected $file_configuration = 'setup.cfg';

    function __construct()
    {
        $f3 = Base::instance();
        $this->f3 = $f3;
        $this->setDatabase();
        $this->setup();
    }
}

and setDatabase() is a simple:

private function setDatabase()
    {
        $search = 'TEST';
        $file = $this->file_configuration;
        // Read from file
        $lines = file('app/config/'.$file);
        $found = false;
        foreach($lines as $line)
        {
            // Check if the line contains the string we're looking for, and print if it does
            if(strpos($line, $search) !== false)
            {
                $found = true;
            }
        }
        if ($found===false)
        {
            $fh = fopen('app/config/'.$file, 'a') or die("can't open file");
            $stringData = "\n";
            fwrite($fh, $stringData);
            $stringData = "New Stuff 1";
            fwrite($fh, $stringData);
            $stringData = "\n";
            fwrite($fh, $stringData);
            $stringData = "New Stuff 2";
            fwrite($fh, $stringData);
            fclose($fh);
        }
    }

(Please don't see the values of variables… only test at the moment) 😉

My question is:

Others classes start extending Controller, will I put too much strain on my server reading every time the file?

Can you hint me a best approach?

Imagine wordpress: I think that every time you call the page, it checks if database exists / is properly configured, otherwise stop / ask for insert connection data (username, password, etc)

Best Answer

Could be (too) heavy for my server performs that check every time?

This is just not good practice in general. If you end up working with other developers and they inherit from Controller as well (which seems like a very centric object in your domain) you will end up with a lot of heavy processing on your server.

I would suggest only setting things in your constructor that help you create the object. Reading things from the database doesn't seem to be a part of it.

This will also make testing a pain in the neck for you.

If you really need to do it in the constructor for some reason then I would suggest using the Singelton Pattern and only create it once. This way you can use its instance without recalling the constructor each and every time.

Related Topic