Blog de Nathan Story

Automatically Delete Temporary Files in PHP With RAII

| Comments


The RAII (Resource Acquisition is Initialization) pattern ties the management of an external resource to an object’s lifetime. In short, when the object is allocated a resource is opened, and when the object is collected, the resource is closed. In a language like Java, where an object is not collected at a deterministic time, this is considered an anti-pattern. In PHP, if we follow certain rules, we can rely on the __destruct method being called at a deterministic time, and, so, we can leverage the RAII pattern for resource management.

Example Code

The following code is taken from my project Phrappe.

class TempFile
    public $path;

    public function __construct()
        $this->path = tempnam(sys_get_temp_dir(), 'Phrappe');

    public function __destruct()

function i_need_a_temp_file()
  $temp_file = new TempFile;
  // do something with $temp_file->path
  // ...
  // the file will be deleted when this function exits

Note: if you want to be “more correct,” the above code could be modified to make the $path variable private, and only accessible via a getPath() method. This would enforce for consumers of the class our intent that $path should never be changed.

Why does this work in PHP?

PHP (5.3+) employs two memory management techniques:

Reference counting is deterministic – when the number of references to an object drops to zero, the memory manager knows that object can be freed and its __destruct method called. This means that as long as as our object can be collected through reference counting (i.e. no circular references are made), we can determine exactly when it will be collected.

Does anyone do this?

This pattern is actually used by the PDO class in the PHP standard library. A PDO object wraps a connection to a database, which is opened when the object is constructed. Instead of offering an explicit close method, the connection is closed when the last reference to the PDO object is removed. This is described under Connections and connection management:

Upon successful connection to the database, an instance of the PDO class is returned to your script. The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted–you do this by assigning NULL to the variable that holds the object. If you don’t do this explicitly, PHP will automatically close the connection when your script ends.