검색 엔진은 대부분 웹을 크롤링하여 찾은 컨텐츠를 색인화하고 필터링하여 대용량 데이터베이스에 저장하고 이러한 데이터베이스를 검색하여 특정 검색 쿼리와 일치하는 결과를 찾는 기능을 한다. 이러한 크롤링/색인화 프로세스는 데이터를 정렬하고 범주화하는 과정에서 편향되지 않게 하고 효율성을 극대화하기 위해 자동으로 수행된다.
이점이 Google Base가 주목받는 이유이다. Google Base는 2005년에 공개된 온라인 데이터베이스로 이 데이터베이스를 이용하면 사용자가 직접 컨텐츠를 업로드하여 다양한 기술적 속성을 부가할 수 있으며 이러한 정보가 기본 Google 검색 엔진을 통해 검색될 수 있도록 할 수도 있다. 이 시스템에는 사전 정의된 항목 유형 세트(예: "jobs", "travel", "events" 등)가 있으며 사용자는 이 시스템에서 사전 정의된 유형을 사용하거나 새로운 유형을 작성하여 컨텐츠를 기술할 수 있다. 절친한 친구의 이름과 생일, "battle of the bands" 경연을 하는 때와 장소 그리고 현재 해당 작업영역에서 얻을 수 있는 작업 기회의 형태와 같은 다양한 정보가 포함된 모든 유형의 데이터를 업로드할 수 있다.
물론, 정보를 저장할 수 있는 온라인 스토리지를 제공하는 것은 전체의 일부분에 불과하며 나머지 부분에서는 정보를 검색하고 액세스할 수 있는 기능을 제공한다. Google Base에 업로드된 컨텐츠는 자동으로 색인화되어 Google 검색 엔진을 통해 공개적으로 사용할 수 있게 된다. 더 중요한 것은 Google Base 컨텐츠는 Google Base Data API를 통해 사용할 수 있으며 애플리케이션 개발자는 이러한 사용자 작성 컨텐츠를 검색하여 사용자 정의 애플리케이션에 통합할 수 있다는 점이다. 이 API는 REST 모델 이후에 개발되었으며 모든 XML 기반 개발 도구를 통해 액세스할 수 있다. 또한, 이 API에는 PHP, .NET, Python 및 Java ™와 같이 일반적으로 사용되는 다양한 프로그래밍 언어용 클라이언트 라이브러리가 이미 포함되어 있다.
이 기사에서는 Google Base Data API를 소개함과 동시에 Google Base에서 다양한 범주의 데이터를 검색하고 검색 결과를 사용자 정의 PHP 애플리케이션과 통합하여 사용하는 방법을 설명한다. 또한, 다양한 속성을 사용하여 데이터를 검색하고 이 시스템에서 데이터를 추가하고 업데이트, 삭제하는 과정을 예제를 통해 살펴본다. 그러면 이제 시작하자.
Google Base를 사용하는 애플리케이션을 개발하려면 먼저 Google Base가 작동하는 방식을 이해해야 한다. 모든 REST 기반 서비스를 사용할 때와 마찬가지로 작동 과정은 지정된 자원에 HTTP 요청을 함으로써 수행된다. 이 HTTP 요청에는 하나 이상의 입력 매개변수가 있는 쿼리가 포함되어 있으며 서버는 XML을 인식하는 모든 클라이언트에서 구분 분석을 하는 데 적합한 Atom 피드를 사용하여 쿼리에 응답한다.
이러한 과정이 어떻게 작동하는지 확인하려면 사용 중인 웹 브라우저에서 다음 URL에 액세스한다.
http://www.google.com/base/feeds/snippets?bq=product+manager[itemtype:jobs][location:CA] |
참고: 형식화하기 위해 앞의 URL을 두 개의 행으로 나누었다. 이 URL을 하나의 문자열로 사용한다. (이 URL을 하나의 문자열로 여긴다.)
이 요청을 수행하면 여러 개의 엔트리로 구성된 목록이 Google Base에서 리턴되며 이 경우에는 캘리포니아 주의 제품 관리자 직업 목록이 표시된다. 이 메소드에 대한 원시 XML 응답(결과 페이지의 소스 코드에서 확인할 수 있음)은 Listing 1과 같은 형태가 되며 여기에는 각 엔트리에 관한 자세한 정보가 포함되어 있다.
Listing 1. Google Base 피드 예제
<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'
xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'
xmlns:gm='http://base.google.com/ns-metadata/1.0'
xmlns:g='http://base.google.com/ns/1.0'
xmlns:batch='http://schemas.google.com/gdata/batch'>
<id>http://www.google.com/base/feeds/snippets</id>
<updated>2010-01-14T06:50:03.819Z</updated>
<title type='text'>Items matching query:
product manager[itemtype:jobs][location:CA]</title>
<link rel='alternate' type='text/html' href='http://base.google.com'/>
<link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml'
href='http://www.google.com/base/feeds/snippets'/>
<link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml'
href='http://www.google.com/base/feeds/snippets/batch'/>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/base/feeds/snippets?start-index=1&
max-results=25&bq=product+manager%5Bitemtype%3A
jobs%5D%5Blocation%3ACA%5D'/>
<link rel='next' type='application/atom+xml'
href='http://www.google.com/base/feeds/snippets?start-index=26
&max-results=25&bq=product+manager%5Bitemtype%3Ajobs
%5D%5Blocation%3ACA%5D'/>
<author>
<name>Google Inc.</name>
<email>base@google.com</email>
</author>
<generator version='1.0' uri='http://base.google.com'>GoogleBase
</generator>
<openSearch:totalResults>11299</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry>
<id>http://www.google.com/base/feeds/snippets/6996651848910375403</id>
<published>2010-01-08T12:57:46.000Z</published>
<updated>2010-01-13T12:31:03.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Jobs'/>
<title type='text'>SR. PRODUCT MANAGER: Internet Video Markets</title>
<content type='html'>As a SR. PRODUCT MANAGER, you're a take-charge person.
A born leader. A people person who sees the big picture, as well as the minute
details. You generate powerful ideas and know how to get them implemented.
If this describes
you, you'll want to ...</content>
<link rel='alternate' type='text/html'
href='http://www.net-temps.com/job/37zk/USA_5192/sr_product_manager_internet.
html?r=goo'/>
<link rel='self' type='application/atom+xml'
href='http://www.google.com/base/feeds/snippets/6996651848910375403'/>
<author>
<name>Net-Temps</name>
</author>
<g:job_function type='text'>Marketing</g:job_function>
<g:location type='location'>San Francisco, CA, us</g:location>
<g:employer type='text'>Manpower</g:employer>
<g:label type='text'>analysis</g:label>
<g:label type='text'>business</g:label>
<g:label type='text'>product</g:label>
<g:label type='text'>access</g:label>
<g:label type='text'>management</g:label>
<g:label type='text'>marketing</g:label>
<g:label type='text'>manager</g:label>
<g:label type='text'>temporary job</g:label>
<g:label type='text'>temp</g:label>
<g:education type='text'>masters</g:education>
<g:education type='text'>bachelors</g:education>
<g:item_language type='text'>EN</g:item_language>
<g:id type='text'>1237852</g:id>
<g:job_type type='text'>contract</g:job_type>
<g:job_type type='text'>contractor</g:job_type>
<g:target_country type='text'>US</g:target_country>
<g:expiration_date type='dateTime'>2010-01-20T12:31:03Z
</g:expiration_date>
<g:job_industry type='text'>Marketing</g:job_industry>
<g:customer_id type='int'>1106811</g:customer_id>
<g:item_type type='text'>Jobs</g:item_type>
</entry>
...
</feed>
|
다른 Google API와 마찬가지로 Google Base Data API는 요청된 데이터가 포함된 Atom 피드를 사용하여 REST 요청에 응답한다. 피드에는 공용 피드(스니펫 피드)와 사설 피드라는 두 가지 중요한 기본 피드가 있으며 이러한 피드는 각각 모든 Google Base 항목의 목록과 특정 사용자가 업로드한 항목의 목록을 포함하고 있다. 전자는 공용으로 검색하고 액세스할 수 있으며 후자는 피드 소유자만 사용할 수 있으며 인증이 필요하다. 이 기사에서는 두 가지 피드를 모두 살펴본다.
Listing 1에는 캘리포니아 주의 제품 관리자 직업에 대한 검색 요청의 응답으로 생성된 스니펫 피드에 관한 예제가 있다. 이 피드는 표준 Atom 피드로 최상위 <feed> 요소에는 결과 세트의 현재, 다음 및 이전 페이지에 대한 URL이 있는 <link> 요소와 요약된 검색 통계 데이터가 있는 <openSearch:> 요소가 포함되어 있다.
또한, 최상위 <feed> 요소는 하나 이상의 <entry> 요소를 둘러싸고 있으며 각 요소는 검색 쿼리와 일치하는 결과 항목을 나타낸다. 각 엔트리에는 제목, 텍스트나 HTML 컨텐츠로 구성된 블록 및 자세한 정보를 제공하기 위한 URL과 같은 기술적 메타데이터가 포함된다. 또한, 각 <entry>에는 관련 정보를 가리키는 URL 링크를 제공하는 <link> 요소가 있다.
아마도 가장 중요한 사실은 각 엔트리에는 항목 유형과 관련된 추가 정보가 있는 속성 세트(<g:> 네임스페이스 지정 요소)가 포함된다는 점일 것이다. Google Base에서는 각 엔트리에 맞는 권장 속성이 포함된 다수의 사전 정의된 항목 유형을 제공한다. 이러한 속성은 다음과 같은 두 가지 이유로 중요하다. 제공자 관점에서는 이러한 속성을 이용하여 각 엔트리에 추가로 기술 정보를 부가하거나 마크업할 수 있으며 사용자 관점에서는 이러한 속성을 사용하여 검색 결과를 필터링할 수 있다.
이점을 제대로 이해하려면 Listing 1을 생성하는 데 사용한 URL을 살펴보아야 한다. 요청 URL에 포함된 location과 itemtype 속성은
필터로 작동하여 결과 세트를 jobs 항목 유형에 속하는 엔트리만으로 제한하며 상태 코드 CA와 함께 부가되어 위치를 지정하게 된다.
물론 작업 리스팅에 필요한 정보 요구사항은 이벤트 리스팅이나 부동산 리스팅에 필요한 요구사항과는 매우 다르다. 따라서, Google Base에서
지원하는 각 항목 유형에 따라 사용 가능한 속성 목록이 다르다는 점을 알아 둘 필요가 있다. 예를 들면, jobs 항목 유형에는 location, employer, education 및 salary와 같은 속성이 통합되어 있는 반면에 recipes 항목 유형에는 course, ingredients, number of servings and preparation time과 같은 속성이 통합되어 있다. Google Base Data API 참조 안내서에는 항목 유형과 각 엔트리의 제안된 속성에 대한 완전한 목록을 얻을 수 있는 방법이 기술되어 있다. (관련 링크는
참고자료를 확인한다.)
SimpleXML을 사용한 Google Base 피드 구문 분석
이러한 배경 정보를 바탕으로 Google Base 데이터를 PHP 애플리케이션에 통합하는 과정을 살펴보도록 하자. 이렇게 하기 위한 가장 단순한 방법은 PHP의 SimpleXML 확장을 사용하는 것으로 SimpleXML 확장은 XML로 인코드된 데이터를 액세스하는 데 필요한 오브젝트 지향 API를 제공한다. 원한다면, PHP의 DOM이나 XMLReader 확장을 사용하여 동일한 작업을 수행할 수도 있다. 이점을 확인해 보기 위해 Listing 2를 살펴보자. Listing 2에서는 SimpleXML을 사용하여 Listing 1에 있는 XML 피드를 구문 분석하고 XML 피드의 인코드된 데이터를 웹 페이지로 변환한다.
Listing 2. SimpleXML을 사용하여 Google Base 피드 구문 분석하기
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Retrieving Google Base snippets</title>
<style type="text/css">
.title {
font-weight: holder;
}
.attr {
margin-left: 15px;
}
.result {
margin-bottom: 5px;
float: left;
width: 450px;
margin-left: 20px;
}
</style>
</head>
<body>
<?php
// define snippet feed URL
$url = 'http://www.google.com/base/feeds/snippets?bq=
product+manager[itemtype:jobs][location:CA]';
// get feed XML and load into SimpleXML object
$sxml = simplexml_load_file($url);
// get summary counts from opensearch: namespace
$counts = $sxml->children('http://a9.com/-/spec/opensearchrss/1.0/');
$total = $counts->totalResults;
?>
<h2><?php echo $sxml->title; ?></h2>
<div id="summary">
<?php echo $total; ?> result(s) found.
</div>
<br/>
<div id="results")
<?php $count = 1; ?>
<?php foreach ($sxml->entry as $entry): ?>
<?php
// iterate over attributes
// get employer, location, industry and type
$attrs = $entry->children('http://base.google.com/ns/1.0');
$valsEmployer = array();
$valsLocation = array();
$valsIndustry = array();
$valsEducation = array();
$valsType = array();
foreach ($attrs as $key => $value) {
switch ($key) {
case 'employer':
$valsEmployer[] = $value;
break;
case 'location':
$valsLocation[] = $value;
break;
case 'job_industry':
$valsIndustry[] = $value;
break;
case 'job_type':
$valsType[] = $value;
break;
case 'education':
$valsEducation[] = $value;
break;
}
}
?>
<div class="result">
<div class="title">
<?php echo $count; ?>.
<?php echo $entry->title; ?>
</div>
<div class="attr">
Employer: <?php echo implode(', ', $valsEmployer); ?> <br/>
Location: <?php echo implode(', ', $valsLocation); ?> <br/>
Industry: <?php echo implode(', ', $valsIndustry); ?> <br/>
Type: <?php echo implode(', ', $valsType); ?> <br/>
Education: <?php echo implode(', ', $valsEducation); ?> <br/>
</div>
</div>
<?php $count++; ?>
<?php endforeach; ?>
</div>
</body>
</html>
|
그림 1과 같은 결과물을 확인할 수 있다. (그림 1의 텍스트 전용 버전 보기)
그림 1. SimpleXML을 사용한 Google Base 검색 결과
Listing 2에서는 먼저 simplexml_load_file() 오브젝트를 사용하여 피드 URL에 요청을 전송하고 그 응답을 SimpleXML 오브젝트로 변환한다. 그런 다음,
응답에 있는 전체 <entry> 요소를 반복하고 foreach() 루프를 사용하여 각 요소를 처리한다. 각 엔트리와 속성은 <g:element> 노드 콜렉션에 저장된다. SimpleXML의
children() 메소드는 g: 네임스페이스와 함께 사용되어 이 노드 콜렉션을 $attrs SimpleXMLElement 오브젝트로 리턴한다.
그러면 이제 SimpleXML을 사용하여 이 오브젝트의 개별 속성과 값을 검색할 수 있다. 예를 들면, 직업 위치는 각 엔트리의 <g:location> 요소에 저장되며
$attrs->location 연관 배열로 액세스할 수 있다. 이 정보는 사용하기 편하도록 간단한 CSS 스타일을 일부 적용하여 복합 HTML 페이지에 결합된다.
Zend_Gdata를 사용한 Google Base 구문 분석
Google Base 피드를 구문 분석할 수 있는 두 번째 기술에서는 SimpleXML을 사용하여 수동으로 피드를 구문 분석하지 않고 PHP 애플리케이션을 Google Base Data API와 통합하려고 하는 개발자들을 위해 특별히 디자인된 Zend 프레임워크의 Zend_Gdata 클라이언트 라이브러리를 사용한다.
Zend_Gdata 라이브러리는 Zend 프레임워크의 일부나 독립형 패키지 형태로 다운로드할 수 있다. (관련 링크는 참고자료를 확인한다.) 이 라이브러리에는 특히 Google Base Data API를 사용하는 데 필요한 모듈과 데이터 액세스 및 인증을 단순화할 수 있는 메소드와 사전 정의된 클래스가 포함되어 있다. 이 라이브러리는 커뮤니티에서 테스트된 완전한 코드베이스를 애플리케이션에 제공할 뿐만 아니라 이 라이브러리를 사용하면 XML 트리를 탐색하는 기능이나 사용자 정의 네임스페이스를 처리하는 세부적인 기능에 집중하는 대신 애플리케이션의 핵심 기능에 집중할 수 있다.
Listing 3에는 작동 중인 Zend_Gdata 클라이언트 라이브러리가 표시되어 있으며 여기에서는 Zend_Gdata 라이브러리를 사용하여 Listing 2와 동일한 결과를 얻었다.
Listing 3. Zend_Gdata를 사용한 Google Base 피드 구문 분석
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Gbase');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
try {
// initialize service object
// no authentication needed for public snippets feed
$service = new Zend_Gdata_Gbase();
// prepare and execute search query on snippets feed
$query = $service->newSnippetQuery();
$query->setBq('product manager[location:CA][itemtype:jobs]');
$feed = $service->getGbaseSnippetFeed($query);
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Retrieving Google Base snippets</title>
<style type="text/css">
.title {
font-weight: bolder;
}
.attr {
margin-left: 15px;
}
.result {
margin-bottom: 5px;
float: left;
width: 450px;
margin-left: 20px;
}
</style>
</head>
<body>
<h2><?php echo $feed->title; ?></h2>
<div id="summary">
<?php echo $feed->totalResults; ?> result(s) found.
</div>
<br/>
<div id="results")
<?php $count = 1; ?>
<?php foreach ($feed as $entry): ?>
<?php
// iterate over attributes
// get employer, location, industry, education and type
$valsEmployer = array();
$valsLocation = array();
$valsIndustry = array();
$valsType = array();
$valsEducation = array();
foreach ($entry->getGbaseAttributes() as $attr) {
if ($attr->getText()) {
switch ($attr->getName()) {
case 'employer':
$valsEmployer[] = $attr->getText();
break;
case 'location':
$valsLocation[] = $attr->getText();
break;
case 'job_industry':
$valsIndustry[] = $attr->getText();
break;
case 'job_type':
$valsType[] = $attr->getText();
break;
case 'education':
$valsEducation[] = $attr->getText();
break;
}
}
}
?>
<div class="result">
<div class="title">
<?php echo $count; ?>.
<a href="<?php echo $entry->getLink('alternate')->getHref(); ?>"
>
<?php echo $entry->getTitle(); ?>
</a>
</div>
<div class="attr">
Employer: <?php echo implode(', ', $valsEmployer); ?> <br/>
Location: <?php echo implode(', ', $valsLocation); ?> <br/>
Industry: <?php echo implode(', ', $valsIndustry); ?> <br/>
Type: <?php echo implode(', ', $valsType); ?> <br/>
Education: <?php echo implode(', ', $valsEducation); ?> <br/>
</div>
</div>
<?php $count++; ?>
<?php endforeach; ?>
</div>
</body>
</html>
|
Listing 3에서는 먼저 Zend 클래스 라이브러리를 로드한 후 Zend_Gdata 서비스 클래스의 인스턴스를 초기화한다. 이 클래스는 Google Base Data API와의 모든 후속 상호 작용을 위한 제어 지점으로서 역할을 한다. 현재의 계획은 공용 스니펫 피드에만 액세스하는 것이므로 서비스 오브젝트에 인증 신임이 필요하지 않지만 사용자의 사설 피드(나중에 살펴봄)를 다루는 경우에는 상황이 달라진다.
공용 스니펫 피드와 함께 사용할 가능성이 높은 Zend_Gdata_Base 메소드는 getGbaseSnippetFeed() 메소드이며 이 메소드는 검색 쿼리와 일치하는 항목으로 구성된
피드를 리턴한다. 이 메소드는 setBq() 메소드를 통해 쿼리 문자열 세트를 사용하여 구성된 Zend_Gdata_Gbase_SnippetQuery 오브젝트의 인스턴스를
전달한다. getGbaseSnippetFeed() 메소드에 대한 응답은
Listing 1에 있는 것과 비슷한 Atom 피드이며 이 피드는 자동으로 구문 분석되어 Zend_Gdata_Gbase_SnippetEntry 오브젝트로 구성된 배열로 변환되며
각 오브젝트는 피드에 있는 하나의 <entry>를 나타낸다.
각 엔트리의 개별 속성은 Zend_Gdata_Gbase_Extension_BaseAttribute 오브젝트로 표현되며 각 오브젝트는 getName()과 getText() 메소드를 나타낸다.
사용자는 Zend_Gdata_Gbase_SnippetEntry 오브젝트의 getGbaseAttributes() 메소드를 사용하여 이러한 속성으로 구성된 완전한 콜렉션을 얻을 수 있다. 이러한
콜렉션을 반복하여 필요한 값을 추출하고 이 값을 HTML 페이지에 표시하는 과정은 매우 단순하다. 또한, 각 엔트리의 써드파티 URL를 가리키는 링크를 리턴하는
getLink() 메소드를 주목하자.
그림 2에는 Listing 3의 결과물이 표시되어 있다. (그림 2의 텍스트 전용 버전 보기)
그림 2. Zend_Gdata를 사용하여 Google Base를 검색한 결과
이러한 기본적인 사항을 제대로 이해하면 Listing 3을 수정하여 대화식 기능을 추가하기가 매우 쉽다. Listing 4에는 다양한 항목 유형을 검색하여 사용자가 입력한 키워드와 일치하는 결과를 얻기 위해 사용할 수 있는 검색 양식을 추가하는 과정이 표시되어 있다.
Listing 4. 사용자가 제공한 기준을 사용하여 Google Base 검색하기
<?php
if (isset($_POST['submit'])) {
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Gbase');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
try {
// initialize service object
// no authentication needed for public snippets feed
$service = new Zend_Gdata_Gbase();
// prepare and execute search query on snippets feed
$query = $service->newSnippetQuery();
$queryStr = $_POST['q'] . '[itemtype:' . $_POST['itemtype'] . ']';
$query->setBq($queryStr);
$feed = $service->getGbaseSnippetFeed($query);
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
}
?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Searching Google Base snippets</title>
<style type="text/css">
.title {
font-weight: bolder;
}
.attr {
border-collapse: collapse;
margin-top: 3px;
}
.result {
margin-bottom: 5px;
float: left;
width: 450px;
margin-left: 10px;
}
</style>
</head>
<body>
<h2>Search</h2>
<form method="post">
Search for:
<input type="text" name="q" />
in section:
<select name="itemtype">
<option value="events and activities">Events</option>
<option value="housing">Housing</option>
<option value="jobs">Jobs</option>
<option value="news and articles">News</option>
<option value="personals">Personals</option>
<option value="recipes">Recipes</option>
<option value="reviews">Reviews</option>
<option value="services">Services</option>
</select>
<input type="submit" name="submit" value="Search" />
</form>
<?php if (isset($feed)): ?>
<h2><?php echo $feed->title; ?></h2>
<div id="summary">
<?php echo $feed->totalResults; ?> result(s) found.
</div>
<br/>
<div id="results")
<?php $count = 1; ?>
<?php foreach ($feed as $entry): ?>
<div class="result">
<div class="title">
<?php echo $count; ?>.
<a href="<?php echo $entry->getLink('alternate')->getHref(); ?>"
>
<?php echo $entry->getTitle(); ?>
</a>
</div>
<table border="1" class="attr">
<?php /* get and display all attributes */ ?>
<?php /* convert hyperlinks using preg */ ?>
<?php foreach ($entry->getGbaseAttributes() as $attr): ?>
<?php if ($attr->getText()): ?>
<tr>
<td><?php echo strtoupper($attr->getName()); ?></td>
<td><?php echo (preg_match('/^(http(s?)):/',
$attr->getText())) ?
'<a href="' . $attr->getText(). '">click here</a>' :
substr($attr->getText(), 0, 50); ?></td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
</table>
</div>
<?php $count++; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
</body>
</html>
|
이 스크립트는 복잡해 보이지만 걱정할 필요가 없으며 보기보다 단순하다. 이 스크립트에서는 먼저 검색 입력 필드와 요약된 Google Base 항목 유형 목록을
사용하여 양식을 설정한다. 그런 다음, 사용자가 입력한 내용을 바탕으로 Zend_Gdata_Gbase_SnippetQuery 오브젝트를 생성하고 이 오브젝트를 getGbaseSnippetFeed() 메소드에
전달하여 입력 매개변수와 일치하는 결과 피드를 얻는다. 그 후, 결과 피드에 있는 각 엔트리가 처리되며 각 엔트리의 속성은 getGbaseAttributes() 메소드를 통해
표시된다.
그림 3에는 키워드 'wine'이 포함된 리뷰를 검색한 결과에 대한 예제가 표시되어 있다.
그림 3. 키워드 'wine'이 포함된 리뷰를 Google Base에서 검색한 결과
앞서 살펴본 예제에서 확인한 바와 같이 단순히 속성을 쿼리 필터로 사용함으로써 Google Base에서 리턴한 검색 결과를 필터링할 수 있다. 다음과 같은 예제에서 표시된 바와 같이 이러한 속성은 일반적으로 대괄호로 둘러싸인다.
- 캘리포니아의 제품 관리자 직업:
http://www.google.com/base/feeds/snippets? bq=product+manager[itemtype:jobs][location:CA] - 베이컨이 포함된 조리법:
http://www.google.com/base/feeds/snippets? bq=[itemtype:recipes][ingredients:bacon] - 뉴욕시의 현대 미술 전시회:
http://www.google.com/base/feeds/snippets? bq=modern+art[itemtype:events%20and%20activities][location:new%20york]
참고: 형식화하기 위해 앞의 URL을 두 개의 행으로 나누었다. 이 URL을 하나의 문자열로 사용한다. (이 URL을 하나의 문자열로 여긴다.)
이와는 별도로 REST 쿼리에 다음과 같은 매개변수를 일부 추가하여 API 결과물을 쉽게 사용자 정의할 수 있다.
start-index매개변수, 피드에 있는 엔트리의 시작 오프셋을 지정한다.max-results매개변수, 피드에 있는 엔트리의 번호를 지정한다.q매개변수, 완전한 텍스트 검색을 하는 데 사용된다.crowdby매개변수, 지정된 속성값을 갖는 항목이 반복되는 횟수를 제어한다.orderby매개변수, 결과를 정렬하는 방법을 지정한다.
Listing 5에는 작동 중인 이러한 매개변수에 대한 예제가 있다.
Listing 5. Google Base 검색 결과 필터링
<?php
if (isset($_POST['submit'])) {
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Gbase');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
try {
// initialize service object
// no authentication needed for public snippets feed
$service = new Zend_Gdata_Gbase();
// prepare and execute search query on snippets feed
// attach attribute filters
$query = $service->newSnippetQuery();
$queryStr = $_POST['q'] . '[itemtype:events and activities]';
if (!empty($_POST['location'])) {
$queryStr .= '[location: '. $_POST['location'] . ']';
}
if (!empty($_POST['event_type'])) {
$queryStr .= '[event_type: '. $_POST['type'] .']';
}
// display 20 results per page
// crowd by content field
$query->setBq($queryStr);
$query->setMaxResults(20);
$query->setCrowdBy('content:2');
$feed = $service->getGbaseSnippetFeed($query);
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
}
?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Searching Google Base snippets</title>
<style type="text/css">
.title {
font-weight: bolder;
}
.attr {
border-collapse: collapse;
margin-top: 3px;
}
.result {
margin-bottom: 5px;
float: left;
width: 450px;
margin-left: 10px;
}
</style>
</head>
<body>
<h2>Search Events</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Keywords:
<input type="text" name="q" />
Location:
<input type="text" name="location" size="10" />
Event type:
<input type="text" name="type" size="10" />
<input type="submit" name="submit" value="Search" />
</form>
<?php if (isset($feed)): ?>
<h2><?php echo $feed->title; ?></h2>
<div id="summary">
<?php echo $feed->totalResults; ?> result(s) found.
</div>
<br/>
<div id="results")
<?php $count = 1; ?>
<?php foreach ($feed as $entry): ?>
<div class="result">
<div class="title">
<?php echo $count; ?>.
<a href="<?php echo $entry->getLink('alternate')->getHref(); ?>"
>
<?php echo $entry->getTitle(); ?>
</a>
</div>
<table border="1" class="attr">
<?php /* get and display all attributes */ ?>
<?php // convert hyperlinks using preg */ ?>
<?php foreach ($entry->getGbaseAttributes() as $attr): ?>
<?php if ($attr->getText()): ?>
<tr>
<td><?php echo strtoupper($attr->getName()); ?></td>
<td><?php echo (preg_match('/^(http(s?)):/',
$attr->getText())) ?
'<a href="' . $attr->getText(). '">click here</a>' :
substr($attr->getText(), 0, 50); ?></td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
</table>
</div>
<?php $count++; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
</body>
</html>
|
Listing 5에서는 이벤트 키워드, 위치 및 유형 필드가 있는 간단한 이벤트 검색 양식을 생성한다. 그 다음에는 이러한 입력을 해당 속성으로 변환하여
Google Base 쿼리에 추가한다. setMaxResults() 메소드는 피드에 표시되는 결과 수를 제어하는 데 사용되며 setCrowdBy() 메소드는 반복을 하는 데 필요한
제어 속성과 값을 정의한다. (이 경우에는 동일한 결과를 갖는 두 개의 중복 엔트리만 허용된다.)
그림 4에는 뉴욕시의 현대 미술 전시회를 검색하는 예제가 표시되어 있다.
그림 4. 필터링된 Google Base 이벤트 검색 결과
이전의 예제에서는 모두 공용 스니펫 피드를 사용하였다. 그러나 아는 바와 같이 인증된 모든 사용자는 사설 피드에 액세스할 수 있으며 이 사설 피드에는 사용자가 자체적으로 Google Base에 추가한 사항이 포함되어 있다. Google Base Data API를 이용하면 프로그램을 통해 이 피드에 액세스할 수 있으며 사용자가 API를 호출하여 항목을 추가하거나 편집, 삭제할 수 있다.다음 섹션에서는 이러한 점을 자세히 살펴본다.
먼저, 새 항목을 추가한다. 이 작업은 실제로 매우 단순하며 새 엔트리를 추가하려면 XML로 인코드된 <entry> 블록을 사설 피드 URL로 간단히 POST한다. Listing 6에는 이러한 블록에 대한 예제가 있다.
Listing 6. Google Base 엔트리 블록 예제
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom">
<atom:title type="text">Chicken Tikka Masala</atom:title>
<atom:content type="text">Cut the chicken into fine pieces. Fry until golden.
Add onions, spices and fry for 4-5 minutes and golden. Add chopped tomatoes,
curd and seasoning. Allow to simmer for 10 minutes.</atom:content>
<item_type xmlns="http://base.google.com/ns/1.0" type="text">recipes</item_type>
<main_ingredient xmlns="http://base.google.com/ns/1.0" type="text">
chicken
</main_ingredient>
<servings xmlns="http://base.google.com/ns/1.0" type="int">4</servings>
<cooking_time xmlns="http://base.google.com/ns/1.0" type="number">30
</cooking_time>
<author xmlns="http://base.google.com/ns/1.0" type="text">Mr. Fantastic Cook
</author>
<ingredients xmlns="http://base.google.com/ns/1.0" type="text">chicken
</ingredients>
<ingredients xmlns="http://base.google.com/ns/1.0" type="text">onions
</ingredients>
<ingredients xmlns="http://base.google.com/ns/1.0" type="text">tomatoes
</ingredients>
<ingredients xmlns="http://base.google.com/ns/1.0" type="text">turmeric
</ingredients>
<ingredients xmlns="http://base.google.com/ns/1.0" type="text">coriander
</ingredients>
<ingredients xmlns="http://base.google.com/ns/1.0" type="text">curd
</ingredients>
<ingredients xmlns="http://base.google.com/ns/1.0" type="text">mustard seeds
</ingredients>
</atom:entry>
|
정의된 바와 같이 사설 피드는 사설이기 때문에 피드에 포함된 데이터에 대한 모든 조작은 Google에서 승인하는 두 가지 인증 방법(AuthSub나 ClientLogin) 중 하나를 통해 피드 소유자의 사용자 이름과 암호를 사용하여 인증된 경우에만 정상적으로 수행된다. 이러한 유형의 인증을 수동으로 처리하게 되면 작업이 매우 번거로워지며 전형적인 인증 트랜잭션 과정에서 일어날 수 있는 다양한 시나리오를 처리할 수 있는 많은 코드가 필요하다.
다행히도 이와 관련된 모든 세부사항을 Zend_GData Client 라이브러리에서 처리하기 때문에 사용자는 이점을 그다지 신경 쓰지 않아도 된다. Listing 7을 살펴보면 여기에는 사설 피드에 새 항목을 추가하는 방법이 표시되어 있다.
Listing 7. Google Base에 엔트리 추가하기
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Gbase');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
// set credentials for ClientLogin authentication
$user = "user@gmail.com";
$pass = "secret";
try {
// perform login
// initialize service object
$client = Zend_Gdata_ClientLogin::getHttpClient(
$user, $pass, 'gbase');
$service = new Zend_Gdata_Gbase($client);
// initialize new item
// set title, content and type
$item = $service->newItemEntry();
$item->setItemType('recipes');
$item->title = new Zend_Gdata_App_Extension_Title('Chicken Tikka Masala');
$item->content = new Zend_Gdata_App_Extension_Content(
'Cut the chicken into fine pieces. Fry until golden. Add onions,
spices and fry for 4-5 minutes and golden. Add chopped tomatoes,
curd and seasoning. Allow to simmer for 10 minutes.');
// set type attributes
$item->addGbaseAttribute('main_ingredient', 'chicken', 'text');
$item->addGbaseAttribute('servings', '4', 'int');
$item->addGbaseAttribute('cooking_time', '30', 'number');
$item->addGbaseAttribute('author', 'Mr. Fantastic Cook', 'text');
$item->addGbaseAttribute('ingredients', 'chicken', 'text');
$item->addGbaseAttribute('ingredients', 'onions', 'text');
$item->addGbaseAttribute('ingredients', 'tomatoes', 'text');
$item->addGbaseAttribute('ingredients', 'turmeric', 'text');
$item->addGbaseAttribute('ingredients', 'coriander', 'text');
$item->addGbaseAttribute('ingredients', 'curd', 'text');
$item->addGbaseAttribute('ingredients', 'mustard seeds', 'text');
// save to server
$entry = $service->insertGbaseItem($item);
// display success message
echo "Entry added successfully with ID: " . $entry->getId();
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
?>
|
Listing 7에서는 먼저 Zend 클래스 라이브러리를 로드한 후 Zend_Gdata 서비스 클래스의 인스턴스를 초기화한다. 앞에서 살펴보았던 것과 달리 이 클래스에서는 이제 Zend_Http_Client 오브젝트를 사용하며 이 오브젝트는 필수 사용자 인증 정보와 함께 제공되어 인증을 거쳐 Google Base 서비스에 연결하는 데 사용된다.
일단 인증을 거쳐 Google Base 서비스에 연결되면 서비스 오브젝트의 newItemEntry() 메소드를 사용하여 Zend_Gdata_Gbase_ItemEntry 클래스 인스턴스를 초기화하며
해당 엔트리 오브젝트의 setItemType() 메소드를 사용하여 항목 유형을 정의한다. 또한, 엔트리의 제목과 컨텐츠가
Zend_Gdata_App_Extension_Title과 Zend_Gdata_App_Extension_Content 클래스 인스턴스로 설정되며 개별 속성은 엔트리 오브젝트의 addGbaseAttribute() 메소드를
통해 할당된다. 엔트리가 완성되면 서비스 오브젝트의 insertGbaseItem() 메소드를 호출하여 Google Base 서버로 모두 전송된다.
엔트리가 정상적으로 전송되면 새로운 엔트리 ID가 포함된 결과 페이지가 표시된다. 그림 5에는 이러한 결과 페이지에 대한 예제가 하나 표시되어 있다.
그림 5. Google Base에 항목이 정상적으로 추가된 결과
또한, 엔트리가 Google Base 계정에 표시된다. 그림 6에는 이러한 예제가 표시되어 있다. (그림 6의 확대 이미지 보기)
그림 6. Google Base 인터페이스에 표시된 새로 추가된 항목
또한, Google Base Data API를 통해 엔트리를 편집하고 삭제할 수 있다. 엔트리를 삭제하려면 해당 엔트리의 <link rel="self" ...> 요소에 지정된 URL인 엔트리 URL에 DELETE 요청을 전송해야 한다. Listing 8과 같이 Zend 라이브러리 컨텍스트에서 이 URL을 Zend_Gdata_Gbase_ItemEntry 오브젝트의 delete() 메소드로 간단히 전달할 수 있다.
Listing 8. Google Base에서 엔트리 삭제하기
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Gbase');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
// set credentials for ClientLogin authentication
$user = "user@gmail.com";
$pass = "secret";
try {
// perform login
// initialize service object
$client = Zend_Gdata_ClientLogin::getHttpClient(
$user, $pass, 'gbase');
$service = new Zend_Gdata_Gbase($client);
// get and delete entry
$id = 'http://www.google.com/base/feeds/items/1256392227904491772';
$entry = $service->getGbaseItemEntry($id);
$entry->delete();
// display success message
echo "Entry deleted successfully with ID: " . $entry->getId();
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
?>
|
마찬가지로 엔트리를 편집하려면 getGbaseItemEntry() 메소드를 사용하여 해당 고유 URL을 사용하는 엔트리를 검색하고 업데이트할 값을 변경한 후 엔트리를
Zend_Gdata_Gbase_ItemEntry 오브젝트의 save() 메소드를 사용하는 서버에 다시 저장해야 한다. save() 메소드는 엔트리의 <link rel="self" ...> 요소에
지정된 URL에 PUT 요청을 전송한다. Listing 9에서 이러한 프로세스를 확인할 수 있다.
Listing 9. Google Base에서 엔트리 업데이트하기
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Gbase');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
// set credentials for ClientLogin authentication
$user = "user@gmail.com";
$pass = "secret";
try {
// perform login
// initialize service object
$client = Zend_Gdata_ClientLogin::getHttpClient(
$user, $pass, 'gbase');
$service = new Zend_Gdata_Gbase($client);
// get entry
$id = 'http://www.google.com/base/feeds/items/11812821492318418471';
$item = $service->getGbaseItemEntry($id);
// set new title
$item->title = new Zend_Gdata_App_Extension_Title('Spaghetti Amatriciana');
// set new content
$item->content = new Zend_Gdata_App_Extension_Content('Cut
the bacon into thin strips and fry. Chop the onions and chillies and fry.
Add the bacon and tomato puree to the mixture. Simmer for 10 minutes,
then drain the pasta and mix.');
// remove existing attributes
// set new ones
foreach ($item->getGbaseAttributes() as $attr) {
$item->removeGbaseAttribute($attr);
}
$item->setItemType('recipes');
$item->addGbaseAttribute('main_ingredient', 'pasta', 'text');
$item->addGbaseAttribute('servings', '4', 'int');
$item->addGbaseAttribute('cooking_time', '30', 'number');
$item->addGbaseAttribute('author', 'Mr. Fantastic Cook', 'text');
$item->addGbaseAttribute('ingredients', 'bacon', 'text');
$item->addGbaseAttribute('ingredients', 'onions', 'text');
$item->addGbaseAttribute('ingredients', 'tomatoes', 'text');
$item->addGbaseAttribute('ingredients', 'green chillies', 'text');
$item->addGbaseAttribute('ingredients', 'pasta', 'text');
$item->addGbaseAttribute('ingredients', 'tomato puree', 'text');
// save changes to server
$item->save();
// display success message
echo "Entry updated successfully with ID: " . $item->getId();
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
?>
|
Listing 9에서는 엔트리의 고유 ID를 사용하여 먼저 엔트리를 검색한 후 새로운 주제와 컨텐츠를 할당한다. removeGbaseAttribute() 메소드를 사용하여
기존의 속성을 제거한 후 새로운 속성 세트를 지정한다. 그런 다음 결과로 생긴 엔트리 오브젝트를 동일한 ID를 사용하여 다시 Google Base에 저장한다.
앞서 살펴본 리스팅에서 알 수 있는 바와 같이 Google Base Data API를 사용하여 Google Base에서 항목을 추가하고, 삭제, 업데이트하기는 매우 쉽다. 이번 섹션에서는 이러한 기능을 중심으로 간단한 PHP 애플리케이션을 빌드하며 사용자는 이 애플리케이션을 통해 Google Base Data API를 사용하여 이벤트 리스팅을 추가하고 삭제할 수 있다.
Listing 10에서는 Listing 7을 기반으로 새로운 이벤트 리스팅을 추가하는 양식을 작성하고 Google Base에 양식 데이터를 제출하여 새로운 이벤트 리스팅을 추가한다.
Listing 10. 사용자의 사설 Google Base 피드에 이벤트 엔트리 추가하기
<?php if (isset($_POST['submit'])) {
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Gbase');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
// set credentials for ClientLogin authentication
$user = "user@gmail.com";
$pass = "secret";
try {
// perform login
// initialize service object
$client = Zend_Gdata_ClientLogin::getHttpClient(
$user, $pass, 'gbase');
$service = new Zend_Gdata_Gbase($client);
//
// perform input validation here
// omitted for clarity
//
// initialize new item
// set title, content and type
$item = $service->newItemEntry();
$item->setItemType('events and activities');
$item->title = new Zend_Gdata_App_Extension_Title($_POST['title']);
$item->content = new Zend_Gdata_App_Extension_Content($_POST['content']);
// set type attributes
foreach ($_POST['attr'] as $key => $value) {
$item->addGbaseAttribute($key, $value);
}
// set date range
$start = date('c', strtotime($_POST['start']));
$item->addGbaseAttribute('event_date_range', $start);
// save to server
$entry = $service->insertGbaseItem($item);
// display success message
echo "Entry added successfully with ID: " . $entry->getId();
echo '<br/>';
echo '<a href="list.php">Back to list</a>';
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
} else {
?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Adding events to Google Base</title>
</head>
<body>
<h2>Add Event</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p>
Title: <br/>
<input type="text" name="title" />
</p>
<p>
Description: <br/>
<textarea name="content"></textarea>
</p>
<p>
Venue: <br/>
<input type="text" name="attr[venue]" />
</p>
<p>
Address: <br/>
<input type="text" name="attr[location]" />
</p>
<p>
Type: <br/>
<input type="text" name="attr[event_type]" />
</p>
<p>
Start date/time (dd-mm-yyyy hh:mm): <br/>
<input type="text" name="start" />
</p>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<?php
}
?>
|
Listing 11에는 사용자의 사설 피드를 쿼리하여 피드에 저장된 모든 엔트리를 검색하는 코드가 포함되어 있다. 이벤트 엔트리는 장소 및 날짜 정보와 함께 목록에 표시된다. 또한, 각 엔트리에는 Listing 12에 있는 스크립트를 가리키는 Delete 링크가 있다.
Listing 11. 사용자의 사설 Google Base 피드에 있는 리스팅 이벤트 엔트리
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Gbase');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
// set credentials for ClientLogin authentication
$user = "user@gmail.com";
$pass = "secret";
try {
// perform login
// initialize service object
$client = Zend_Gdata_ClientLogin::getHttpClient(
$user, $pass, 'gbase');
$service = new Zend_Gdata_Gbase($client);
// get item feed
$feed = $service->getGbaseItemFeed();
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Listing events on Google Base</title>
<style type="text/css">
.title {
font-weight: bolder;
}
.attr {
margin-left: 15px;
}
.result {
margin-bottom: 5px;
float: left;
width: 450px;
margin-left: 20px;
}
</style>
</head>
<body>
<h2>List Events</h2>
<a href="add.php">Add a new event</a>
<br/> <br/>
<div id="results">
<?php $count = 1; ?>
<?php foreach ($feed as $entry): ?>
<?php if ($entry->getItemtype() == 'events and activities'): ?>
<?php
// iterate over attributes
// get required data
foreach ($entry->getGbaseAttributes() as $attr) {
if ($attr->getText()) {
switch ($attr->getName()) {
case 'location':
$location = $attr->getText();
break;
case 'venue':
$venue = $attr->getText();
break;
case 'event_date_range':
$date = $attr->getText();
break;
case 'event_type':
$type = $attr->getText();
break;
}
}
}
?>
<div class="result">
<div class="title">
<?php echo $count; ?>.
<?php echo $entry->getTitle(); ?>
(<a href="delete.php?url=
<?php echo $entry->getSelfLink()->getHref(); ?>"
>delete</a>)
</div>
<div class="attr">
Description: <?php echo $entry->getContent(); ?> <br/>
Venue: <?php echo (!empty($venue)) ? $venue :
'Unspecified'; ?> <br/>
Address: <?php echo (!empty($location)) ? $location :
'Unspecified'; ?> <br/>
Type: <?php echo (!empty($type)) ? $type :
'Unspecified'; ?> <br/>
Date/time: <?php echo (!empty($date)) ?
date('d-m-Y h:i', strtotime($date)) : 'Unspecified'; ?> <br/>
</div>
</div>
<?php $count++; ?>
<?php endif; ?>
<?php endforeach; ?>
</div>
</html>
|
Listing 12에서는 엔트리의 URL을 받아서 앞서 Listing 7에서 살펴본 기술을 사용하여 다음과 같이 Google Base에서 엔트리를 삭제한다.
Listing 12. 사용자의 사설 Google Base 피드에서 이벤트 엔트리 삭제하기
<?php
// load Zend Gdata libraries
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Gbase');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
// set credentials for ClientLogin authentication
$user = "user@gmail.com";
$pass = "secret";
try {
// perform login
// initialize service object
$client = Zend_Gdata_ClientLogin::getHttpClient(
$user, $pass, 'gbase');
$service = new Zend_Gdata_Gbase($client);
// get and delete entry
$id = $_GET['url'];
$entry = $service->getGbaseItemEntry($id);
$entry->delete();
// display success message
echo "Entry deleted successfully with ID: " . $entry->getId();
echo '<br/>';
echo '<a href="list.php">Back to list</a>';
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
?>
|
마지막 몇 페이지에서는 SimpleXML과 Zend 클라이언트 라이브러리를 조합하여 Google Base Data API 데이터를 PHP 애플리케이션에 통합하는 방법을 집중적으로 살펴보았다. 이 기사에서는 예제를 통해 다음과 같은 내용을 살펴보았다.
- 두 가지 기본 Google Base 피드를 소개했다.
- 항목 유형과 속성을 사용하여 Google Base에서 데이터를 분류하는 방법을 설명했다.
- 다양한 필터를 사용하여 Google Base 컨텐츠를 검색하는 방법을 살펴보았다.
- 프로그램을 사용하여 컨텐츠를 추가하고 수정, 삭제하는 방법을 확인했다.
- 사용자의 Google Base 데이터에 액세스할 수 있는 사용자 정의 인터페이스를 빌드했다.
이러한 예제에서 알 수 있는 바와 같이 Google Base Data API는 개발자를 위한 강력하고 유연한 도구로 이 도구를 이용하면 컨텐츠 수집 및 검색과 관련된 창조적인 새로운 애플리케이션을 즉시 빌드할 수 있다. 이 API를 사용해 보고 의견을 주기 바란다.
교육
- Developer's Guide 및 Reference Guide: Google Base Data API에 관해 자세히 배울 수 있다.
- Google Data API 인증: 두 가지 인증 유형을 자세히 배울 수 있다.
- Google Base 블로그: Google Base에 관한 새로운 소식을 확인할 수 있다.
- Google Account: 자신의 계정을 등록하여 시작할 수 있다.
- Google Base API 개발자 포럼: Google Base API 개발에 관한 토론 내용을 읽고 참여할 수 있다.
- Zend_Gdata_Gbase 라이브러리: Zend 프레임워크 및 이 프레임워크와 함께 Google Base Data API를 사용하는 방법을 자세히 확인할 수 있다.
- 필자의 더 많은 기사(Vikram Vaswani, developerWorks, 2007년 8월 - 현재): XML, 추가 Google API 및 기타 기술에 대한 기사를 읽어보자.
- developerWorks의 XML 영역: XML 분야의 기술을 향상시키는 데 도움이 되는 참고자료를 얻을 수 있다.
- IBM XML 인증: XML 및 관련 기술에 대한 IBM 인증 개발자가 되는 방법을 찾아볼 수 있다.
- XML Technical library: developerWorks XML 영역에서 다양한 기술 관련 기사와 팁, 튜토리얼, 표준 및 IBM Redbook을 볼 수 있다.
- developerWorks 기술 행사 및 웹 캐스트: 이들 세션에 참가하여 최신 기술에 대한 정보를 얻을 수 있다.
- developerWorks
팟캐스트: 소프트웨어 개발자의 흥미로운 인터뷰와 토론을 확인할 수 있다.
제품 및 기술 얻기
- Zend Gdata 클라이언트 라이브러리 Google Base Data API를 액세스하는 데 필요한 모든 것을 다운로드하여 얻을 수 있다.
- IBM 제품 평가판: IBM SQA Sandbox의 온라인 시험판을 다운로드하거나 살펴보고 DB2®, Lotus®, Rational®, Tivoli® 및
WebSphere®의 애플리케이션 개발 도구와 미들웨어 제품을 사용해 볼 수 있다.
토론
- XML 영역 토론 포럼: 여러 XML 관련 토론에 참여해 볼 수 있다.
- developerWorks
포럼 & 블로그: 이러한 블로그를 읽어보고 참여할 수 있다.
Vikram Vaswani는 오픈 소스 도구와 기술을 전문으로 다루는 컨설팅 서비스 회사인 Melonfire의 창립자이자 CEO이며 PHP Programming Solutions 및 PHP: A Beginners Guide의 저자이기도 하다.