Software engineering notes

Posts Tagged ‘code php

PHP atomic write function

with 7 comments

Motivation:

An atomic write function for those who appreciate the convenience of file_put_contents(), but need an atomic operation.  Please leave a comment if you have a more convenient and/or efficient solution.

Update (5/31/11):

Now using flock, as recommended by Petr and Hayden in their comments below, to avoid race condition. Thanks for the help!

Source code:


function atomic_put_contents($filename, $data)
{
    // Copied largely from http://php.net/manual/en/function.flock.php
    $fp = fopen($filename, "w+");
    if (flock($fp, LOCK_EX)) {
        fwrite($fp, $data);
        flock($fp, LOCK_UN);
    }
    fclose($fp);
}

Example usage:


$content = 'some content';

atomic_put_contents('path/file.ext', $content);

//creates file called path/file.ext containing 'some content'

Written by Erik

October 26, 2008 at 1:58 am

Posted in code

Tagged with

PHP class to manage read-only vars and arrays

leave a comment »

Source code:


class Constants
{
    private $var_cache;

    public function set($key, $val)
    {
        if(isset($this->var_cache[$key]))
        {
            throw(new Exception("Constants->get() error: var $key has already been defined"));
        }
        else
        {
            $this->var_cache[$key] = $val;
        }
    }

    public function get($key)
    {
        return $this->var_cache[$key];
    }
}

Example usage:

$constants = new Constants();

$constants->set('base_url', 'www.domain.com/path');

...

$img_src_url = $constants->get('base_url').'/img/file.jpg';

echo "<img src='$img_src_url'/>";

Written by Erik

October 26, 2008 at 12:04 am

Posted in code

Tagged with