分享一段Magento关于刷新索引的代码
在调整Magento的Index,偶然间看到这样一段代码,写得很好,摘录出来分享下。
/**
* Reindex all data what this process responsible is
*
* @return unknown_type
*/
public function reindexAll()
{
if ($this->isLocked()) {
Mage::throwException(Mage::helper('index')->__('%s Index process is working now. Please try run this process later.', $this->getIndexer()->getName()));
}
$this->_getResource()->startProcess($this);
$this->lock();
$this->getIndexer()->reindexAll();
$this->unlock();
$this->_getResource()->endProcess($this);
}
/**
* Lock process without blocking.
* This method allow protect multiple process runing and fast lock validation.
*
* @return Mage_Index_Model_Process
*/
public function lock()
{
$this->_isLocked = true;
flock($this->_getLockFile(), LOCK_EX | LOCK_NB);
return $this;
}
/**
* Lock and block process.
* If new instance of the process will try validate locking state
* script will wait until process will be unlocked
*
* @return Mage_Index_Model_Process
*/
public function lockAndBlock()
{
$this->_isLocked = true;
flock($this->_getLockFile(), LOCK_EX);
return $this;
}
/**
* Unlock process
*
* @return Mage_Index_Model_Process
*/
public function unlock()
{
$this->_isLocked = false;
flock($this->_getLockFile(), LOCK_UN);
return $this;
}
/**
* Get lock file resource
*
* @return resource
*/
protected function _getLockFile()
{
if ($this->_lockFile === null) {
$varDir = Mage::getConfig()->getVarDir('locks');
$file = $varDir . DS . 'index_process_'.$this->getId().'.lock';
if (is_file($file)) {
$this->_lockFile = fopen($file, 'w');
} else {
$this->_lockFile = fopen($file, 'x');
}
fwrite($this->_lockFile, date('r'));
}
return $this->_lockFile;
}
关于flock函数的用法。
/**
* Portable advisory file locking
* @link http://www.php.net/manual/en/function.flock.php
* @param handle resource <p>
* An open file pointer.
* </p>
* @param operation int <p>
* operation is one of the following:
* LOCK_SH to acquire a shared lock (reader).
* @param wouldblock int[optional] <p>
* The optional third argument is set to true if the lock would block
* (EWOULDBLOCK errno condition). (not supported on Windows)
* </p>
* @return bool Returns true on success or false on failure.
*/
function flock ($handle, $operation, &$wouldblock = null) {}


