⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 service.php

📁 php的编程工具
💻 PHP
📖 第 1 页 / 共 2 页
字号:
<?php/** * @copyright Copyright 2007 Conduit Internet Technologies, Inc. (http://conduit-it.com) * @license Apache Licence, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *     http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @package Apache * @subpackage Solr * @author Donovan Jimenez <djimenez@conduit-it.com> */require_once('Apache/Solr/Document.php');require_once('Apache/Solr/Response.php');/** * Starting point for the Solr API. Represents a Solr server resource and has * methods for pinging, adding, deleting, committing, optimizing and searching. * * Example Usage: * <code> * ... * $solr = new Apache_Solr_Service(); //or explicitly new Apache_Solr_Service('localhost', 8180, '/solr') * * if ($solr->ping()) * { * 		$solr->deleteByQuery('*:*'); //deletes ALL documents - be careful :) * * 		$document = new Apache_Solr_Document(); * 		$document->id = uniqid(); //or something else suitably unique * * 		$document->title = 'Some Title'; * 		$document->content = 'Some content for this wonderful document. Blah blah blah.'; * * 		$solr->addDocument($document); 	//if you're going to be adding documents in bulk using addDocuments * 										//with an array of documents is faster * * 		$solr->commit(); //commit to see the deletes and the document * 		$solr->optimize(); //merges multiple segments into one * * 		//and the one we all care about, search! * 		//any other common or custom parameters to the request handler can go in the * 		//optional 4th array argument. * 		$solr->search('content:blah', 0, 10, array('sort' => 'timestamp desc')); * } * ... * </code> * * @todo Investigate using other HTTP clients other than file_get_contents built-in handler. Could provide performance * improvements when dealing with multiple requests by using HTTP's keep alive functionality */class Apache_Solr_Service{	/**	 * Response version we support	 */	const SOLR_VERSION = '2.2';	/**	 * Response writer we support	 *	 * @todo Solr 1.3 release may change this to SerializedPHP or PHP implementation	 */	const SOLR_WRITER = 'json';	/**	 * Servlet mappings	 */	const PING_SERVLET = 'admin/ping';	const UPDATE_SERVLET = 'update';	const SEARCH_SERVLET = 'select';	const THREADS_SERVLET = 'admin/threads';	/**	 * Server identification strings	 *	 * @var string	 */	private $_host, $_port, $_path;	/**	 * Query delimiters. Someone might want to be able to change	 * these (to use &amp; instead of & for example), so I've provided them.	 *	 * @var string	 */	private $_queryDelimiter = '?', $_queryStringDelimiter = '&';	/**	 * Constructed servlet full path URLs	 *	 * @var string	 */	private $_updateUrl, $_searchUrl, $_threadsUrl;	/**	 * Keep track of whether our URLs have been constructed	 *	 * @var boolean	 */	private $_urlsInited = false;	/**	 * Stream context for posting	 *	 * @var resource	 */	private $_postContext;	/**	 * Escape a value for special query characters such as ':', '(', ')', '*', '?', etc.	 *	 * NOTE: inside a phrase fewer characters need escaped, use {@link Apache_Solr_Service::escapePhrase()} instead	 *	 * @param string $value	 * @return string	 */	static public function escape($value)	{		//list taken from http://lucene.apache.org/java/docs/queryparsersyntax.html#Escaping%20Special%20Characters		$pattern = '/(\+|-|&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|\*|\?|:|\\\)/';		$replace = '\\\$1';		return preg_replace($pattern, $replace, $value);	}	/**	 * Escape a value meant to be contained in a phrase for special query characters	 *	 * @param string $value	 * @return string	 */	static public function escapePhrase($value)	{		$pattern = '/("|\\\)/';		$replace = '\\\$1';		return preg_replace($pattern, $replace, $value);	}	/**	 * Convenience function for creating phrase syntax from a value	 *	 * @param string $value	 * @return string	 */	static public function phrase($value)	{		return '"' . self::escapePhrase($value) . '"';	}	/**	 * Constructor. All parameters are optional and will take on default values	 * if not specified.	 *	 * @param string $host	 * @param string $port	 * @param string $path	 */	public function __construct($host = 'localhost', $port = 8180, $path = '/solr/')	{		$this->setHost($host);		$this->setPort($port);		$this->setPath($path);		$this->_initUrls();		//set up the stream context for posting with file_get_contents		$contextOpts = array(			'http' => array(				'method' => 'POST',				'header' => "Content-Type: text/xml; charset=UTF-8\r\n" //php.net example showed \r\n at the end			)		);		$this->_postContext = stream_context_create($contextOpts);	}	/**	 * Return a valid http URL given this server's host, port and path and a provided servlet name	 *	 * @param string $servlet	 * @return string	 */	private function _constructUrl($servlet, $params = array())	{		if (count($params))		{			//escape all parameters appropriately for inclusion in the query string			$escapedParams = array();			foreach ($params as $key => $value)			{				$escapedParams[] = urlencode($key) . '=' . urlencode($value);			}			$queryString = $this->_queryDelimiter . implode($this->_queryStringDelimiter, $escapedParams);		}		else		{			$queryString = '';		}		return 'http://' . $this->_host . ':' . $this->_port . $this->_path . $servlet . $queryString;	}	/**	 * Construct the Full URLs for the three servlets we reference	 */	private function _initUrls()	{		//Initialize our full servlet URLs now that we have server information		$this->_updateUrl = $this->_constructUrl(self::UPDATE_SERVLET, array('wt' => self::SOLR_WRITER ));		$this->_searchUrl = $this->_constructUrl(self::SEARCH_SERVLET);		$this->_threadsUrl = $this->_constructUrl(self::THREADS_SERVLET, array('wt' => self::SOLR_WRITER ));		$this->_urlsInited = true;	}	/**	 * Central method for making a get operation against this Solr Server	 *	 * @param string $url	 * @return Apache_Solr_Response	 *	 * @throws Exception If a non 200 response status is returned	 */	private function _sendRawGet($url)	{		//$http_response_header is set by file_get_contents		$response = new Apache_Solr_Response(@file_get_contents($url), $http_response_header);		if ($response->getHttpStatus() != 200)		{			throw new Exception('"' . $response->getHttpStatus() . '" Status: ' . $response->getHttpStatusMessage());		}		return $response;	}	/**	 * Central method for making a post operation against this Solr Server	 *	 * @param string $url	 * @param string $rawPost	 * @param string $contentType	 * @return Apache_Solr_Response	 *	 * @throws Exception If a non 200 response status is returned	 */	private function _sendRawPost($url, $rawPost, $contentType = 'text/xml; charset=UTF-8')	{		//ensure content type is correct		stream_context_set_option($this->_postContext, 'http', 'header', 'Content-Type: ' . $contentType. "\r\n");		//set the content		stream_context_set_option($this->_postContext, 'http', 'content', $rawPost);		//$http_response_header is set by file_get_contents		$response = new Apache_Solr_Response(@file_get_contents($url, false, $this->_postContext), $http_response_header);		if ($response->getHttpStatus() != 200)		{			throw new Exception('"' . $response->getHttpStatus() . '" Status: ' . $response->getHttpStatusMessage());		}		return $response;	}	/**	 * Returns the set host	 *	 * @return string	 */	public function getHost()	{		return $this->_host;	}	/**	 * Set the host used. If empty will fallback to constants	 *	 * @param string $host	 */	public function setHost($host)	{		//Use the provided host or use the default		if (empty($host))		{			throw new Exception('Host parameter is empty');		}		else		{			$this->_host = $host;		}		if ($this->_urlsInited)		{			$this->_initUrls();		}	}	/**	 * Get the set port	 *	 * @return integer	 */	public function getPort()	{		return $this->_port;	}	/**	 * Set the port used. If empty will fallback to constants	 *	 * @param integer $port	 */	public function setPort($port)	{		//Use the provided port or use the default		$port = (int) $port;		if ($port <= 0)		{			throw new Exception('Port is not a valid port number'); 		}		else		{			$this->_port = $port;		}		if ($this->_urlsInited)		{			$this->_initUrls();		}	}	/**	 * Get the set path.	 *	 * @return string	 */	public function getPath()	{		return $this->_path;	}	/**	 * Set the path used. If empty will fallback to constants	 *	 * @param string $path	 */	public function setPath($path)	{		$path = trim($path, '/');		$this->_path = '/' . $path . '/';		if ($this->_urlsInited)		{			$this->_initUrls();		}	}	/**	 * Set the string used to separate the path form the query string.	 * Defaulted to '?'	 *	 * @param string $queryDelimiter	 */	public function setQueryDelimiter($queryDelimiter)	{		$this->_queryDelimiter = $queryDelimiter;	}	/**

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -