summaryrefslogtreecommitdiff
path: root/framework/DataAccess/SQLMap/TSqlMapClient.php
blob: 33b4131be431de7d0e979a221e874dc74c8f2d2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php

require_once(dirname(__FILE__).'/TSqlMapper.php');

/**
 * A DataMapper client class that can load a cached SqlMapper. Give the configuration
 * file, it looks for a .cache file containing serialized TSqlMapClient instance to
 * load. Usage:
 *
 * <code>
 * $client = new TSqlMapClient;
 * $sqlmap = $client->configure($configFile, true); //load from cache.
 * $products = $sqlMap->queryForList('statementName');
 * </code>
 *
 * To save the TSqlMapper instance to cache for later usage, call
 * cacheConfiguration(). 
 *
 * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
 * @version $Id$
 * @package System.DataAccess.SQLMap
 * @since 3.0
 */
class TSqlMapClient
{
	private $_mapper;
	private $_cache;
	
	public function configure($configFile, $loadFromCache=false)
	{
		if(is_null($this->_mapper))
			$this->initMapper($configFile, $loadFromCache);
		return $this->_mapper;
	}

	public function getInstance()
	{
		return $this->_mapper;
	}

	public function cacheConfiguration()
	{
		if(!is_null($this->_mapper) && $this->_cache !== false)
		{
			if(!is_file($this->_cache))
			{
				file_put_contents($this->_cache,serialize($this->_mapper));
				return true;
			}
		}
		return false;
	}
	
	protected function initMapper($file=null,$loadFromCache=false)
	{
		$this->_cache = $this->getCacheFile($file);
		if($loadFromCache && $this->_cache !== false && is_file($this->_cache))
		{
			$this->_mapper = unserialize(file_get_contents($this->_cache));
		}
		else
		{
			$builder = new TDomSqlMapBuilder();
			$this->_mapper = $builder->configure($file);
		}
	}

	protected function getCacheFile($file)
	{
		$path = realpath($file);
		if($path !== false)
			return substr($path,0, strrpos($path,'.')).'.cache';
		else
			return false;
	}
}

?>