1. Trang chủ
  2. » Công Nghệ Thông Tin

Maintenance from the Outset

71 413 1
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Maintenance from the outset
Tác giả Graeme Foster
Trường học php|architect
Chuyên ngành PHP Programming
Thể loại bài viết
Năm xuất bản 2003
Thành phố Markham
Định dạng
Số trang 71
Dung lượng 2,62 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

This also means that LaTeX documents can be creat-ed by any application that is able to create text files and of course PHP is able to do this.. LaTeX provides features for: • Typesettin

Trang 1

The Magazine For PHP Professionals

Case studies in Client/Server Applications

Transforming XML to PDF

with the help of LaTeX

Embedding Assembler in PHP

Take your PHP to new lows

Take your PHP to new lows

March 1 st - March 5 th 2004See inside for details

Get Ready For

Maintenance

from the Outset

Building a monitoring system

into your scripts

Discover the ins and outs

of this indispensable tool

Trang 2

*By signing this order form, you agree that we will charge your account in Canadian dollars for the

“CAD” amounts indicated above Because of fluctuations in the exchange rates, the actual amount charged in your currency on your credit card statement may vary slightly †Limited time offer expires August 31st, 2003.

Choose a Subscription type:

International Surface $108.99 $94.99 CAD ($79.99 $69.99 US*)International Air $122.99 $108.99 CAD ($89.99 $79.99 US*)

Your charge will appear under the name “Marco Tabini & Associates, Inc.” The first issue of your subscription will be mailed to you in September, 2003 Please allow up to 6 weeks for your subscription to be established.

*US Pricing is approximate and for illustration purposes only

php|architect Subscription Dept.

VISA Mastercard American Express

Credit Card Number:

Expiration Date:

E-mail address:

Phone Number:

Buy now and save $10 off the price of any subscription†

Visit: http://www.phparch.com/print for more information or to subscribe online.

Signature: Date:

php|architect

The Magazine For PHP Professionals

Existing subscribers

can upgrade to

the Print edition

and save!

Login to your account

for more details.

NEW!

Trang 3

Signup now and save $100.00!

Hurry, space is limited.

Visit us at www.phparch.com/cruise for more details.

March 1 st - March 5 th 2004

Andrei Zmievski - Andrei's Regex Clinic, James Cox - XML for the Masses, Wez Furlong -Extending PHP,Stuart Herbert - Safe and Advanced Error Handling in PHP5, Peter James -mod_rewrite: From Zero to Hero, George

Schlossnagle - Profiling PHP, Ilia Alshanetsky - Programming Web Services, John Coggeshall - Mastering PDFLib,

Jason Sweat - Data Caching Techniques

We’ve got you covered, from port to sockets.

Port Canaveral • Coco Cay • Nassau

Plus: Stream socket programming, debugging techniques, writing high-performance code,

Trang 5

Marco Tabini

Editor-in-Chief

Brian K Jones brian@phparch.com

Editorial Team

Arbi Arzoumani Brian Jones Eddie Peloke Peter James Marco Tabini

Graphics & Layout

Arbi Arzoumani, William Martin

Although all possible care has been placed in assuring the accuracy of the contents of this magazine, including all associated source code, listings and figures, the publisher assumes no responsibilities with regards of use

of the information contained herein or in all associated material.

Contact Information:

General mailbox: info@phparch.com Editorial: editors@phparch.com Subscriptions: subs@phparch.com Sales & advertising: sales@phparch.com Technical support: support@phparch.com

Copyright © 2002-2003 Marco Tabini & Associates,

Inc — All Rights Reserved

Icould not be happier right now As I sit here at

my laptop, writing this editorial, by my side sits

a glass of beer that I made from scratch, not quite

a month ago I’m inspired by the similarities that

exist between the evolution of php|architect as a

powerhouse publication and de facto standard

source of PHP knowledge, and the creation of

what is now a simple glass of lovely ale

I brew with real grain and real hops None of

this ‘just add water’ stuff I’ve never done it, and I

won’t I suppose it’s fine if you just want a ‘quick

and dirty’ beer However, I have an overwhelming

feeling that my integrity as a brewer would be

sac-rificed for ‘ease’ (I call it ‘laziness’), and it doesn’t

sit well with me I want honest beer I want to

know how the wort was produced, and where it

came from Indeed, I want to be intimately

associ-ated with the very essence of the finished product

For better, or for worse

I found this same spirit in the publisher of

php|architect, who I’ve now come to know as

both a good friend and close business associate,

Marco Tabini Marco understood my leanings

toward things that were, for lack of a better term,

‘organic’ or ‘untainted’ I wanted material written

by doers I shunned several articles by

profession-al writers whose writing lacked the spirit that

we’ve by now become accustomed to at

php|architect; the spirit of someone who has

fought and lost battles on their way to great

dis-coveries using PHP Other writers, in comparison,

appear to have ‘just added water’ We’ve made it

a goal to avoid such articles Of course, it is the

‘road less traveled’, but we feel it has made all the

difference, and you’ve let us know that we’re

right

Of course, brewing from scratch comes with its

headaches Brewing from scratch means more

steps are involved, the materials are handled and

transferred more often, and more opportunities

exist for molds and bacterias to be introduced into

the beer While I’ve so far been able to avoid that,

and produce very drinkable beer, it is not without

its flaws The one I’m drinking now took on a bit

of a ‘chill haze’ after being bottled, for example; a

minor problem that doesn’t affect anything but

the aesthetic qualities of the beer As I continue to

brew and master the craft, I’ll inevitably fix the

‘chill haze’ problem, while introducing others

Eventually, it all works out, and you achieve

‘excel-lent beer’

Trang 6

Such is the case with this magazine as well.

We’re not perfect We haven’t ever claimed to be

perfect, and as a team, I don’t think any of us

could ever foresee a day when there isn’t at least

the slightest bit of ‘haze’ However, it is the

atti-tude of this team that as long as there is not

per-fection, there is work to be done, and so we’re

constantly busy, if not with fingers to the

key-board, then with developing ideas or analyzing

weaknesses It is this attitude, and the fact that it

permeates every digital thread of the publication,

that will earn us whatever critical acclaim may

await us

Finally, beer and brewing is a learning process I

was fortunate enough that my buddy Matt was an

already experienced brewer without a convenient

location to brew, and I was a homeowner with a

large back yard and a willingness to learn Matt

and I have known each other since childhood, and

we work well together We understand each other

and relate to each other better than most other

people we know This makes for a great working

relationship, partially because we grew out of the

‘polite friendship’ stage somewhere around age

14 We constantly question and debate Our beer

thus far has been better for it This type of

work-ing relationship is invaluable in creatwork-ing anythwork-ing

of any quality

In striving for quality of material in

php|archi-tect, anyone who has written for our editorial

team will note that I take a decidedly different

approach The approach is largely the brainchild

of Marco and I, who have somehow been able to

achieve a vigorous and successful working

rela-tionship Constantly questioning and debating

each other, we’re always playing ‘devil’s advocate’

to insure that, in the end, we’ve done right by all

parties involved In the process we’ve learned

what makes this monster we’ve created tick, and

how to channel our efforts to add even more value

to our readership Our ability to come to a

‘meet-ing of the minds’ on all aspects of the publication

has brought us not only to where we are now, but

will influence the direction of the publication in

the future – for better, or for worse In reality, at

the end of the day, it’s our ability to tell each other

that our ideas completely suck that has made all

the difference!

But there is another ingredient in our recipe at

php|architect It’s the ‘recognition’ phase

Recognition of a person’s ‘highest and best use’

We seek people to join our team who we feel wecan work with, and we eventually move everyoneinto a position where their interests and skills areput to work to produce the best ‘stuff’ that theycan As I’ve mentioned from the very beginning,editorial work is not my highest and best use Nomatter how much I love editing and the editorialprocess, the reality is that a) I’m not a hardcorecoder, and b) I’m not a hardcore editor!

It is with these words that I am proud to pass theEditor in Chief torch to the very capable PeterJames Peter has accomplished much in his rela-tively short time as Senior Editor at php|architect,affecting both the outward appearance of themagazine, as well as the backend procedures forcoordinating the editorial process All by his owninitiative, and all without a thought for anythingbut the good of the publication Furthermore, as ifthis weren’t enough, he still constantly asks formore responsibility, and a greater role in the mag-azine’s creation Finally, I came to the conclusionthat the only way for Pete to do anything morewas to take my job, which would allow me to beapplied to my highest and best use as well Sofrom now on, it will be Pete’s job to try hard togive you all a reason to read the editorial columnthat I’m still convinced is a pretentious waste ofpaper (be it digital or ‘dead tree’ in form)

I’ll not be far, mind you! I’m taking on a new rolethat will also produce some really cool and excit-ing new (but as yet unmentionable) ‘stuff’ in thenot too distant future I’m excited at the opportu-nity, though I’ll always make myself available onthose sleepless nights when Pete can’t get some

‘damned Linux code’ to validate or something

I wish Pete a lot of luck, and thank him for thehard work he’s done, along with the rest of theproduction crew who have helped php|architectbecome what we are today, and what we will betomorrow I also thank all of the readers for thefeedback and guidance along the way

until we meet again

brian

Trang 7

PHP 4.3.3 RC3

PHP.netannounced the release

of PHP 4.3.2 release candidate

3

“This should be the last

release candidate prior to the final 4.3.3 release Please

test this release as much as possible, so that any

remain-ing issues can be uncovered and resolved.”

Bug fixes include:

escapeshellcmd()can now handle quoted

arguments

• exit code lost when exit()called from

register_shutdown_function()

• methods misidentified as constructors

• and much more

Visit php.netto download or view the change log

Apache 2.0.47

The Apache Software Foundation and the Apache HTTP

Server Project announce the tenth public release of the

Apache 2.0 HTTP Server

This is a security, bug fix and minor upgrade release.

Due to security issues, any sites using Apache 2 versions

prior to Apache 2.0.47 should upgrade to Apache 2.0.47

Security issues:

a Fixed a bug in the handling of accept errors

by the prefork MPM when handling accept

errors, which could allow a denial of service

attack if multiple listeners are configured

b Fixed a bug in the optional renegotiation

code in mod_ssl which could cause cipher

suite restrictions to be ignored if optional

To download, visit Apache.org

ionCube and the Cerberus Encoder

ionCube.com announced the release of the ionCube3.0

The ionCube standalone PHP encoder is a high ance encoding solution for PHP, offering encoding of com- piled code to deliver the maximum security and run-time performance for encoded file, and features to allow easy integration into build and release systems, and also web- sites for just-in-time software delivery.

perform-New Version 3.0 advantages:

a Customizing of Loader event messages

b Restricting encoded files to only cooperatewith other encoded files that have certain

‘properties’

c Improved encoding performance

In addition to Version 3.0, Ioncube has released theCerberus Encoder

This is the same as the full featured encoder, but addsthe ability to restrict files to a MAC address

For more information, visit ionCube.com.

Trang 8

PHPNuke 6.7

PHPNuke.organnounced the release of version 6.7

PHPNuke is a PHP based content management system.

This newest version fixes XSS and other vulnerabilities

and security bugs like path disclosure, and adds

associat-ed topics to the News module There are many cosmetic

changes and minor bugs fixed, and the Update folder was

It’s still a development version but takes one step

further to the stable release It contains proposal #2,

#3 and #7 of the PHPEdit Community

PHPEdit invites all users to report problems or tweaks

in 0.7.1.131 to the PHPEdit Community

PHPEdit also asks all users to vote for requests they

want to be in the next release to the Community

Visit PHPEdit.netto download

patUser 2.1.2 and 2.20

Beta

PHP Application Tools announced the release of

patUser 2.1.2 and 2.20 Beta

New in this version: bugs, notices and warnings

removed Warning: this is the last version of patUser

sup-porting patDbc, as we are switching to PEAR::DB Version

2.2.0 is the new branch supporting PEAR:DB - but keep in

mind that it is still BETA! If you are willing to test it, feel

free to send your bug reports to gERD directly “

For more information or to download, visit

PHP-Tools.de

DatabasesMySQL and PostgreSQL both announced new releasesthis month

PostgreSQL 7.3.4

PostgreSQL.org announced the release of their latestversion 7.3.4 This version addressed a potentially seri-ous (although rare) server startup failure that wasrecently reported This release is critical for users ofPostgreSQL version 7.3.3, and highly recommendedfor all other PostgreSQL users The latest version can bedownloaded from the PostgreSQL FTP site

MySQL 4.0.14

MySQL.comannounces the release of version 4.0.14.This release is a maintenance release for the currentproduction version and includes functionality such as:

a Enabled `INSERT’ from `SELECT’ when thetable into which the records are inserted isalso a table listed in the `SELECT’

b Changed optimiser slightly to prefer indexlookups over full table scans

c `FLUSH LOGS’ now rotates relay logs in tion to the other types of logs it alreadyrotated

addi-For the full list of additions and bug fixes, or to load, visit MySQL.com

down-php|a

Trang 10

Types of documents

XML is commonly used to store several types of

infor-mation Not only do developers use it in their daily

work to store configurations or define protocols, it is

also a great way to structure your everyday documents,

like letters, books, or articles Even if they can be read

with any text editor (XML is an ASCII format), XML

doc-uments are not the first choice when it comes to

docu-ments that you'd like to read in your free time The

mix-ture of tags, attributes and plain text may confuse you

while you are trying to get to the actual information

XML was designed to be read by machines, not

humans XML does not contain any layout but only the

structure of the raw data or content An XML

docu-ment consists of several tags (like HTML) which

describe the information contained within the tags

Any program may use these tags to decide what to do

with the text information between these tags This

could mean a program is able to prioritize parts of a

document, if it had to create a search index or

some-thing similar

Humans tend to decide what to do with the

informa-tion they read according to how it has been laid out If

you are reading an article, you will surely recognize that

the headline has some significance in the context of the

rest of the article, as it is printed in bold and large

let-ters

So if information has to be accessed by computersand humans, the best solution would be to presentboth species the same information in different formats.The first choice of delivering information to a machine

is nowadays XML, while PDF can be read with almostevery client and operating system, and can easily beprinted, which enables you to take the information towherever you'd like without the need for a computer

As we're living in the age of automation, you will notwant to create both versions of the information on yourown but use your friendly neighbourhood webserverand scripting language (PHP) for it This article willexplain one way to achieve this without a single drop

of sweat

Transforming documents

To automate the generation of one version of the tworequired documents, you have to define which versionshould be created manually and which one should begenerated by an application This problem is solved inthe blink of an eye, as the previous section explained

Trang 11

that XML can be read by machines, and if your

web-server does not differ too much from the one we used,

it definitely is a machine So once we have made the

decision to transform the XML document into a PDF

document, we have to stop for a moment and think

about how this transformation can be achieved

After choosing PHP as a programming language (as

this is a article about PHP, after all) we realize that the

task of distributing and accessing the document is now

simpler, as both versions can later be accessed from

anywhere in the world from our web server over the

internet

If you are familiar with transforming XML documents

you will probably be sitting at your desk yelling "Why

the $@#! aren't you using XSLT? It was designed

specif-ically for the task of transforming XML documents!"

The answer is quite simple: XSLT was designed to

trans-form an XML document to another XML document

with a different structure A PDF is not an XML

applica-tion, and it is not even based on the ASCII standard

This means you will have a hard time transforming XML

to PDF using XSLT Some of you may still be sitting

there wondering why we are not using XSL-FO, which

is able to create PDF files and uses XML as its input

for-mat We do not want to use XSL-FO as it is not very

easy to use Furthermore, it has already been discussed

in other articles, and we are here to teach you

some-thing new Call it an 'alternative method' A better way

to transform XML to PDF is to take a detour and use

LaTeX It is based on the ASCII character set, available

on nearly every operating system for free and can

easi-ly be converted to PDF documents (or other printable

formats)

A short introduction to

LaTeX

LaTeX is a document preparation system for

high-qual-ity typesetting It is most often used for

medium-to-large technical or scientific documents, but it can be

used for almost any form of publishing LaTeX is not a

word processor! Instead, LaTeX encourages authors not

to worry too much about the appearance of their

doc-uments, but to concentrate on getting the right

con-tent This means LaTeX is not edited in a WYSIWYG

(What You See Is What You Get) editor LaTeX

docu-ments can be created using your favourite editor,

whether it is vi, emacs, Homesite or even Notepad (but

not FrontPage)

This also means that LaTeX documents can be

creat-ed by any application that is able to create text files

(and of course PHP is able to do this) If you want to

view a LaTeX document, it has to be converted first

You cannot view it directly in your editor, or you will get

the plain source code of your document, not the

ver-sion including layout This would be similar to trying to

view an HTML document in vi or Notepad

LaTeX is based on Donald E.Knuth's TeX typesettinglanguage Development started in 1985 by LeslieLamport and is currently maintained by the LaTeX3Project

A typical LaTeX document looks like this

If you are familiar with markup or programming guages, you may already have guessed that this means:

lan-1 The document is an article

2 The title of the document is "Dynamic formations of XML to PDF with LaTeX"

trans-3 The article has been written by StephanSchmidt ("Hey, that's me! Look mum, I'm onTV!")

4 It has been written in April 2003

5 The document consists of a title, followed bythe text "We love XML, but everyone wantsPDF."

As there are a lot of tutorials on LaTeX available onthe web (see the end of this article for useful links), wewill only list the most important features and showsome simple examples LaTeX provides features for:

• Typesetting articles, technical reports, letters,books and slide presentations

• Control over large (and we really mean large)documents

• Control over sectioning, cross references, note, tables and figures

foot-• Automatic creation of bibliographies andindexes

• Inclusion of images

• Using PostScript or Metafont fontsBasic usage of LaTeXLaTeX documents consist of commands, macros andenvironments as well as plain text Commands alwaysstart with a backslash ("\") If a command needs param-eters, they have to be enclosed in curly braces ("{" and

"}"), and if those parameters are optional, they have to

Trang 12

be enclosed in brackets ("[" and "]") and separated with

commas (",") Typical LaTeX commands look like this:

It is possible to include comments in your

docu-ments, they have to start with "%" and end at the end

of the line (like "//" in PHP)

Environments are used to split the document into

logical parts (like tags split XML documents)

Environments always start with the "\begin" command

and end with the "\end" command

Now you know enough to start creating your very

own LaTeX document, and we will guide you through

the needed steps Each document has to start with the

"\documentclass" command, which is being used to

define what kind of document you are creating The

documentclass is responsible for the command set that

is available in your document E.g if you are writing an

article, there is no use for the "\chapter" command

Furthermore the "\documentclass" command is used

to define the basic layout style, like two column layout

or paper format

After this command you may load packages

contain-ing macro definitions uscontain-ing the "\usepackage"

com-mand Packages include features for localization

(differ-ent character sets), hyphenation, graphics or cross

ref-erences

Usually you will now include meta information about

the document, like the title, author or the date it has

been created Finally the "\begin{document}"

com-mand is used to indicate the start of the actual

docu-ment

Within the "document" environment you may use

any LaTeX command that is used to structure the

doc-ument or include graphics Common commands

include:

• \section, \subsection and \subsubsection to

structure the document

• \em to emphasize parts of the document

• \item to create lists

• \footnote (for footnotes, of course)

• \label, \bibitem, \ref and \href to createcross-references

• \includegraphics to include images

• \begin{table}, \begin{itemize} to create monly used environments

com-• \tableofcontents, \listoftables and ures to create indexes

\listoffig-• and many more

So your first LaTeX document could look like this:

OK, you have created your first LaTeX document,containing the tragedy of your life, but nobody is able

to read it What you probably want to do is to create aPDF document from it, print it and distribute it throughyour local comic book store The next section will showyou how

Converting LaTeX to PDFConverting LaTeX documents to PDF is not somethingyou do every day, but nevertheless it is quite easy,assuming you have the right software installed.Otherwise you have to install it first

If you are using Linux, there is no problem at all.LaTeX is included in most distributions, and, if not, it isavailable as an installable package for your favouritepackage manager The package is most often called

"tetex" You will find more information on the teTeXhomepage

If you are a Windows user, you should download andinstall MikTeX This should pose no problem, as MikTeX

is distributed as a Windows installer

Now, as you are proud to have LaTeX installed onyour system, there is nothing to hold you back fromgenerating the PDF version of your document All you

When I was twelve, Superman was my greatest hero.

\subsection{Our relationship grew stronger}

I first met him in person at the age of 16.

\subsection{Everything has to end}

When he died at the hands of {\em Doomsday}, I was really sad and devoted my life to Batman.

\section{My relationship to Batman}

My relationship to Batman started last week so there's not much to tell, yet.

But I already know some of his friends:

\begin{itemize}

\item{\em Robin}, the Boy Wonder

\item{\em Oracle}, the former Batgirl

\documentclass{article} % This will be an article

% This line is a comment and will be ignored later

\maketitle

\footnote{I am a footnote}

\documentclass[a4paper,twoside]{book}

Trang 13

need to do is to call pdflatex with the filename of your

LaTeX document:

This creates several files in the folder where you have

saved your LaTeX document:

• superheroes.pdf is the PDF file you wanted to

If you execute pdflatex, the

application parses the LaTeX

document from top to bottom

and generates the table of

con-tents, anchor files for hyperlinks,

PDF bookmarks and other meta

information As this data should

also be included in the PDF file,

you have to call "pdflatex

super-heroes.tex" twice to achive the

desired result

If you have done this, open

the file superheroes.pdf with

Acrobat Reader and you should

see your lifestory rendered as a

PDF document If everything

went like it should, you will

probably see something like

what’s shown in Figure 1

To get acquainted with LaTeX,

visit a tutorial on the web and

try fooling around with various

LaTeX commands and how they

are rendered as PDF

Dynamic creation

of LaTeX and

PDF documents

You may wonder why this article

has been published in a

maga-zine about PHP, and there has

not been any PHP code so far

This will change with this

sec-tion, where you will learn to

generate LaTeX documents

dynamically As LaTeX

docu-ments consist of plain text, you may use any PHP tion to modfiy them The easiest way is to dynamicallycreate a LaTeX document using "echo" statements like

func-it has been done wfunc-ith HTML for ages, capture the resultand transform it to PDF The following snippet showshow it is done:

Now open your favourite webbrowser (Mozilla, Ihope), open the script and append your name as GETparameter "name"

The URL will probably look like

http://localhost/latex.php?name=Aquaman If you viewthe sourcecode of the resulting page, you should seethe complete LaTeX source including the name youentered in the URL Save it to disk and transform it withpdflatex

Trang 14

Of course this is not what we initially wanted to do,

as you still have to save the LaTeX document and

trans-form it manually To automate the process of saving the

file to disk you should use PHP's output control and file

system functions To automate the "pdflatex" call you

can use "system" or "exec" These functions are used to

execute any command that is available on your server,

just like you would execute it in the shell

Using "echo" to dynamically create LaTeX documents

is the easiest - but also the ugliest - way to complete the

task If you are using LaTeX to create a printable invoice

for customers in your online shop, you have to mix

LaTeX (which contains content like your address) with

PHP code (which is responsible for the logic of the

invoice) The resulting files will be very hard to

main-tain, if changes to either the logic our the layout have

to be made This means you should use the same tools

that are nowadays commonly used for creating

dynam-ic HTML pages Correct, we are talking of template

engines Just use your favourite template engine (of

course, we recommend ours, patTemplate), create your

LaTeX templates and let PHP fill them with any content

you can to find You may retrieve content from the user

by supplying forms, get it from databases, or even XML

files, which is the topic of the next section

Transforming XML

documents using

patXMLRenderer

As the title of this article is "Transforming XML to PDF

with the help of LaTeX" we are now going back to

where we came from and take a look at XML

docu-ments and how they can be transformed to PDF In

order to know how to transform LaTeX to XML we have

to take a look at the gap between XML and LaTeX

doc-uments Both languages split the document into logical

expressions that can be nested as deep as you like So

the easiest way to transform XML to LaTeX is to define

a LaTeX representation for each XML tag that is used in

your documents and parse the XML document

recur-sively The result will be a LaTeX document with the

same structure and content as the source XML

docu-ment As we do not wish to reinvent the wheel, we are

relying on an existing software package called

patXMLRenderer There is online documentation for

this available at the official website

This application makes use of a templateing engine

(patTemplate) and allows you to define a

representa-tion for each tag by creating a template with the same

name as the XML tag In this template, you may access

the content of the tag and all of its attributes As the

document is parsed recursively using a SAX based

pars-er, all children of a tag are transformed before the tag

itself is transformed patXMLRenderer also allows you

to include dynamic content by overloading

name-spaces with methods of PHP classes This enables you to

include content (SOAP requests, database content, textfiles, ) while the XML file is being transformed to theLaTeX document

A sample XML file, that can be transformed to LaTeXcould look like this:

To transform this document to LaTeX (and later toPDF) you have to define representations for all tagsused in the document: article, paragraph and imp TheLaTeX templates could look like this:

The resulting LaTeX template will be:

Now all you have to do is to call "pdflatex" and theXML file has been transformed to PDF and, as prom-

\section{I lied to you}

When I was talking about {\em Superman}, I lied.

He came back from the dead and rose to the glory

<article title="Me and the superheroes, part 2">

<paragraph title="I lied to you">

When I was talking about <imp>Superman</imp>,

Trang 15

ised, you did not lose one drop of sweat We are

cur-rently developing an application that automates the

process of transforming XML to PDF and allows you to

combine several XML files through a graphical user

interface It will hopefully be available as a download

together with patXMLRenderer from our website

Common pitfalls

When transforming XML to PDF you have to be

cau-tious and avoid some common pitfalls First of all, you

have to tell patTemplate that you want to create LaTeX

files instead of HTML files This is done when creating a

new instance of the class, by passing "tex" as first

parameter to the constructor When creating LaTeX

output, variables have to be enclosed in "<{" and "}>"

instead of just "{" and "}" so they cannot be mistaken for

LaTeX commands

Furthermore, you have to replace some characters in

your XML files (quite similar to HTML entities) The

application that we are planning to release will do this

for you, so we'll just give a small overview of what has

to be done in the background:

• Some specialchars like "$", "{", "}", "_", etc

have to be quoted by adding a preceding

backslash

• " " should be replaced by "\dots"

• \\ is used to mark the end of a paragraph,remember to include it in your templates

• ~ is used to explicitly create a space, similar to

&nbsp; in HTML

A list of all pitfalls would be nearly endless, given thepossible level of complexity of LaTeX and XML docu-ments If you experience problems with any specialcharacters you should take a look the LaTeX documen-tation to see if the characters you used have any rele-vance in LaTeX documents

Stephan Schmidt is a web-application developer from Karlsruhe in Germany He started coding PHP about three years ago and decided to join the Open Source community in 2001 He is a founding member of PHP Application Tools (http://www.php-tools.net) and author of patTemplate, patXMLRenderer, patUser and other classes.

About The Author ?>

Click HERE To Discuss This Article

PHP, mySQL and Curl Optimized for OSCommerce

Free Shared Certificate & Integrated SSL Server

20+ Contributions Pre-Installed on MS1 Release

Web Mail and Web Based File Manager

Full FTP and phpMyAdmin Access

Free Ongoing Hands-On Support

Web Stats by Urchin Reports

Free Installation and Configuration

USE PROMO CODE: phpa

Get an Extended Free Trial and Free Setup!

As the publishers of Ian's Loaded Snapshot we know OSCommerce!

100's of OSCommerce powered sites rely on our years of experience with OSCommerce, direct

866-994-7377 or sales@chainreactionweb.comwww.chainreactionweb.com

www.chainreactionweb.com/reseller

Nobody

Hosts OSCommerce Better!

We Guarantee It!

Trang 16

The other day, while I was perusing through some

books at a local bookstore (computer books of

course), I noticed a book in the computer section about

Ming "Ming", I said to myself, "never heard of that"

So I began to leaf through the book and discovered

that Ming is a library of code with a set of wrappers that

one can use to dynamically create SWF format files

(compiled Flash Movies) using PHP "Oh, this is too

cool", I can remember saying; however, since I had

already blown my book budget on some others, the

Ming book went back on the shelf I did promise

myself, however, to look into this Ming library a little bit

more once I returned home So I turned to the Internet

(a fantastic invention, this Internet thing), and found

plenty of documentation and examples to get my

cra-nial juices flowing

I've finished my journey into cyberspace to seek out

Ming, and I'd like to share with you my findings Don't

worry there won't be a three hour slideshow

Let's take a little journey into the world of Ming with

PHP

The first stop is to investigate the website for the

Ming library, and this site is located at

http://ming.sourceforge.net Take the time to visit the

site and scour through the function reference There is

a nice list here, and using these classes and their

meth-ods we can do just about everything you can do

with-in the Flash authorwith-ing environment You can even add

Actionscript, which is the built-in scripting language

inside Flash

I think this library is great, and a lot of nice work has

been done here My one beef is they could havenamed the objects better to represent the Flash "lingo".For instance, in Flash you would refer to an animatedobject as a "movie clip", but the Ming project leadersdecided to call the class SWFSprite A small thing,but nonetheless for a PHP developer beginning to learnFlash and Actionscript, this could be confusing whentrying to get references and examples from the Flashcommunity

Also check out the mailing lists archive located at

http://www.opaque.net/pipermail/ming-fun/ If you arehaving a problem, chances are good that someone elsehas had the same problem, and there may be a workaround or a solution there

Did you ever have to make up yourmind?

There are some cases where it makes sense to use theFlash authoring environment, and there are some caseswhere it would be nice to dynamically build a Flashmovie As we work through some examples you willbegin to see that if you have an elaborate idea it may

be best to draw it in Flash, especially if your idea tains plenty of animations Even if you were to get

con-By Seth Wilson

PHP Version: 4.1.1+

O/S: Any Additional Software: A browser with Flash Player installed, Ming 0.2a library, MySQL

Code Directory: ming

Trang 17

fancy and really optimize the PHP code, coding a Flash

movie is a lot of work Even still, I can think of a few

applications where a dynamically generated SWF file

would be far easier to code than to draw

A couple of cool applications I can think of would

work great for a website that offers advertising space

For a basic advertising package you could create a PHP

web application where companies wishing to create a

web banner can pick from a set of pre-coded Flash

movies, and they include their own text and graphics

That way they can advertise without going through a

lengthy design and development phase just for a

sim-ple web banner Heck, they don't even have to know

Flash You could also have a dynamically created photo

gallery or slideshow based on a user's query, and add

some neat fade in/fade out or other effects Or you

could create custom e-cards where the content is

deliv-ered all in Flash Actually, that's a great idea Nobody

else use that idea, ok?

Make sure you check out a method in the SWFMovie

class called streamMP3() This one caught my

atten-tion immediately I figured what's a better example

than to make a Ming MP3 player, but first we need to

learn some fundamentals

Ming compiles your PHP code into Flash version 4

movies, and at the same time any Actionscript you

embed is compiled to Flash version 5 Why that is I

don't know, so if you are looking to add Actionscript,

please remember it must conform to Flash 5

Actionscript syntax, which is slightly different than the

newest version, Flash MX The very latest CVS Ming

version 0.3a has support for Flash MX However, this

version is not released yet, so this article will focus on

Ming 0.2a

If you do not presently have a browser with Flash

player 6 you will need to download

and install it Flash player 6 is

avail-able from Macromedia's website

(http://www.macromedia.com) and is

backwards compatible, so even

though Ming creates Flash 4 movies,

they will still be viewable with Flash

player 6

Installation

The installation on a Windows

machine is fairly straightforward as

long as you are using a recent build

for Windows I am running PHP

4.3.1 on a Windows 2000 machine,

and the Ming extension has already

been compiled into PHP All we need

to do is enable Ming by modifying

the php.ini file Locate and open the

php.ini file on your system and scroll

down until you find a section labeled

"Paths and Directories" There

should be a line just below this that begins with sion_dir =" We want to change this line to reflect thelocation of our PHP extension directory where a filecalled php_ming.dll resides If you have the defaultinstall of PHP (c:\php) on a Windows box it will proba-bly be

"exten-The second modification to the php.ini file is touncomment the line that reads

"extension=php_ming.dll", under the section labeled

"Dynamic Extensions"

Installing Ming on a Linux system is a whole differentstory There are pre-compiled PHP modules on theMing website, but these are compiled for older versions

of PHP That means you must build Ming support intoPHP yourself, unless you can find a nice soul who hasdone the compiling for you There is some documen-tation on how to do this located at

http://ming.sourceforge.net.After installation, restart your Apache server and -badda bing - you are ready to roll Of course, if you donot want to cause yourself grief, make sure that Ming isworking properly by writing a little script as in Listing 1and running it If Ming is installed properly you should

be able to scroll down and see something similar toFigure 1 If you still have problems check out yourApache log file, it sometimes sheds some light onthings

Trang 18

Flash conventions

Before we get into using Ming and draw up some

movies, we should go over some conventions with

Flash Flash movies have the origin of the movie at 0,0

This point is in the uppermost left corner From this

point the x value increases from the left to the right,

and the y increases as we go from top of the screen

downward The other hot tip to know is that an

object's depth in the movie corresponds to the order

you added it to your movie Have a look at Figure 2 to

see what I mean

SWFMovie

The first object we should look at in the Ming library is

the SWFMovieobject This is the object that handles

the creation of our movie, setting the frame rate, the

overall dimensions, the background colour, and also

handles the addition and removal of "items" These

items can be shapes, other movies, movie clips (or

sprites), buttons or text If you want to see it (or hear

it), you must add it Listing 2 shows the setup code

necessary for our movie Don't bother viewing the

movie at this point because all you will see is a blank

white screen

As you can see from Listing 2, I like to add the code

to instantiate the movie, and set all the settings right at

the beginning Then I like to jump down to the bottom

and include two more lines to spit out the Flash movie

to the browser for viewing

The first line will tell the browser what type of file this

is, and the next line outputs the finished SWF file to thebrowser Alternatively, you can output the Flash movie

to a SWF file by using

SWF_ShapeShapes are drawn using the SWFShape object, andshapes are the foundation to a Flash movie You cantake a shape that is drawn and use it for backgroundfills, add it to a movie clip or sprite, or create a buttonwith it At the same time we can fill this shape with acolour, gradient or bitmap, as well Enough talkingalready! Let's draw our first shape (see Listing 3)

In this first example we are using a few methods ofthe shape object First off, we create a new SWFShape

28 $s -> drawLineTo ( $x -( 0.5 * $height ), $y + $height );

29 $s -> drawLineTo ( $x +( 0.5 * $height ), $y + $height );

Trang 19

object, which in this case we are calling $s Then we

use the setLine() method to set the line thickness

(the first argument) and the colour (the last three

argu-ments - red, green and blue) In this case, we specify a

dark green The line

adds a light green fill (the first three arguments) to

the outline we are about to draw The last argument to

addFill()is the "alpha" of the fill Alpha can be best

explained as the opaqueness of the fill, with 0 being

transparent and 255 being fully opaque The

setRightFill()and setLeftFill()methods are

best explained in the Ming documentation

Now that we've told Ming what we want to draw, we

can now give the commands to draw The best way to

visualize this is to think about actually drawing on

paper by hand First you move your pen to a spot, put

it down on the paper then draw a line to another point

This is the exact same process used by the

movePenTo()and drawLineTo()methods

One note that I should mention here is when you arecoding any Ming project, step by step is the best plan

of attack Make sure that you have display_errors onand, as a rule of thumb, don't put your head down andbang out three hours of code, because you'll spend thesame amount of time, or more, debugging

If you run Listing 3 in your browser, you should seesomething similar to Figure 3

SWFGradientInstead of a straight colour fill, you can also fill a shapewith a gradient using the SWFGradientobject A gra-dient is basically a smooth transition from one colour toanother There are two types of gradients: a linear gra-dient, which is a line; and a radial gradient, which is cir-cular Listing 4 shows a basic gradient fill The code issetup to show the linear gradient first Just commentout the first line calling addFill() and uncommentthe line below it to see the radial gradient Make sureyou run the script in your browser to have a look atwhat it does

$f=$s->addFill(0,255,0,255);

Figure 3

Trang 20

Buttons in Flash act as a user interface with the movie

You create a button with Ming by using the

SWFButtonobject A button is basically a specialized

movie clip Once you create the

object, you can add previously-drawn

shapes to define the shape and size of

the button Without a shape, a

but-ton will not be seen by your users A

basic button has up, down, over, and

hit states, and you can define

differ-ent shapes for each button state to

create some neat effects

One downfall with Ming is you

can-not add text or other shapes to your

button You can work around this by

first drawing the button, then

draw-ing another shape over top We will

use this technique in our MP3

player

Have a look at Listing 5 (included in this month’s

package), and then run this script in your browser to

see the button in action You can tell a shape is a

but-ton, because when you mouse over the button themouse icon will change from an arrow to a hyperlinkicon

The future looks painful Let's create a class

drawShapes class

I hope you're starting to see that if youhave a movie with a bunch of buttonsand shapes, it will become very painful

to code The last example has over fiftylines just to draw the shapes for onebutton If you had even five buttons inyour movie, your code would look verymessy We could create some functionsthat will do some of the drawing, butthis is still cumbersome because youeither have a function with a hugenumber of arguments, or it would real-

ly only save a couple of lines of code.There is a solution to this problem:another object, of course I developed this class (shown

in listing 6 - also included in this month’s package) toaid in the drawing of shapes Feel free to add more

18 $f = $s -> addFill ( $g , SWFFILL_LINEAR_GRADIENT ); // Comment this to see radial

19 //$f = $s->addFill($g, SWFFILL_RADIAL_GRADIENT); // Uncomment this to see radial

Trang 21

shapes as you like.

Have a look at Listing 7, which shows the previous

example, this time using the drawShapes object That

looks a lot nicer, and is easier to follow I think so,

any-way

Animate…good times come on!!!

(Or is that celebrate?)

Everyone loves (or hates) Flash movies because of the

animations With the Flash authoring tools, you have a

nice interface in which to draw your beginning and end

shapes in different frames on the timeline, after which

Flash will happily perform all the drawing in between

Not the case with Ming Now you are the person that

will happily draw all the animation in between Really,

it's not that bad If we use our wits, and some control

structures, we can minimize some of the work

We can use the following methods to animate our

shapes

move(x,y) and moveTo(x,y)

scale(x,y)and scaleTo(x,y)

in action

Also note that you must advance themovieclip or movie frame-by-framemanually using the nextFrame()

method You can also fully animateshapes using only Actionscript, butthat's beyond the scope of this article

Let's build this MP3 er

play-I think we have most of the tools now tobuild a fully functional MP3 player, andany other tools we will pick up on thefly I have told a little white lie, it's notreally an MP3 player, but rather theplayer plays a SWF file with an embed-ded MP3 Either way, the users listen-ing will not be able to download thetrack

There are two parts to this player.The first part will be a PHP script thatwill allow a user to upload an MP3 file.The second part is the user interfacethat will have the play, stop and pausebuttons, volume control, and selectableplaylist

Upload and add scriptMP3 files will be uploaded and convert-

ed to a SWF file using a separate PHPscript from the player The script, calledupload.php, uses a library developed

by someone else (no sense re-inventingthe wheel) that will read the MP3 head-

er information and the ID3 tag Theheader information is needed to grabthe length of the song It is absolutelyimperative to retrieve this informationbecause when we embed the MP3 into

a SWF file we need to make sure the

Trang 22

SWF file has enough frames to encapsulate the entire

song The ID3 tag information is stored into a MySQL

database and is used by the player to display track

information

The HTML form is called addplaylist.html, and

is shown in Listing 9 It is the front end for the

upload.php script, shown in Listing 10 (included in

this month’s package)

We need to modify the php.ini file again to make

sure the file is uploaded and processed properly Open

up your php.ini file and search for the line that reads

and change to something appropriate like

We also need to change the input and execution

times to accommodate the larger sized files Change

these settings to

You may need to fiddle with these settings if you are

uploading files larger than 8 megs

As I mentioned, the script that handles the

process-ing is called upload.php and can be seen in Listprocess-ing

10 The script performs some basic validation of the

uploaded file, strips out the ID3 tag and stores that as

a new database record It then processes the MP3 by

embedding it into an SWF file The Ming library is used

for the last step, and the newly created SWF is saved to

the local disk Make sure you have permissions set forthe directory to be able to write files, or you couldchange the script slightly to suit your tastes There are

a few variables in this script that you may have tochange to suit your system The first variable is

$uploaddir You will have to change this path toreflect where your player script resides The other vari-ables that could be changed are $user and $pwd

which are used for accessing the MySQL database

I have run into some problems uploading MP3 filesthat have no ID3v1 information I know this is a painbut try and make sure there is ID3v1 information in theMP3's you upload

For those worried about security (and we all shouldbe), having any Regular Joe upload a MP3 file to theirserver would keep them up at night Think of this script

as an administration tool then, don't put it online, andsleep well

The player interface(See the complete listing for the player in Listing 13, inthis month's package)

Let's make the interface look cool I thought thatusing a radial gradient that transitions from black towhite transparent, and placing the center of this gradi-ent in the four corners of the rectangle shape wouldlook really neat The only way to do this is to createfour identically sized shapes and place one gradient indifferent corners Run Listing 11 (also included in thismonths package) in your browser to see the effect I'vebeen talking about

Next up is to add some text fields We will use threetext fields for our player One text field will containinformation on which track is currently being played,another will be a status bar and the last will serve the

4 <title>Add Song To Ming Mp3 Playlist</title>

5 <meta name="generator" content="editplus">

6 <meta name="author" content="">

7 <meta name="keywords" content=" ">

8 <meta name="description" content="">

18 <input type="hidden" name="MAX_FILE_SIZE" value="8388608" />

19 Add this MP3<input name="userfile" type="file" />

20 <input type="submit" value="Send MP3 File" />

Trang 23

purpose of a scrolling playlist I have not covered how

to add a text field, so I will do it now

A text field cannot be animated but it can be

dynam-ically changed during the movie's timeframe When

you instantiate the SWFTextfield object,

you can specify the behaviour of the text field by

specifying different flag arguments The flags are listed

below from the Ming documentation You can set

mul-tiple flags by using the bitwise OR operator ( | )

Valid text field flags:

You can also specify the height, width, type and size

of the font using the methods of the SWFTextField

object You can even specify the instance name of the

text field so that you may populate it dynamically using

Actionscript

The status bar text field for our player will be named

"status", and will be the default, non-editable text field

The second text field, which will contain track

informa-tion, will be named "trackinfo" The scrolling playlist

will be non-editable, non-selectable, multiline, and will

contain HTML code This is an undocumented flag for

an SWFTextField, called SWFTEXTFIELD_HTML, thatwill make our text field render HTML code We want torender this text field as HTML so that each track will belisted with a hyperlink which when clicked on will loadthat song into the player Once you see you see theActionscript it will make more sense

Now we can add our buttons to play, pause, andstop, as well as volume controls and scrolling buttons

The buttons for track control will be circles, and the ume and scroll buttons will be triangles ThedrawShapes class comes in very handy Have a look atthe listing to see the addition of the buttons Let'smake our buttons a cool X-box green, with dark greenborders

vol-With buttons, come actions

Of course, now that you have a button, you want to beable to do something once the user clicks on it Youcan add Actionscript to a button, movie clip or themovie itself All actions are added using the

SWFActionobject

You can add many Actionscript statements inside oneadd SWFActioncommand, just make sure to end eachActionscript statement with a semi-colon

It's very simple to add Actionscript to a button The

SWFButton object has a method called

addAction(), and the first argument we pass to thismethod will be an SWFAction object complete withthe Actionscript The second argument is a flag to tellFlash after which button event this code should becalled

$b->addAction(new SWFAction("_root.mp3.play();"), SWFBUTTON_MOUSEUP);

SWFTEXTFIELD_NOEDIT indicates that the field shouldn't

be user-editable

SWFTEXTFIELD_PASSWORD obscures the data entry

SWFTEXTFIELD_DRAWBOX draws the outline of the text field

SWFTEXTFIELD_MULTILINE allows multiple lines

SWFTEXTFIELD_WORDWRAP allows text to wrap

SWFTEXTFIELD_NOSELECT makes the field non-selectable

$t = new SWFTextField([$flags]);

Have you had your

PHP today?

Visit us at http://www.phparch.com

and subscribe today php|architect

• Subscribe to the PRINT edition

• Subscribe to the ELECTRONIC edition

Trang 24

For the volume controls, we have a few lines of

Actionscript When the volume up or volume down

buttons are clicked the Actionscript global variable

called Vol will be incremented or decremented

accord-ingly, then a new Sound object will be created, and will

be passed this new volume setting

The scroll up and scroll down buttons also have some

Actionscript code They access a property of the text

field called 'scroll' If the playlist has more items than

what can be seen in the text field, these buttons will

allow the user to scroll up or down to see more items

This scrolling action is done byincrementing or decrement-ing the scroll property of thetext field

Add some fancytouches withMySQL

We are going to also harnessthe power of MySQL, and use

it to hold information aboutthe MP3 Ultimately, we areusing an SWF with an embed-ded MP3 file, so we cannotgrab any information aboutthe MP3 unless it is storedsomewhere else We are going to use the same data-

base to populate the scrolling playlist, and also to

retrieve information about the current track being

played Listing 12 shows the SQL file to import the

table structure into a MySQL database Let's call the

database "mp3stream", and import this information

into it

Now, last but not least, we can now add a movie clip

or SWFSpritethat will act as a container for the MP3embedded SWF file Let's call this movie clip (sprite)

"mp3", and leave it empty for now because we aregoing to add the MP3 dynamically using Actionscriptcode

Actionscript for the movieThere are only a few lines of Actionscript to get thiswhole movie going (see the bottom of Listing 13) Thefirst thing we do is set the initial volume using the pre-viously mentioned Vol Flash variable Then we load theSWF movie containing our MP3 using the loadMoviefunction into the empty movie clip called "mp3" Next,

we create a new Sound object to handle the volumeinitially Lastly, we add the track information into thetextfield That's it We are ready to press play….so go

on, press play

All of this code is neatly commented and can be seen

) TYPE=MyISAM;

Listing 12

<? Tap Internet PHP Training Courses ?>

Been handed a PHP project and don't quite know where to start? Itching to learn PHP in a classroom environment?Tap Internet has trained hundreds of PHP developers over the past 2 years, and is the largest independent PHP trainingorganization in the U.S We provide complete PHP training solutions for all levels, including on-site courses

PHP Beginner- $999

Next class: Sept 22-24, 2003

A 3 day course providing beginners a solid

Next class: Sept 15-18, 2003

A full 4 days with all topics from PHPBeginner plus:

Next class: Sept 29-31, 2003

A 3 day course covering the LogiCreateapplication server

• Installation

• User management

• Custom permission systems

• Rapid application development

• Error handling

All classes feature hands-on instruction with friendly experienced teachers Each student is assigned an individualworkstation, and class sizes are limited to increase personal instruction Lunch and snacks are also provided

Call 1-866-745-3660 or 734-480-9961 to book your seat now or visit http://www.tapinternet.com/php

“For those worried

Trang 25

in Listing 13 The finished player can be seen in Figure

4

How to make this better

To make this script a full blown application, we would

have to add a few touches to really make it polished A

pre-loader would be essential to show users on slow

connections that the MP3 is loading A Flash version

check would also be really slick That way you can

direct users that do not have the Flash plug-in installed

to Macromedia's site The ultimate touch would be a

Winamp-style visualizer with some cool animations that

would really make your CPU smoke

You could change the architecture of this script a

small bit, and have the script embed the MP3 into the

SWF on-the-fly (rather than creating it up-front) This

would limit the size of media files on your server, but

will slow the performance of the script significantly

A second step in the file upload procedure allowing

users to add or change the ID3 information before

sav-ing to the database would be nice feature, I think Also

adding more shapes to the drawShapes object would

be nice Hearts, stars, more geometric shapes like

pen-tagons, hexagons and the like would be really helpful,

as well

So what is this script really good

for?

I think this script would be great for anyone who wants

to offer some audio content on their website If you are

a motivational speaker or a local garage band, and youdon't want people to grab your content this might be

a solution for you Since this player uses Flash, you aregoing to reach nine out of ten Internet users withoutthem having to download a separate plug-in

Acknowledgements

I would like to thank a regular contributor to the Mingmailing list, Armel Grignon at mingshop.arpane.net,who indirectly, through his posts to previous queries,helped me immensely I would also like to thank theauthor of the mp3.inc.php script I searched high andlow for the author, but came up empty Thanks for sav-ing me some work!

Seth Wilson runs his own computer consulting business based in Waterdown, Ontario, Canada He enjoys breaking and fixing comput- ers, writing code, playing, watching, and talking hockey and rollerblad- ing with his wife Trish

About The Author ?>

Click HERE To Discuss This Article

http://www.phparch.com/discuss/viewforum.php?f=38Figure 4

Trang 26

After months of patient wait, hundreds of submissions

and hours of deliberation, it’s finally time to pick two

winners for our Grant Program

The choice was made particularly tough by the fact that

of the over 200 submissions we received, many were

either original applications that broke new ground, or

established platforms that were looking to expand in new

directions

However, having a clear goal helped us a great deal: we

wanted to find (and fund) two projects that were capable

of demonstrating that PHP is a worthy platform in highly

demanding environments and industries In the end, we

had to make a choice so, to quote Zapp Brannigan from

Futurama, “without further adieu”, here are this year’s

winners!

Nurse—I need some PHP stat!

There are few industries that are

as demanding and exacting as

healthcare After all, a mistake of

any kind could mean serious

harm to a patient—this is an

environment in which the

expression “blue screen of

death” takes on a whole new

(and much more ominous)

meaning

We were quite surprised,

therefore, when we found out

that a group of developers were

working on a hospital

adminis-tration platform based entirely

on PHP, called Care 2002 After

a chat with the team leader, and

a quick visit to their website

(http://www.care2x.com) we

were convinced that this team

was on to something big A

hos-pital implementing a Care

2002-based management solution

would be a great vote of

confi-dence for PHP from an industry

sector where “tolerance for

error” is usually in the same

sen-tence as “zero”

“Care 2002 is software for

hospitals and health care organizations, designed to integrate the different information systems existing in these organizations into one single efficient system,” says team leader ElpidioLatorilla “It solves the problems commonly found in a net-work of multiple programs that are incompatible witheach other It integrates almost any of the services, systems, departments, clinics, work processes, data, com-munication, etc., that exist in a hospital Its design caneven handle non-medical services or functions like securi-

ty, maintenance, surveillance, etc It is also urable, modular and scalable.”

user-config-Care 2002 uses standard SQL The use of a single dataformat solves the problem of data redundancy With itsdatabase abstraction layer, it can support different data-bases The entire system is web-based, and all its functionscan be accessed with a common web browser Therefore,

Granted!

Announcing the winners of the 2003 php|architect Grant Program

Trang 27

side, updates and extensions do not require changes on

the browsers, eliminating the need for network

interrup-tions and downtimes

According to Elpidio, his team chose to use PHP for their

project mainly because of its stability, portability and ease

of use

Even though it was started in 2000, Care 2002 is still in

beta—for the most part, due to the grueling requirements

imposed on it by its intended audience Still, many parties

have expressed interest in implementing it at their

health-care facilities once it exits from its long beta testing cycle

We’re happy to announce that our grant will be put to

good use As the project’s final stable release comes close,

the team is planning to do numerous presentations, and

our contribution will go towards the purchase of hardware

needed for these events Assisting the success of a project

like Care 2002 is what makes the Grant Program so

impor-tant to us

Let’s manage a network just for

fun

The second winning entry in our program comes from a

group who’s trying to work in what is perhaps one of the

more demanding sectors of I.T.: network management

Just for Fun Network Management (JFFNM), available at

http://jffnms.sf.net/, is a complete suite of extensible

net-ment in 2002 and it has rapidly become a widely-usedopen-source project, fueled by the power and ease ofdeployment of PHP

JFFNM, which is used in about 300 mid-sized networks,contains a total of over 16,000 lines of code That maysound like a lot, but given its functionality, we were sur-prised that so little was needed to make it function JFFNMsupports all sorts of network management functions, such

as SNMP integration, Tacacs+ Authentication andAccounting, Syslog Logging with PCRE Matching, SNMPTrap Handler, TFTP Configuration, Smokeping, MSyslogand Syslog-NG “Using PHP allowed us to reuse all possi-ble code,” says Javier

The JFFNM team has a long list of needs that our grantwill help to cover, from new hardware to actual develop-ment time for the introduction of new features, such asnetwork auto-discovery Congratulations to the entireteam, and keep up the good work!

php|a

More screenshots at http://jffnms.sourceforge.net/shots.php

Trang 28

Visit www.zend.com

for evaluation version and ROI calculator

Zend Performance Suite

Reliable Performance Management for PHP

Serve More.

With Less.

Trang 29

of support for multiple database servers, feature list,and price were unbeatable Unfortunately, though, I’vebeen recently searching for a replacement Dezign 2was two years old, with no major updates, and wasbeginning to show its age Much to my dismay, thereare no products even close to its price point.

Finally, earlier this month, Dezign 3 was released Itfeatures a shiny new interface and lots of new features

I was eager to play with this new version, and I thought

I would share my experience with you

rela-I couldn’t have said it better Dezign allows you tovisually design your database schemas If you’ve everworked with a large CMS like Drupal or PostNuke, youmight be vaguely familiar with the enormous database

structure lurking beneath Imagine trying to design

that structure in phpMyAdmin Simply specifying thefinal layout of a system like this could be a traumatizingexperience

If you do any medium- or large-scale work with bases, you know that having a visual representation isimperative, especially in the design phase Using a toollike Dezign, I can try out my wacky database layout

NT, Windows 2000 and Windows XP.

"DeZign for Databases" requires a mum of 16MB RAM and will run on a 486 processor Disk space requirements is 6

MS SQL Server

MS Access SQLAnywhere

Sybase Informix Pervasive Advantage DB DBISAM FoxPro

CA Clipper PostgreSQL

Trang 30

ideas with little effort I couldn’t do that easily on the

command-line, or using a tool like phpMyAdmin Plus,

being a visual person, I enjoy the abstract

representa-tion that modeling tools like Dezign offer

Without further delay, let’s take a look and see if this

new version of Dezign stacks up

IInnssttaallllaattiioonn aanndd CCoonnffiigguurratiioonn

I downloaded the 30-day trial from the Datanamic

website, and ran the installer with no problems

Although there are plenty of ways to configure the

interface, no initial configuration was necessary

On first run, a sample entity-relationship diagram

(ERD) came up automatically Dezign ships with a

number of example files, which could be very helpful to

someone just starting out

One thing to note for anybody upgrading from

Dezign 2 to Dezign 3 is that it will automatically

con-vert your v2 files to v3, letting you know what it had

problems with Note that this conversion is irreversible,although Dezign helpfully (and thankfully) saves abackup copy of your v2 file

D

Deessiiggnniinngg wwiitthh DDeezziiggnnThere’s certainly a lot of functionality in Dezign 3 Asyou start to build your ERD, you are afforded a greatdeal of control over your design

As an example of the plethora of options, let’s look atadding a table (or entity) Upon specifying that youwant a new table, you have the option to add attributes(or fields), indexes, triggers, table constraints, extrascripts, a detailed description, and a set of TODO’s.And each of these options has it’s own set of detailedoptions

Amazingly, the huge amount of configurability doesnot detract from the simple tasks If you just want toget your structure in there, it’s very fast If you want totake your time and set everything up with proper

Figure 1

Trang 31

defaults, constraints, and indexes, then it’s going to

take a little more time

A really cool feature is that you can maintain multiple

diagrams (or views) of your main schema This includes

subsets of tables, meaning that you can have a main

diagram of your whole ERD, and then provide more

concise and more documented diagrams of the user

management system, or the commerce system, all the

while maintaining only one physical table set

Adding relationships between entities has become

really easy in Dezign 3 One-to-many relationships are

doable in two clicks and a drag Many-to-many

rela-tionships require a comparable amount of work, but

automatically create the association mapping table,

which saves a fair bit of effort

The help system in Dezign is quite thorough, and

even includes a section on database theory I must

mention, though, that the Dezign help system doesn’t

contain a single screenshot or icon This may sound

nit-picky, but – again – I’m a visual person Explaining

the options on a dialog or a toolbar is fine, but I like

pic-tures Especially ones with arrows

Trying to support as many database systems as

Dezign does is an amazing feat, especially if its done

well I can’t comment on the other RDBM systems

sup-ported by Dezign, but PostgreSQL support is actuallyquite good There are a couple of quirks here andthere, but nothing that will prevent you from beingmiles ahead of where you were And some of thesequirks can be immediately addressed by one ofDezign’s coolest features: the template system

Dezign allows you add your own new database type

I found this interesting, and poked around trying tofind out how it works Dezign maintains a list of tem-plates for each database type that it supports Thereare a handful of files necessary to add a new type, butusually it is acceptable to just copy and modify filesfrom other database types

Besides the configuration directives and data typespecifications, you also must provide a template file.The templating language is a subset of Pascal, making

it pretty easy to work with Although there is zero umentation (that I could find) on the templates, I found

doc-I could make significant changes inside of about 20minutes of first looking at the files Of course, youprobably want to back up your original copies first, soyou don’t irreversibly change something important

While the support for triggers and procedures isthere, it’s pretty basic There is a semi-highlightingcode editor, but it doesn’t do much more than that In

Figure 2

Trang 32

order to add triggers to PostgreSQL using Dezign, I’d

have to pretty much not use the trigger interface, and

just stick with the general SQL editing box But I’m

going to say that this is really just a function of having

to support multiple database systems

A very simple report generator has been incorporated

into Dezign 3 This allows you to specify complex

tem-plates (again, using the Pascal subset), and build your

own reports The HTML reports require a stylesheet,

and this allows even more flexibility in your reports

Dezign offers the ability to print your ERD, as well as

exporting it to any of a number of image types This is

nice for presenting your design to pointy-haired

boss-types

Dezign helps you manage document versioning The

system is pretty simple when compared to CVS, or even

RCS, but it is nice to have it built in

Speaking of CVS and RCS, Dezign’s file formats are all

plain text, including some XML This means that

stan-dard version control systems will work properly and

usefully

W

Whhaatt II lliikkeedd

I really like the easy specification of table relationships

That’s going to save me lots of time

The template paradigm is awesome Datanamic has

really taken a step forward and put the power back

where it belongs If you can offer this sort of extension

system to your users, your product will almost certainly

enjoy a longer and happier life

The diagram system is great Being able to cut up

your larger ERD into small bite-sized pieces is invaluable

when it comes to explaining it to other people

W

Whhaatt II ddiiddnn’’t lliikkee

I didn’t like the help system; I found it was plain A helpsystem may not seem like an important bell to ring Imean isn’t the help content the important part? Yesand no The help system is what acquaints users withyour product If your help system is not strong andengaging, people are not going to learn your productproperly

I didn’t like the lack of documentation on the plating systems Perhaps this is in the works, but it isgoing to be noticed and people are going to want touse it We need documentation

tem-The support for triggers and procedures leaves much

to be desired, at least for me But again, this comesdown to supporting many database types

php|a

In conclusionAfter using Dezign 2 for two years, and reallyenjoying it (for the most part), I’m really likingDezign 3 It has a very nice interface, lots of fea-tures, and an eye for the future I suggest youdownload the evaluation copy, and see if it canmake you more productive I give DatanamicDezign for Databases a 4 out of 5

Publish your data fast with PHPLens

PHPLens is the fastest rapid application tool you can find for publishing your databases and creating sophisticated web applications Here’s what a satisfied customer, Ajit Dixit of Shreya Life Sciences Private Ltd has to say:

I have written more than 650 programs and have almost covered 70% of MIS, Collaboration, Project Management, Workflow based system just in two months This was only possible due to PHPLens You can develop high

quality programs at the speed of thinking with PHPLens

Visitphplens.comfor more details Free download

Trang 33

There are two main parts to our system, the client and

the server, both written in PHP The client part, when

executed, connects to a server through a port and

address using the fsockopen() function In the

examples we cover in this article, the client will

actual-ly be used to connect to a number of servers The

serv-er is executed when it is called by the xinetd daemon

xinetd is the successor to inetd, and is common to

recent distributions of RedHat Xinetd is a super-server

- a server that listens on many ports and executes the

appropriate service when a request is made to a certain

port For example, if xinetd were watching port 23, it

would probably start the Telnet service when a request

came through

In this article, we'll examine two scenarios The first

deals with a small web hosting company with three

dif-ferent servers having trouble centralizing control of

their accounts The second scenario demonstrates the

construction of a simple load monitoring system for

several servers Let's get started!

Case study 1: Multiple-Server

Control Panel

Let's imagine that we're running a small web-hosting

company and that we're operating a couple of web

servers Our web servers each came packaged with a

web-based control panel, but it's clunky and slow and

we want a better way to manage customer accounts.Fortunately, the web servers also came with a fairlyrobust suite of command line account-managementutilities

"But," a small voice in the back of your head may ask,

"how can we turn these sleek command line utilities toour advantage?"

"With our PHP client/server solution of course!" thecopious other voices inhabiting your mind shouldinstantly reply ;-)

Let's think this through We have several web servers

to operate on, each one with a set of utilities we canuse to manipulate customer accounts and we'd like to

be able to manage all of the web servers from a singlecontrol panel instead of with each individual machine'scontrol panel - how can we put this together?

We'll start with the idea of a central control panel.The obvious candidate for this is the PHP client Whatabout the PHP server? Not-so-coincidentally, our webservers are the ideal choices for the server part of oursystem

S

By Eugene Otto

PHP Version: php 4.0.6+, CLI, O/S: Unix/Linux

Additional Software: MySQL Code Directory: sockets2

EE In one of last month's articles, we talked about building a client/server system with PHP and xinetd This month,

we'll run through a couple of case-studies showcasing a

couple of ways to employ this very powerful technique.

We'll start with a quick review.

Trang 34

Figure 1 shows a basic diagram of the setup of our

client-server system

The Client

The client will have access to customer data (through a

MySQL database, we'll say) A few fields would be

domain name, service plan, e-mail address, username,

password, and a unique ID number to help us identify

accounts Listing 1 shows the SQL code for creating

the table we'll be using Listing 2 shows a row of our

database where I've inserted some data for testing

The client will also contain a list of our web servers

and their addresses In this simplified control panel, the

administrator will be able to view a customer's records

and select a server for the customer's account Our

client code is shown in Listing 3 (included in this

month’s package)

We start out by connecting to MySQL and storing a

customer's data in an associative array - note that for

simplicity, I've hard-coded the customer's ID number

into the script instead of first printing a list of customers

for the administrator to choose from

Next, I've thrown in two

func-tions that I often use to help me

organize my PHP code, as well as

the HTML output PrintLn()

simply echoes whatever was sent

to it in $Line and appends a

new-line character During

debugging sessions, I've often opened up my HTMLsource to try to find a problem but been dismayed tofind one long line of HTML Using our PrintLn()

function instead of print or echo will space out ourHTML output very nicely and will help us keep our PHPcode free of new-line characters

PrintSoc()is similar to PrintLn()except that ituses the fputs()function to print to a network sock-

et Although it doesn't impact HTML output, it doesadd a necessary new-line character which is recognized

by servers as a separator argument It also cleans upour PHP code by minimizing the number of new-linecharacters we have to append in the actual code

Next, the if-statement checks to see if our form wassubmitted If so, a connection is opened to the serverthat was chosen The server we'll be writing later onwill run on port 64401, so we're setting up our client toconnect to that port If the connection fails, an error isreported Otherwise, our pass-phrase and the cus-tomer's domain name, service plan, e-mail address,username, and password are sent across the server con-nection The pass-phrase is a form of authenticationknown as a handshake where the client and server basi-cally introduce themselves Finally, we read and printout any output that is sent from the server until theconnection is closed - hopefully the information theserver sends us will say that the customer's account wascreated successfully

Figure 2 shows a screenshot of what our barebonescontrol panel looks like in a browser

Although we've left it out here, last month's articlediscusses encryption as an important security measure

mysql> select * from customers;

CREATE TABLE customers (

Domain varchar(255) NOT NULL default '',

ServicePlan varchar(32) NOT NULL default '',

Email varchar(255) NOT NULL default '',

Username varchar(32) NOT NULL default '',

Password varchar(32) NOT NULL default '',

id int(5) NOT NULL auto_increment,

PRIMARY KEY (id),

Trang 35

Encrypting the customer's information before

transmit-ting it to your server would be a wise decision in order

to try to be as safe as possible

That about does it for our PHP client, now let's work

on our server

PHP Server

The purpose of our server (shown in Listing 4) will be

to act as an intermediary between our client and the

account creation utilities local to the server It will need

to be executed from the command line, so we'll have

to add a few arguments usually not seen in a normal

PHP script

If you're unfamiliar with shell scripting, the most

apparent difference is probably line 1 This line simply

tells the operating system the location of our parser

The -q argument tells the PHP parser to go into quite

mode, which means that the HTML headers that are

usually added to our output will be suppressed

The next two statements set STDIN and STDOUT as

streams to standard input and standard output These

constants will be used as the means for reading and

writing information to and from the client

Note that if you're using PHP 4.3.0 or above, the -q

argument on line 1 and the definitions for STDIN and

STDOUT are unnecessary as they will be defined by

default

Next, we read in our pass-phrase from STDIN using

the fputs() function and trim off any white space

that might have come through We compare the

pass-phrase to our hard-coded answer, and if it doesn't

match, the script is exited

If all is well thus far, we continue on and read in the

customer's account information I haven't included it

here, but we can put in some error checking and return

an error message if a variable turns out to be invalid

We now construct a command string with the path

to our account-creation utility and the necessary ments I've chosen to use the shell_exec()function

argu-to execute the utility so that the utility's output will bereturned, giving us a little more control over how tostore it In this example we've simply returned it to theclient by printing it to STDOUT, but we could havestored it in a local database or used any of a number ofother methods to communicate the result of the com-mand

We finish by closing the STDIN and STDOUT streamsand exiting the script

One last thing we have to do before this script willrun is chmod it so that our system knows that it's anexecutable file See how this is done below Notice thechanges in permission settings

[root@ns1 root]# ls -l server.php -rw-r r 1 root root 5 Jul 8 04:25 server.php [root@ns1 root]# chmod 755 server.php

[root@ns1 root]# ls -l server.php -rwxr-xr-x 1 root root 5 Jul 8 04:25 server.php

[root@ns1 root]# chmod 755 CreateAccount

As you can see, the dummy script is very minimal anddoes absolutely nothing with the arguments sent to it,but it will provide an indicator of how wellserver.phpworks

Now, follow the interactions shown in Listing 6 Wefirst execute the server and then enter a few values tomake sure that everything works as expected

1 #!/usr/bin/php -q

2 <?PHP

3 define ( 'STDIN' , fopen ( 'php://stdin' , 'r' ));

4 define ( 'STDOUT' , fopen ( 'php://stdout' , 'w' ));

10 $Domain = trim ( fgets ( STDIN , 256 ));

11 $ServicePlan = trim ( fgets ( STDIN , 256 ));

12 $Email = trim ( fgets ( STDIN , 256 ));

13 $Username = trim ( fgets ( STDIN , 256 ));

14 $Password = trim ( fgets ( STDIN , 256 ));

fputs ( STDOUT , "Account created successfully! \n" );

Listing 6

Ngày đăng: 18/10/2013, 22:15

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN