Tải bản đầy đủ - 0 (trang)
Hack 60. Program Your Own iGoogle Gadget

Hack 60. Program Your Own iGoogle Gadget

Tải bản đầy đủ - 0trang

whichcomescompletewithhosting(aplacetostoreyourfiles

online)andcolor-codingcapabilities.Tosetupyourowngadget

developmentframework,gotoiGoogleathttp://igoogle.com

andclick"Addatab"tocreateanewtabnamed"Gadget

Development"(besuretouncheckthe"I'mfeelinglucky"

option[Hack#57]).Nowclick"Addstuff"totherightandselect

the"Addfeedorgadget"option.Entergge.xmltoaddthe

GoogleGadgetEditor,andenterdeveloper.xmltoadda

developerhelpergadget.Next,click"BacktoiGoogleHome"to

gotoyournewtab.

Byrearrangingthegadgets,youcansetupadevelopment

environmentaspicturedinFigure6-9.(TomaketheGoogle

GadgetEditorwider,clickthedown-pointingarrowtotheright

ofthetabname,chooseEditThisTab,andpickatwo-column

layoutthatgivesmorewidthtotheleftmostcolumn.)

Technically,theHelloWorldsampleisalreadyfinishednow,

becauseGooglepreloadedthissampleintotheeditor!Clickon

thePreviewtabofthegadgeteditortoseethisasitwould

appearlive.Next,clickEditor,thentakealookatthesource

codeofthegadget:








Hello,world!

]]>



TheXMLdeclarationontopdefinesthecharacterset,UTF-8

[Hack#12].TherootelementiscalledModule,asgadgetswere

previously(andstilloccasionallyare)called"modules"by

Google.TheModulePrefselementstoresyoursettingsforthis

gadget,suchasitstitle;aUserPrefelement,notshowninthis

shortexample,canstorethecustomusersettings.Theactual

contentofyourmoduleistheHTMLsection,wrappedwithinthe



CDATApart.

Changethecontentfrom"Hello,world!"toanythingelse,and

includesomesimple(X)HTML,likethefollowing:



...




Helloworld,thisismyfirstgadget!



]]>

...



TheGoogleGadgetEditor,alongwiththe"MyGadgets"

gadget,helpsyouwiththedevelopmentprocess



Previewthegadget,andifyouliketheresults,saveitby

selectingFile SaveAsfromtheeditorgadgetmenu.Youcan

opttouseGoogle'shostingsolutionforthis.Chooseany

filenameforyoursample,likehello2.xml.Youwillseethis

filenamedisplayedinthetoprightofyoureditor.Clickthelink

toopentheURLinanewwindow,andtheaddressmaylook

similartothefollowing:

CodeView:



http://hosting.gmodules.com/ig/gadgets/file/1227103127405711789

























Copytheaddressyouareseeingandpasteitintothebox

withinthedeveloperhelpergadget(thegadgettitled"My

Gadgets").ClickingtheAddbuttonwillnowshowyourgadget

ontheiGooglepage.Atthispoint,youcansharethegadget

withanyoneelse,orreadthroughGoogle'stutorialat

http://google.com/apis/gadgets/docs-home.htmltofindout

moreaboutthegadgetsyntax.Youcanalsoloadfurther

samplesintothegadgeteditortoseewhattheyaremadeof.To

doso,selectNewfromtheGoogleGadgetEditor'sFilemenu.

IfyouchooseGoogle'sgadgethosting,notethat

allyoursavedfileswillsharethesamefolder,and

someoneknowingthefoldernamemaybeableto

guessyourfilename.Itisadvisabletonotpublish

anythingwithinyourgadgetthatyouwouldn't

wanttheworldtosee.

GoogledoesnotdeclareanyHTMLdocumenttype

whenrenderinggadgetstothebrowser.Although

youcanimplicitlyuseXHTMLorHTML(Strictor

Transitional)inyourgadget,thelackofdoctype

makessomebrowsersswitchtoaso-called

"quirksmode."Thismaybringwithitsomesubtle

differencesinregardstohowCSSisdisplayed,

amongotherissues.



TheDailyProductImageGadget

Supposethatyouwanttocreateagadgetthatdisplaysa

differentimagefromyourproductdatabaseeveryday.Notethis



sectionrequiresabasicunderstandingofthetechnologies

involved—thegadgetsyntax,Apache/PHP/MySQL,CSS,and

XHTML—andgivesjustabroadoverviewofhowyoucanputthe

individualpiecestogether.

Thefirstchoiceyoufacewhendecidinghowtosetupyour

gadgetiswhethertoembedyourcodeinthegadgetXML,or

justhavetheXMLpointtoapageonyourserver.Theformer

approachhasthebenefitofusingtheGooglegadget

framework'snativecachingcapabilities.GooglepollsyourXML

definitioneveryonceinawhilebutthenservesitfromtheir

ownserverstogadgetusers,savingyoubandwidth.Thishack

usescodeembeddedinanXMLfileinsteadofapointertoyour

webpage.

Ifyourhypotheticaldatabasetable"products"hasthefieldsid,

title,price,andimage,thenyoucouldcreateasecondtable

"products_random"withthefieldsid,product_id,anddateand

fillitoncewithproductimageIDsusingascript,oraddtoit

dailyusingacronjobonyourserver.Pleasenotethatifyou're

notcomfortablewithusingaSQLservertable,analternative

approachtodefinetheproductdataislistedshortlyaswell.

WhetheryouareusingSQLornot,thePHPfiletoshowthe

dailyimageisasfollows:




header('Content-Type:text/xml;charset=UTF-8');

echo'<'.'?xmlversion="1.0"encoding="UTF-8"?'.'>'."\r

?>


title_url="http://example.com"

description="ShowsanewAcmeIncproducteveryday!"

author="JaneDoe"

author_email="officehacks@gmail.com"

author_affiliation="AcmeInc"

author_location="Chicago"

screenshot="http://example.com/gadget-screenshot-280x250.p

thumbnail="http://example.com/gadget-thumbnail-120x60.png"



/>






/*ifyouhaveadditionalCSS...*/




//-->


?>"alt=""/>



]]>





Thefunctiontogettheproductimage(usingSQL)couldbeas

follows(notethatotherfunctionsreferencedherearenotlisted

forthissample—ifyouwanttotrythisoutwithoutsettingup

theSQLdatabase,trythenextversionofthisfunction):




functiongetProductImageUrl()

{

$url='no-image.jpg';

$database=openDatabase();

$query='SELECTproducts.imageASproductImageFROMproduc

'LEFTJOINproducts_random'.

'ONproducts.id=products_random.id'.

'WHEREdate='.smartQuote(getIsoDate()).'LI

$rows=mysql_query($query)ordie('Error');

while($c=mysql_fetch_array($rows)){

$url=$c['productImage'];

}

closeDatabase($database);

return'http://example.com/images/'.$url;



}

?>



Ifyou'drathernotuseSQLfornow,youcanalsouseafunction

thatstoresyourproductdatainanarray.Inthefollowingcode,

severalcoverimageIDsfromtheO'Reillycatalogarelisted.

Usingtheday()function,yougetanumberrepresentingthe

dayoftheyear—0forJanuary1,42forFebruary12,andsoon.

Themodulusoperator(%)nowgivesyoutheremainderof

dayOfYeardividedbytheamountofcoversavailable.This

coverIndexnumbercanbeusedtograbaspecificcoverID—

foreverynewdayadifferentnumberispicked(rotatingbackto

thebeginningofthearrayifnomorenewcoversareavailable):




functiongetProductImageUrl()

{

$coverIds=array(

'9780596528348',

'0596527209',

'0596007795',

'0596100604',

'0596101538');

$dayOfYear=date('z');

$coverIndex=$dayOfYear%count($coverIds);

$coverId=$coverIds[$coverIndex];

return'http://oreilly.com/catalog/covers/'.$coverId.'

}

