27.9. Advanced

27.9.1. Using index as static property

Zend_Search_Lucene object uses object destructor to commit changes and clean up resources.

It stores added documents in memory and dumps new index segment to disk depending on MaxBufferedDocs parameter.

If MaxBufferedDocs limit is not reached then there are some "unsaved" documents which a saved as new segment in object destructor. Index auto-optimization procedure is invoked if necessary depending on MaxBufferedDocs, MaxMergeDocs and MergeFactor parameters.

Static object properties (see below) are destroyed after the "last line of executed script".

<?php
class Searcher {
    private static $_index;

    public static function initIndex() {
        self::$_index = Zend_Search_Lucene::open('path/to/index');
    }
}

Searcher::initIndex();

Nevertheless, object destructor for static properties is correctly invoked and has possibility to do everything it has to do.

Potential problem is an exception handling. Exceptions thrown by destructors of static objects don't have context, because execution is performed "after the end of script".

You will get "Fatal error: Exception thrown without a stack frame in Unknown on line 0" error message instead of exception description for such cases.

Zend_Search_Lucene gives the possibility to handle this problem with commit() method. It saves all unsaved changes and frees memory used for storing new segments. You are free to use commit operation any time or several times during script execution. You can still use Zend_Search_Lucene object for searching, adding or deleting document after commit operation. But commit() call guarantees, that if there are no document adding or deleting after commit call, then Zend_Search_Lucene destructor has nothing to do and doesn't throw any exception:

<?php
class Searcher {
    private static $_index;

    public static function initIndex() {
        self::$_index = Zend_Search_Lucene::open('path/to/index');
    }

    ...

    public static function commit() {
        self::$_index->commit();
    }
}

Searcher::initIndex();

...

// Script shutdown routine
...
Searcher::commit();
...