?>



Asyoucanseeintheseexamplefunctions,thereturnedimage

URLisanabsoluteURL;that'sbecauseeventhoughtheXMLis

initiallyhostedonyourserver,itwilllaterbeservedbyGoogle

throughthegmodules.comdomain.



Inordertohaveyourscriptberecognizedbyyourwebserver

asaPHPscript,youwillprobablyneedtogiveitafilename

suchasproduct-gadget.php.IfyouareusingtheApacheserver

withmod_rewriteenabled,youcanmakeitlooklikeanXMLfile

byusingsyntaxlikethefollowinginsidean.htaccessfileon

yourserver:

RewriteEngineOn

RewriteRule^product-gadget\.xmlproduct-gadget.php



ThiswouldletyouuseaURLlikehttp://example.com/productgadget.xml.Yourgadgetisnowreadytobesubmittedat

http://google.com/ig/submit!



NOTE

Notethatanalternativetothisapproachistohaveyour

productimagescriptemitanRSS/Atomfeed,asiGoogle

userscanalsoaddanyfeedasagadget.Thisway,you

wouldalsosupportRSSreaders,RSS-enabled

screensavers,andmobiledevicesthatsupportRSS.



Hack61.CreateaniGoogleTheme

IstheplainwhitebackgroundoftheGooglehomepageboring

you?

WhenyouclicktheSelectThemelinkatiGoogle.com,youare

forwardedtothethemesdirectorytopickoneofthemany

availablelooksforyourGooglehomepage.You'llfindchoices

likeLollipopland,HongKong(picturedinFigure6-10),orDarts.

SomeofthethemesareprovidedbyGoogle;othersare

homebrewed.Certainthemeswillalsochangewiththetimeof

theday,andmayincludeEastereggs—specialsurprises

showingatspecifictimesoftheday.



NOTE

Pssst:notkeenonwaitingforhoursonendtoglanceat

theEastereggs?TakealookatUKdeveloperTony

Ruscoe'shacktomakethemappearinstantlyat

http://ruscoe.net/blog/2007/03/google-personalizedhomepage-easter.asp.

Ifyouwanttocreateyourowntheme,Googlehasadetailed

one-stoptutorialtotheThemesAPIforyouat

http://code.google.com/apis/themes/docs/dev_guide.html.

Basically,eachthemeconsistsofanXMLfilethatlistsdifferent

"skins,"whichdefinethingslikelinkcolors,textcolors,and

backgroundimages.(Notethatalthoughyoucanchoose

betweenthedifferentavailableiGooglelogos,youarenot

allowedtocompletelyremovethelogo.)

igThemer

EvenmoredirectthangoingthroughtheGoogletutorialto

developathemeistouseigThemer.Availableat

http://hawidu.com/themes/,thisthird-partytoolpresentsa

formlistingthevariousavailableoptions.I'veclickedonthe

colorpickerfortheheaderbackground,forinstance,andafter



makingaselection,pressedtheRefreshbuttonatthetopofthe

form.ThisresultedinthelookshowninFigure6-11.

HittheCreatebuttonattheendoftheformwhenyou'redone

customizing,andigThemerwillhosttheXMLforyouataURL

similartothisone:

http://hawidu.com/themes/public/theme021208093859.xml.

TheiGoogleThemeEditorBookmarklet

Anotherveryinterestingoptionforthemecreationisthe

bookmarkletdevelopedbyJapan'sYoshiomiKurisi,at

http://chris4403.blogspot.com(thankstoIonutof

http://googlesystem.blogspot.comforsuggestingthishack).A

bookmarkletisashortpieceofJavaScript,storedasabrowser

bookmark,thatyoucanexecuteonanywebpage[Hack#16].

Google'sHongKongthemeforiGooglepaintsthe

backgroundascityscape



igThemertakesyouthroughcreatinganiGoogletheme



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 60. Program Your Own iGoogle Gadget

Tải bản đầy đủ ngay(0 tr)

×