Posts filed under 'php articles'
Refine and debug PHP applications with syslog
PHP version of venerable UNIX syslog offers a simple, effective debugging tool
An old technique for exploring a running program is to place code that “displays” the current value of variables at strategic points. But how is this done without interfering with the standard output of the program? With PHP’s
syslog()facility, examining these values is easy. Find out how.
<!– if (document.referrer&&document.referrer!=”") { // document.write(document.referrer); var q = document.referrer; var engine = q; var isG = engine.search(/google\.com/i); var searchTerms; //var searchTermsForDisplay; if (isG != -1) { var i = q.search(/q=/); var q2 = q.substring(i+2); var j = q2.search(/&/); j = (j == -1)?q2.length:j; searchTerms = q.substring(i+2,i+2+j); if (searchTerms.length != 0) { searchQuery(searchTerms); document.write(“
“); } } } //–> Programming a computer is a tedious business, but it’s fun, too. One of the fun aspects of programming is learning about new ways to use an old tool. Recently, I was contracted to fix a dozen bugs in a large, complex, Linux®, Apache, MySQL, and Linux, Apache, MySQL, PHP/Perl (LAMP)-based content-management system (CMS). The architecture of the CMS was the standard LAMP model, with Enterprise Red Hat Linux running Apache V2.0. The code that drove the Web sites consisted of a few hundred PHP source modules spread out over 30 subdirectories in the Apache document root directory. The Apache and MySQL portions of the system required no changes, so all my bug-busting activities were to occur in the PHP workspace.
After spending considerable time learning how the CMS worked, I grew to appreciate the system’s elegant design and I realized that, as in most mature programming environments, this system relied on only a small number of the available PHP functions. (Shades of the old 80/20 rule here, where 80 percent of the work is accomplished with 20 percent of the available functions.) This article shows how the process of debugging an unknown but complex system can help you learn about those little-used functions and provides examples of how to apply your new knowledge by using the rich functionality of the syslog() function.
With literally hundreds of functions available in the PHP programming language, some (dare I say most?) functions are never used unless you read about them in articles like this one. Another way to learn more about the language is to debug programs that others have written in it. I’m always impressed by the creative ways in which programmers use the tools.
Debugging, like computer programming, is part science and part art. When tracking down obscure bugs in a system that you didn’t create, you need to have a good feel for where they manifest themselves in the code. With hundreds of code modules to deal with, a good place to begin is where the output revealing the bug is found, then work your way backward from there to isolate the problem.
Say, for example, that a calculated value that was being output is known to be incorrect. You must devise some way to see the intermediary values that lead up to the problem. Another problem may manifest itself with bad data coming from an important database query. You need to be able to see the SQL statement generated (and submitted by the code to the MySQL engine) to see whether that’s where the problem lies.
One age-old technique for doing this is to insert code that simply prints these strings and values. Unfortunately, with a tool like PHP, or any Web-based application, you don’t want to clutter up the natural output of systems like this (that is, HTML code being sent to the browser) with debugging information, especially if the system you’re examining is a production server.
You could create a custom logging file and write log messages to it, but why not use the tools that have already been provided for you? Always remember: Don’t bury your tools. The time spent seeing whether the language authors have already provided a library routine or function to do something you suspect would be a commonly needed function is well spent. In fact, anytime you suspect that something should obviously be part of a programming package, it probably is.
I realized that what I needed to use was something similar to the syslog functionality of UNIX®. I thought it likely that PHP would have a hook into the syslog functionality, so upon a quick review of the PHP documentation, I found it! The PHP syslog() function is one that I had overlooked for many years until I was contracted to do this project. With syslog(), I was able to hunt down and exterminate most of the bugs in the production system without introducing side effects other than the minute amount of time it took for each function to execute.
As you grow in your knowledge and become more skilled in your craft, different ways of doing things become apparent, and some way will eventually become the obvious way to perform the required task. What you must always keep in mind is that what is obvious to you is not obvious to other people. What may be simple to you can present a mountain of complexity to others.
Using a tool like the syslog() function keeps complexity under control and provides the added benefit of allowing easy customizations through configuration files, such as syslog.conf. For example, you can insert code to format a SQL statement, log it to syslog(), and pass it to MySQL for execution. Later, a slight modification of the syslog.conf file sends the text to a different log file or perhaps just to the bit bucket. Weeks or months later, if it becomes necessary to see what’s happening again, another simple change to the syslog.conf file will restore the functionality.
|
syslog has a rich and colorful history in the UNIX world. Originally developed as part of the Sendmail project, syslog had proven to be so useful that many other tools have incorporated in its functionality, proving that the simplest ideas are sometimes the most powerful.
In a nutshell, syslog allows applications to write tagged messages to a common set of system log files that can reside where it’s convenient for the programmers and network administrators to access. This means, for example, you can configure syslog on a Web server to log system messages on a different server — one that is perhaps a few layers deeper behind the security firewalls and easier for the aforementioned administrators to access. But for my purposes, I just accept the default behavior of files being written to the /var/log directory.
The syslog mechanism is started at boot-up, and its initial behavior is defined by the rules in the syslog.conf file. These rules enable you to finely tune what can and cannot be logged with the mechanism — which, on a high-volume, hard-working server can translate to log files of a manageable size.
Each rule consists of two fields: selector and action. Basically, the selector field selects what facility will be logged (for example, kern, user, mail, lpr) and what priority the facility has. The priority field contains a keyword, such as debug, info, notice, or warning. And the action field of a rule defines what to do with messages of a kind that match the selector field. The rules can specify which file to log the message to, what machine to send the logging message to, what user to send the message to (in the form of console messages), etc.
|
Study the info and man pages associated with the syslog facility to learn how to configure the system for your needs. In my case, I needed to know what the value of various PHP variables were at different times while the production CMS system was running. I also needed to know when certain modules were started and ended, as well as what various intermediate variable values were. Before getting into specifics about what to log, let’s set up the basics for logging.
With your favorite editor, create the file shown in Listing 1, name it test.php and put it where your Apache document root is found (on my system, it’s /var/www).
Listing 1. test.php
<html>
<head>
<title>PHP Test Page</title>
</head>
<body>
<?php
syslog(LOG_NOTICE, "{$_SERVER['REMOTE_ADDR']}: test.php - PHP Index page accessed.");
echo '<p>PHP Test Page</p>';
?>
</body>
</html>
|
You should have PHP installed and configured, as well. If not, check Resources for links on how to do this. If you configured everything properly, you should see the following text in your browser when you access the page with the URL http://localhost/test.php:
PHP Test Page |
Next, open an X terminal window and type the following command to see what was logged to the /var/log/messages file:
tail /var/log/messages |
If all goes well, you should see a line like this one near the end of the listing:
Jul 23 14:43:42 localhost apache2: 127.0.0.1: test.php - PHP Index page accessed. |
If you did, that’s great. You have now verified that all you need to do to begin detailed debugging of the complex system you’re working on.
I have found it a good practice to use syslog() for all the PHP/MySQL calls so that every time you interact with the Web site, you can see which SQL queries are generated in real time to build the page returned to you. A handy way to make this work is to open a spare X terminal window and use the tail command with the -f option for “live” viewing of the messages log:
tail -f /var/log/messages |
|
Now that you’ve verified that the logging works and that you can see the results of the logging mechanism, here are a few tips for shortening the process of learning a foreign system as quickly as possible using these tools.
It’s important to know what modules do what beyond what their documentation may say. For this reason, I like to include logging messages that mark the beginning and end of the modules. In this way, you can play with the pages of the Web site, keeping an eye on the spare X terminal window running the tail -f /var/log/messages command. In this way, you see which modules execute and in what order every time the browser requests a new page.
I also like to log the boundaries between different programs being called into action during the running of the PHP code. Examples include when the MySQL calls are made to query the databases or when external programs are called to make formatting changes to data (Extensible Stylesheet Language Transformation (XSLT) engines, for example). The very practice of systematically inserting these checkpoints into each PHP code module helps you get used to the names and locations of the modules. When the code sends you messages you see in the spare X terminal while browsing various pages, you get important feedback that facilitates and enhances your knowledge of the system.
|
The syslog facility is a powerful tool for debugging an application someone else wrote. It allows you to watch which modules are being executed, which SQL statements are executing, and which variable values change as you navigate the Web site. This helps pinpoint the modules in which you’re likely to find problems.
Learn
- Learn more about the
syslog()function. - Discover the history of syslog on Wikipedia.
- PHP.net is the central resource for PHP developers.
- Check out the “Recommended PHP reading list.”
- Browse all the PHP content on developerWorks.
- Expand your PHP skills by checking out IBM developerWorks’ PHP project resources.
- To listen to interesting interviews and discussions for software developers, check out developerWorks podcasts.
- Using a database with PHP? Check out the Zend Core for IBM, a seamless, out-of-the-box, easy-to-install PHP development and production environment that supports IBM DB2 V9.
- Stay current with developerWorks’ Technical events and webcasts.
- Check out upcoming conferences, trade shows, webcasts, and other Events around the world that are of interest to IBM open source developers.
- Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM’s products.
- Watch and learn about IBM and open source technologies and product functions with the no-cost developerWorks On demand demos.
Get products and technologies
- Innovate your next open source development project with IBM trial software, available for download or on DVD.
- Download IBM product evaluation versions, and get your hands on application development tools and middleware products from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®.
Discuss
- Participate in developerWorks blogs and get involved in the developerWorks community.
- Participate in the developerWorks PHP Forum: Developing PHP applications with IBM Information Management products (DB2, IDS).
Add comment November 2, 2007
PHP Web Site Generation using Ruby
by Eric Rollins
ntroduction
“Raising the level of abstraction means moving toward WHAT, not HOW – telling the system what we want to do, declaratively,instead of how to do it, procedurally. This trend is desirable because declarative means the system does the work, while procedural means the user does the work.” C.J. Date, What Not How, 2000.
In Chapter 10 Database Access of Code Generation in Action Jack Herrington and I presented a code generator written in Ruby that generated a SQL schema and Enterprise Java Beans database access tier based on an input XML schema description. For this article I have modified the Ruby code to generate PHP code, and extended it to generate production PHP/HTML web pages.
I will cover building a database access layer for PHP, but I will also focus on the numerous benefits of generating production web pages using a system that has complete knowledge of the database schema. To finish I will discuss the highly productive development style that is enabled by continuously extending the declarative grammar in your own generator, and then provide some conclusions.
The Ruby source code and other files are available here.
I will not be explaining the Ruby source code; a detailed explanation is presented in Chapter 10 of the book.
And code generation provides many other advantages I do not discuss, please see the book and the Code Generation Network website FAQ for more.
Test Case
Our test case is an application that manages book publishing. It consists of 5 tables:
Book
| bookID | title | ISBN | authorID | publisherID | status | numCopies |
| 100 | Object Oriented Perl | 1-884777-79-1 | 100 | 100 | 2 | 1 |
| 101 | Bitter Java | 1-930110-43-X | 101 | 100 | 2 | 1 |
Author
| authorID | name | penName |
| 100 | Conway | |
| 101 | Tate |
Publisher
| publisherID | name |
| 100 | Manning |
Store
| storeID | name |
| 100 | Borders |
StoreBook
| storeID | bookID | quantity |
| 100 | 100 | 45 |
| 100 | 101 | 399 |
Generator Architecture
Our generator will take four XML files as input and using a series of templates will build a series of SQL and PHP files. The diagram below shows this relationship:

The four input files are:
| schema.xml | Describes the database tables, columns, column datatypes, andforeign key relationships. |
| extensions.xml | Describes extended Value Objects, queries, and methods beyond those automatically generated from schema.xml. |
| pages.xml | Describes production list, add, update, and delete web pages which access tables described in schema.xml. |
| samples.xml | Describes sample data that is placed in a Tests.php web page to be automatically loaded via the generated PHP APIs. |
The output files are:
| tables.sql | SQL script that creates tables and foreign key relationships. |
| code/*SS.php | Database access layer (class) for table *; provides add, update, delete, get, getAll, and custom queries and methods. |
| code/*Value.php | Value Object class for table *; used to pass data between web pages and *SS layer. |
| tests/Tests.php | PHP web page used to load sample data described in samples.xml. |
| webtest/*Add.php, *Update.php, *Delete.php, ValueList.php | Test PHP web pages automatically generated for table *. |
| web/*.php | Production PHP web pages specified in pages.xml. |
Database Access Architecture
The PHP web pages do not access the database directly. Instead they pass Value Objects to the SS layer, which in turn calls the PHP PEAR DB database abstraction layer API. This is diagrammed below:

The web browser talks to the PHP page on the Apache web server. The web page creates (or requests) a Value Object. The Value Object is passed to the SS layer, where it is transformed into a SQL statement passed to the PEAR database abstraction layer API, and on to the database.
PHP Generator
Now that we have completed a high level overview, lets drill into the generator itself. We first start with the lowest level, the schema.
Schema
The fundamental input to the generator is the schema.xml file. A fragment is show below:
<table name="Book">
<column name="bookID" datatype="integer" not-null="true"
primary-key="true" />
<column name="title" datatype="varchar" length="80" not-null="true" />
<column name="ISBN" datatype="varchar" length="80" not-null="true"
unique="true" />
<column name="authorID" datatype="integer" not-null="true" />
<column name="publisherID" datatype="integer" not-null="true" />
<column name="status" datatype="integer" not-null="true" />
<column name="numCopies" datatype="integer" not-null="true" />
</table>
<foreign-key>
<fk-table>Book</fk-table>
<fk-column>authorID</fk-column>
<fk-references>Author</fk-references>
</foreign-key>
<foreign-key>
<fk-table>Book</fk-table>
<fk-column>publisherID</fk-column>
<fk-references>Publisher</fk-references>
</foreign-key>
The schema.xml file specifies the database tables, columns, column datatypes, etc. It also specifies the foreign key relationships between tables. It is initially used to generate the database SQL schema file. The corresponding generated fragment is:
create table Book (
bookID integer not null
,title varchar(80) not null
,ISBN varchar(80) not null unique
,authorID integer not null
,publisherID integer not null
,status integer not null
,numCopies integer not null
,constraint Book_pk primary key(bookID)
);
alter table Book
add constraint Book_authorID
foreign key (authorID)
references Author (authorID);
alter table Book
add constraint Book_publisherID
foreign key (publisherID)
references Publisher (publisherID);
In this example all table columns are listed directly in schema.xml.
Stereotypes
Unlike the generated SQL file, the schema.xml file does not need to directly list all the fields, datatypes, etc. of a table. In production systems many tables contain repetitive columns for purposes of audit trail, optimistic locking, etc. Instead of manually adding these fields to each table a stereotype may be used. This concept has been borrowed from UML, where it is represented in class diagrams as <<stereotype_name>>. Here we take advantage of our extensible XML grammar to attribute tables with desired stereotypes. An example would be to mark tables as <constant/> or <dynamic/>.
Dynamic tables would automatically have columns create_date, modification_date, and modification_count, used in optimistic locking, added. Database SQL trigger code to maintain these fields can be generated. Higher-level layers of generated code would automatically utilize these locking columns transparent to the developer.
Constant tables can produce generation-time or run-time warnings if they are modified. Later the <dynamic/> semantics could be extended to track column usage by adding created_by and modified_by columns, again automatically maintained by the higher layer code and again transparent to the developer.
The leverage provided by applying arbitrarily complex semantics to simple extensions to the grammar is a key advantage of this generation system. The equivalent in a UML-based generation system would be to apply a new custom stereotype <<dynamic>> to a class and extend the generator to implement the semantics.
Stereotypes leave the application developer free to concentrate on the important elements of the data design.
Basic SS Layer and Value Objects
The SS database access layer separates web pages from PEAR database access routines. The web pages communicate with the database by passing Value Objects. The SS layer is implemented as a separate PHP class wrapping each schema table. Default methods on the class accept or return Value Objects to add, update, delete, get, and getAll database rows. Independent of any customization a basic Value Object and SS layer is generated for each table in schema.xml.
The basic Value Object looks like this:
class BookValue {
// private member variables
var $_bookID;
var $_title;
var $_ISBN;
var $_authorID;
var $_publisherID;
var $_status;
var $_numCopies;
// empty constructor
function BookValue(){
...
}
// ResultSet constructor
function setFromRow($row){
...
}
// member variable getters and setters
function getBookID() { return $this->_bookID; }
function setBookID($bookID){ $this->_bookID = $bookID; }
...
}
When you add or edit a record you need to construct or fetch a Value Object, then alter its contents and send it to the SS layer to be stored in the database.
The standard SS layer API looks like this:
class BookSS {
function getBookValue($bookID)
// returns array of BookValue
function getAllBookValue($orderBy)
function add($value)
function update($value)
function delete($bookID)
}
Extending the API
From schema.xml we create the SS layer and basic set of Value Objects. Production web pages often require more complex queries and Value Objects. Our generation system allows the Value Object, which defines the fields available for display, to be varied independently from the “where” portion of the custom query. A custom query can be used to return an auto-generated default Value Object, and an auto-generated get or getAll can be applied to a custom Value Object. Having them defined separately allows a custom Value Object to be defined once and then reused with many different queries. This is useful for the large number of web pages where the displayed table columns are identical but the specific query is different.
The extensions.xml file is used to define new Value Objects and add custom queries and methods to the SS layer.
Here are some extensions added to the Book table:
<value-object name="BookWithNamesValue" base-table="Book">
<add-column table="Author" column-name="name" />
<add-column table="Author" column-name="penName" />
<add-column table="Publisher" column-name="name" />
</value-object>
This defines a new Value Object. It will contain all the columns of the base table plus the new columns added from the other tables. Generated SQL strings will automatically perform the joins necessary to pull in the other columns. get* and getAll* methods are generated for this new Value Object.
<sql-query-method name="getAllByTitle" value-object="BookWithNamesValue" >
<parameter name="title" />
<where>Book1.title = ?</where>
</sql-query-method>
This defines a new SQL query. It returns the previously defined new Value Object, and restricts its results using the specified SQL where-clause fragment.
<custom-method name="updateStatusByPublisher" table="Book" return-type="void">
This defines a custom method. The actual implementation is placed in a hand-written PHP file, and is invoked by the SS layer.
Pages
The generator automatically produces test add, update, delete, and list web pages for all defined Value Objects, queries, and methods. Production web pages are specified in pages.xml. Supported page types are also add, update, delete, and list.
Here is an example list page for the Book table:
<page name="BookList" type="list" label="Book List"
value-object="BookWithNamesValue" order="Book1.title">
<buttons>
<button label="Add Book" target="BookAdd"/>
<button label="List Books in Stores" target="StoreBookList"/>
</buttons>
<fields>
<field name="update" label="Update" link="BookUpdate" virtual="true"/>
<field name="delete" label="Delete" link="BookDelete" virtual="true"/>
<field name="title" label="Title" link="BookView"/>
<field name="ISBN" />
<field name="author_Name" label="Author Name"/>
<field name="publisher_Name" label="Publisher Name"/>
</fields>
</page>
Here is how the generated web page looks in the browser:

Note this page is using the BookWithNamesValue Value Object defined in extensions.xml. It automatically uses the SS method getAllBookWithNamesValue() (an extension is to use an alternate query method with the parameters read from the request).
The results are ordered by Book.title. The fields refer to the columns by name, or by table_Name in the case of columns added to the Value Object. Labels for all fields default to the column name but can be customized. Here customizations are specified directly; alternately they could be keys into a localization file indexed by user locale.
Hyperlinked buttons are supported both in the body of the table as well as separately. Different styles of hyperlinks (using icons, etc.) are one example of a feature easily added to the generator grammar based on page developer requests.
Here is the xml for an add page for the Book table:
<page name="BookAdd" type="add" label ="Add Book"
value-object="BookValue" success="BookList">
<fields>
<field name="title" label="Title"/>
<field name="ISBN" />
<field name="authorID" label="Author">
<select table="Author" text="name" />
</field>
<field name="publisherID" label="Publisher">
<select table="Publisher" text="name" />
</field>
<field name="status" label="Status"/>
<field name="numCopies" label="Number of Copies"/>
</fields>
</page>
Here is the generated page in the browser:

Note HTML select tags (drop-down-lists) can be specified in the XML simply by listing the desired table and field name. The relevant SQL queries are automatically invoked at run-time. Because the generator has basic schema information available, field validation can be performed automatically:

Currently the system performs required (not null) and integer validation automatically. Single-column unique validation can also easily be added. Maximum text field widths are currently set from the schema.
Note the similarity between the pages.xml specification for a page and a functional specification. Both specify which fields are on a page in what order, which tables fields are taken from, which buttons are on the page, which pages they link to, and what labels are on the fields and buttons. This has several advantages:
- This system has removed all the grunt work from the translation of functional specification into code. The developers can spend their time concentrating on business analysis and back-end business logic implementation instead of HTML, PHP, javascript, field validation, etc.
- The amount of clerical work in connecting the front-end to the back-end is reduced, so there is significantly less chance of an issue with improper field mappings.
- The simple declarative syntax of pages.xml aids communication with non-developer stakeholders on the project.
- Re-targeting the system to other platforms and technologies – WAP, JSP, Swing, etc. is simplified.
The pages.xml specifications are so short because all the layout, etc. decisions have been moved elsewhere in the system. CSS (Cascading Style Sheets) allow the colors, fonts, etc. of HTML elements to be specified in a separate file. But basics of page layout currently need to remain in the HTML file.
By moving the high-level specification of a page to pages.xml the generator controls the placement of page elements. A simple change to the generator template file can alter the button layout, for instance:

Here we have altered the generator with a new layout style. The generator enforces the latest layout style standards so the page developers can concentrate on business functions.
While templating systems alone can accomplish some of these goals, templating combined with generation can create a much more powerful system. Generators can both utilize templating systems in their implementation of generated pages and utilize a templating pattern in XML specification of pages.
Pages in pages.xml can be parameterized and treated as sub-components of other pages. In this way a single page description can be varied and utilized in many different pages. Of course hierarchically composed pages can be constructed from a mixture of generated and hand-written subpages.
Development Style
Currently the generator presented here (and available for download) is a “toy” system. A significant amount of functionality would need to be added to complete a production web site. From my experience performing this extension is a feasible and productive method of developing a working system.
The amount and types of extensions necessary depend on the kind of web site being developed. The production web pages may be nearly suitable as-is for a simple administrative user interface. Customer-facing list pages will need paging mechanisms, editable fields, icons, localization, etc. Headers and footers providing logos, navigation menus (also generatable from a declarative description!), etc. should also be added. Mechanisms for attaching hand-written fragments of PHP code to generated pages will also be needed. These fragments use HTTP get/post and session state variables in preparing query parameters, calling business logic, and controlling navigation flow.
The grammar used in each of the XML files, and especially pages.xml, forms a unique, very high level, declarative language describing your specific application. As new requirements arise during iterative analysis and implementation the grammar is extended (new XML elements and attributes are added). The XML grammar remains concise because it is not trying to be a general-purpose language. The development team will typically be split between business analyst / page author / business logic developers and generator tool developers. The generator tool developers will continuously add new features based on analyst / page author requests. The generator and its grammar co-evolve with your understanding of your application domain. A release of the generator is done when the entire system is ready to ship.
And a big tip for team productivity, for both the analysts and the generator developer: maintain up-to-date DTDs (Document Type Definitions) or XML Schemas for your XML grammar. When anyone has a question about their XML input ask “does it validate?” While none of the Ruby XML APIs currently validate, it is simple to create a 15-line Python script and add it as a build target to your system. DTDs schema.dtd, extensions.dtd, pages.dtd, and samples.dtd have been included with the code. DTDs and XML Schemas allow you to declaratively specify your XML grammar and automatically validate input files against it using the XML parser. Otherwise you have to check for grammatical errors yourself procedurally inside your generator. DTDs and XML Schemas also provide exact documentation of your current grammar for the other developers.
Conclusions
There are many different ways to implement a code generator that generates complete application tiers. I have presented the advantages of a generator that has complete schema information and uses a custom-defined and continuously extended declarative XML grammar. Some advantages I have presented are:
- At the schema level:
- The SQL table creation code and higher level PHP code come from the same source, so they are guaranteed to always be in sync.
- New stereotypes can be used to extend large numbers of tables through simple declarative changes. The generator automatically adds associated functionality to all relevant layers of the system.
- At the database access level:
- Reusable Value Objects and queries can be independently defined and assembled together.
- Value Object (and associated query) definitions automatically track simple schema changes like column addition.
- At the web page level:
- Field validation can automatically be done based on datatype information from the schema.
- Select (drop down) lists can be simply specified.
- New grammar specifying features like new hyperlink types can easily be added.
- Many aspects of page layout may be modified without touching the input XML files.
- New page types and ways of compositing pages together can continuously be added.
- Page definitions resemble high-level functional specifications, easing the work of developers and aiding communications with other stakeholders.
Finally, all of these and many other discussed advantages are possible because we have built our generator around a declarative grammar that focuses on WHAT, not HOW.
Special thanks to Jack Herrington for editorial suggestions.
Add comment November 2, 2007
tranzlation in php
Internationalization and localization of a web page is simply the act of setting it up to be able to handle displaying in multiple languages and adding those different languages in. There are many different ways in which to do this. One of the simplest is to just make sure that all your strings that you ever output are stored as variables or constants in an included file. That way, you can make multiple copies of that file,each with different language versions written into them. Just include the appropriate file for the language that you want to display.
This idea can be extended to images as well because any image with text on it would also need translated. Just define the imgsrc of each image in your included file as well.
Listings 9.7.1, 9.7.2, and 9.7.3 are examples of what these included files could look like, given in three different languages.
Listing 9.7.1 Localization File for English—Filename: en.php
<?php // Declare all text strings that we need, // in English. $GLOBALS['text'] = array ( 'welcome' => 'Welcome to our website!', 'thanks' => 'Thank you for your patronage.', 'sky' => 'The sky is falling!', 'game' => 'Would you like to play a game?', 'switch' => 'Switch the language to:', ); // Now, also define alternative imgs for our use $GLOBALS['imgsrc'] = array ( 'title' => 'graphics/title.en.png', 'footer' => 'graphics/foot.en.jpg' ); ?>
Listing 9.7.2 Localization File for French—Filename: fr.php
<?php
// Declare all text strings that we need,
// in French.
$GLOBALS['text'] = array (
'welcome' => 'Bienvenue à
notre site Web!',
'thanks' => 'Merci de soutenir nos affaires.',
'sky' => 'Le ciel tombe!',
'game' => 'Aimez-vous jouer un jeu?',
'switch' => 'Commutez la langue à:',
);
// Now, also define alternative imgs for our use
$GLOBALS['imgsrc'] = array (
'title' => 'graphics/title.fr.png',
'footer' => 'graphics/foot.fr.jpg'
);
?>
Listing 9.7.3 Localization File for German—Filename: de.php
<?php
// Declare all text strings that we need,
// in German.
$GLOBALS['text'] = array (
'welcome' => 'Willkommen zu unserer
Web site!',
'thanks' => 'Danke für Ihr Patronat.',
'sky' => 'Der Himmel fällt!',
'game' => 'Wurden Sie mögen ein
Spiel spielen?',
'switch' => 'Schalten Sie die Sprache zu:',
);
// Now, also define alternative imgs for our use
$GLOBALS['imgsrc'] = array (
'title' => 'graphics/title.de.png',
'footer' => 'graphics/foot.de.jpg'
);
?>
Now that we have all the different language versions saved in separate files, we want to make it easy for any page to use these. Therefore, a library should be created to handle this. The library shown in Listing 9.7.4 when included in a web page automatically detects what language should be used based on a GET string or a cookie. It also provides a function for easily creating some XHTML that allows for switching languages.
Listing 9.7.4 Localization Library—Filename: language.php
<?php
// This is a library, that by including it,
// automatically determines the proper language
// to use and includes the language file.
// First define an array of all possible
// languages:
$languages = array('en' => 'English',
'fr' => 'French', 'de' => 'German');
// Look at the GET string to see if lang is
// specified:
if (isset($_GET['lang'])) {
// It's been specified, so set the language
$lang = $_GET['lang'];
// While here, send a cookie to remember this
// selection for 1 year.
setcookie('lang', $lang, time()+(3600*24*365));
}
// Ok, otherwise look for the cookie itself:
elseif (isset($_COOKIE['lang'])) {
// Use this
$lang = $_COOKIE['lang'];
} else {
// Otherwise, default to English
$lang = 'en';
}
// Make sure that the language string we have is
// a valid one:
if (!(in_array($lang, array_keys($languages)))) {
die("ERROR: Bad Language String Provided!");
}
// Now include the appropriate language file:
require_once "{$lang}.php"
// As one last step, create a function
// that can be used to output language
// options to the user:
function switch_language_options() {
// Include a few globals that we will need:
global $text, $languages, $lang;
// Start our string with a language specific
// 'switch' statement:
$retval = $text['switch'];
// Loop through all possible languages to
// create our options.
$get = $_GET;
foreach ($languages as $abbrv => $name) {
// Create the link, ignoring the current one.
if ($abbrv !== $lang) {
// Recreate the GET string with
// this language.
$get['lang'] = $abbrv;
$url = $_SERVER['PHP_SELF'] . '?' .
http_build_query($get);
$retval .= " <a href=\"{$url}\">
{$name}</a>";
}
}
// Now return this string.
return $retval;
}
?>
With this completed, it can be easy to generate a web page that is language independent, such as Listing 9.7.5.
Listing 9.7.5 Localization: Complete Example
<?php // Include our language library: require_once 'language.php'; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><?= $text['welcome'] ?></title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> </head> <body> <p><img alt="<?= $text['welcome'] ?>" src="<?= $imgsrc['title'] ?>" height="50" width="500" /></p> <h2><?= $text['thanks'] ?></h2> <p><?= $text['game'] ?></p> <p><img alt="<?= $text['sky'] ?>" src="<?= $imgsrc['footer'] ?>" height="10" width="220" /></p> <p><?= switch_language_options(); ?></p> </body> </html>
Note: PHP also provides an interface to the GNU gettextgettexthttp://php.net/gettext. library. This is a generic library created to handle internationalization/localization problems. Using it requires building the support for it into PHP and installing the library on your computer. If you want to learn more about this, visit
October 24, 2007
google tricks
Introduction
Search engines are good. Google has been the indisputable king of search engines for quite some time now, and even if msn is trying it’s best to pursue the surfers with a new engine, a massive advertising budget and a new “css” based layout, google is still on top. Yahoo and Ask Jeeves has always been alternatives, and still are, while the 90’s big shots AltaVista and webcrawler has taken a big step down.
This article will demonstrate how you can build your own search engine using Google’s API service and some PHP magic. Google has released the source code for it’s results, and they are free for anyone to use with the only drawback being a limit of 1000 queries per day and displays a maximum of 10 results at a time.
And while we’re at it, we might as well do it right this time, using semantic XHTML markup and accessible forms. This will also make it possible for you to add your own search engine to your site with googles powerful back-end serving up the results.
The retro-cool google
Google is loved by many and hated by few. It’s light, fast, (almost) ad-free and secure. But a quick look under the hood makes any web developer wonder why the biggest of them all are still using markup that belong to the 90’s. Inaccessible forms, tables for layout, markup errors, incorrect ampersands in the url, old-school <b> tags etc. etc. Now, in order to change all this you could write them an email explaining your concern about their coding. Or you could create your own search engine, built on the same reliable back-end but re-coded with modern front-end technologies. We will do the later in this article.
Google API
As mentioned before, google released their search results to the public some time ago. All you have to do is sign up a google account at https://www.google.com/accounts/NewAccount if you don’t already have one. Once there, you can request for an API key. If you have problems obtaining one, see their help pages for more info. This key is exactly what is sounds like – a key to access their massive database of basically all web pages available on the world wide wisdom. We will use this key in the example, so make sure you have one before you continue.
PHP and NuSOAP
We will use PHP to create the program. PHP is an open-source server side scripting language and is very similar to perl and c++. Ask your host if they support it (all good hosts do) or try to install it on your local machine. Not only will we use PHP, but also an extension called NuSOAP. It contains many useful classes, especially for tasks like accessing the google results and parsing them. You can download the package at http://sourceforge.net/projects/nusoap/. Once downloaded, unzip the .zip archive and locate the folder named “lib”. In there you will find several PHP files with the extension “.php”. These are the files we will use to access the NuSOAP library.
Getting Started
To get started with the tutorial, make sure you go through these steps:
- Get an API key at https://www.google.com/accounts/NewAccount
- Create a new directory in the root called “search”
- Download the NuSOAP library at http://sourceforge.net/projects/nusoap/
- Unzip the NuSOAP .zip archive, locate the lib folder and copy all files in the folder into the search folder you just created
- Read the next section
Google did wrong – let’s make it right
Semantic markup and web standards are the way of the future. It’s like any tool or technological advance – first comes availability and then perfection. Google’s markup is quite far from perfection, but we know better. After a quick analyze of the search results page I decided that a definition list would probably be the best way to code the results, since it has all the typical fields: a title and descriptions. So this is basically what we want:
<form>
<p>[search_form]</p>
</form>
<p class="results">[results_info]</p>
<dl>
<dt><a href="[url]">[title]</a></dt>
<dd>[description]</dd>
<dd class="url">[url] - [size]</dd>
[ ... repeated ... ]
</dl>
<p class="nav">[page_nav]</p>
Getting the PHP stuff working
Now is the time to download the index.php sample file. This is the file that contains all vital php instructions to create the search engine. Once downloaded, upload it to the search folder on your root directory or open it up in your favourite text editor. Once there, lets take a look at the general sections of the PHP file:
- Preferences
- Main program
- Sub programs
- XHTML rendering
1. Preferences
Theese are the preferences. Modify as you wish, but never change the google API key once you obtained it.
$pref->text– defines what text should be displayed if google doesn’t find any text.$pref->title– defines what title should be displayed if google doesn’t find any title.$pref->key– this is where you should enter your Google API key – read previous section for more info on how to obtain one.$pref->results– sets the number of results to be displayed on one page. Google API has a limit of max 10 results.$pref->start– sets the starting item to be displayed. If set to “Auto”, a page navigation will appear in the bottom.$pref->safe– toggles the SafeSearch filter on or off. “false” means off and “true” means on.$pref->filter– toggles the google filter for similar pages on the same domain on or off. “false” means off and “true” means on.
2. Main program
The main program contain 4 commands:
require_once('nusoap.php');$query = $_GET['q'];$results = getResults($query);$title = getTitle($query);
The first line includes the NuSOAP lib into the document. The second line collects the query string. The third collects the search results in a variable called $results and the fourth line collects the document title into $title.
3. Sub programs
I am not going into detail of all aspects of these functions, but here is a quick review. The getTitle(); is very simple and collects the title depending on what and if the search query has been done. The getResults(); parses the $query string and collects the google results using the NuSOAP functions, then returns the data. The markup is parsed with some regular expressions using the preg_replace(); function in order to remove unwanted tags, correct ampersands and convert <b> tags to XHTML. The function also contains an advanced page and results calculator if you have set the $pref->start to “auto”.
4. XHTML rendering
The last section looks familiar for any web programmer. A few things should be noted here:
- The default style is my childish attempt to assimilate google’s well known layout interface. You can change this to whatever you like.
- Please note the
<title><?php echo $title; ?></title>line. That means that the PHP will take care of the title. - The form also contains some PHP commands, leave them where they are or experiment as you wish.
- The most important line is
<?php echo $results; ?>. This is where the data comes in from the PHP program.
Wrapping it all up
Once you have configured the preferences, just save your file and point your browser to http://www.yoursite.com/search/index.php and start googling. Or, you can have a look at our example demo. You can alter and refine the PHP code depending on what level you master, or you can stick to modifying the XHTML rendering in the fourth section of the document. In any way, you will have a fully standard compilant, valid and highly customizable google search engine at your disposal, ready to use at your site or wherever you like. Remember that the google API only allows 1000 queries per day, so if the search results are empty, you might need to cool off and take a walk.
Add comment October 24, 2007
Creating a PHP-Based Content Management System
part one
i will ad the part tow in few days
If you’re going to run an intranet site, then you’ll probably want a content management system (CMS) — a tool used to organize documents and keep track of what’s where. I’ve covered a plethora of such systems in previous articles, but for many businesses there can be only one solution: to design and implement their own custom system.
Why? It’s not like the off-the-shelf systems lack features or stability. On the contrary, many have been crafted by hundreds of man-hours of work, and are successfully implemented by thousands of Web sites and intranets. But when it comes down to it, it’s hard to have much clue as to how they work. If you want to customize the way these systems operate, you’ll often have to wade through vast amounts of (often badly documented) code to find what needs changing.
Writing your own CMS, on the other hand, can lead to a solution that is better suited to your requirements, better addresses the needs of your users, and is better understood by your development team. If you have the time and expertise to write your own in-house system, it may well prove the better option. And this is what I shall be embarking upon in this series.
The system we create will be written using the PHP programming language, which excels in the development of Web-based systems. I’ll be using MySQL as the database server, but the system will be written to allow the use of alternative databases, such as PostgreSQL or SQL Server.
So what will this system actually do? First and foremost, it will allow the bulk of the intranet or Internet site’s content to be easily stored and managed in a database. We’ll also include a number of other features required for running a successful site, such as authenticating users and managing files.
Some basic PHP knowledge will be needed for coding your own CMS, although most of what you’ll need to know will be demonstrated here. I’ll assume you have access to a server running PHP and a database system. Once the series is complete, I’ll make available a polished version of the CMS for anyone to use.
I don’t promise the vast array of abilities incorporated into systems such as Postnuke, Smarty, or some commercial content management systems. But just having lots of features isn’t always what’s needed, and this series will help you to develop a system specifically targeted to your needs. With that, let’s get going…
Planning the CMS
To begin with, we’ll plan how our PHP-based content management system will work. In subsequent articles, I’ll demonstrate how each of the major components are implemented, leading to a complete system.
The first step is a basic specification of what our CMS must do. Obviously, this will depend on your needs:
- Content Management: Probably the most vital function of the system, it must store content such as documents and news in a database, and display to the user whatever he or she requests. An easy-to-use interface is required to allow editors to add, remove, or modify content.
- User authentication: There may be certain areas of the intranet or Internet site to which we wish to limit access. At the very least this will be the “admin” area, where the editor of the site will be able to add, edit or modify content. You may also wish to have areas only available to certain departments or staff.
- Page uniformity/templates: The system should have a uniform look and feel, and this design element needs to be separated from the logic element, e.g., the programming required to display an article should be separated from how that article looks (stylistically) on the screen.
Object-Oriented Programming
PHP helps the design process by supporting object-oriented programming (OOP). When putting together our system, there are certain chunks of programming that are needed again and again, such as database access, user authentication, etc. To keep this code neat and tidy, we bundle it together in PHP files called “classes.” We can then create instances (or “objects”) of these classes whenever they are needed. Thus, the class can be thought of as a blueprint for one or more instances.
For example, we could create a class with code for connecting to a database, and then create an instance of that class whenever we need to query the database. If this isn’t immediately clear then don’t worry, it will become more obvious when we start coding. This method of programming allows a complex system to be broken down into smaller and simpler blocks, which makes life easier when it comes to management, modification, and error finding.
Let’s now consider how the system will fit together. This will doubtless be tweaked as you consider the requirements for your own system, but below is a basic outline:

We have four main PHP modules (or “classes”) that will be widely used in the system. These are tasked with accessing the database, allowing the user to upload files to the site, reading and writing templates, and logging users in and out. These classes all “extend” one parent class called “systemObject.”
Think of these four as being independent of one another, yet all inheriting whatever data we put in systemObject. This technique of hierarchy allows us to make changes effecting all four system classes, just by adding or modifying the code in the systemObject parent class. Again, this concept will become clearer when we start coding. In the middle of the diagram are the basic areas of the administration system, and each will need one or more PHP pages to perform the required tasks.
This article requires a basic knowledge of PHP programming, although a number of concepts are explained for those less experienced.
Our CMS will be stored in a number of folders, structured as follows:
|
|
You may wish to create these four folders now. We’re going to start by creating the PHP class which all others will “extend.” This will be the root of the administration system, and anything we put in it (such as variables and functions) will trickle down to the other classes.
This root class will be called ‘SystemComponent’. The code follows, and a full explanation is below:
<?php
class SystemComponent {
var $settings;
function getSettings() {
// System variables
$settings['siteDir'] = ‘/path/to/your/intranet/’;// Database variables
$settings['dbhost'] = ‘hostname’;
$settings['dbusername'] = ‘dbuser’;
$settings['dbpassword'] = ‘dbpass’;
$settings['dbname'] = ‘mydb’;return $settings;
}
}
?> Reminder: A class is a block of code. Whenever we need to run that code, we create an ‘object’ or ‘instance’ of the class. We can create as many instances of a class as we like. If you don’t understand objects and classes by the end of this article, I recommend getting a book or finding a Web site on Object Oriented Programming.
The above code starts off by telling PHP that our class will be called ‘SystemComponent’. Between the braces (squiggly brackets) we declare the variable $settings, and a function called ‘getSettings’. The purpose of this is to store a number of values in $settings, containing the path on the server to the intranet (’siteDir’), and the details of the database. Change these appropriately for the database system you’ll be using (this tutorial uses MySQL, more details coming up). Finally, the ‘return’ command sends $settings to whichever class or function has requested it. We’ll be storing more data in $settings as the series progresses.
Save this code to a file called SystemComponent.php in the ‘includes’ folder you created. Now let’s do something with this class.
All of the information to be displayed in our Content Management System will be stored in a database. It is sensible, therefore, to create a reusable PHP class that we can call upon whenever we need to access our data. The code listed here is for connecting to a MySQL database. If you’ll be using a different system, such as PostgreSQL, MS SQL or SQLite, then change the code appropriately. It’s obviously quite a bit longer than our previous class, but it performs a number of very important tasks. The code follows:
<?php
////////////////////////////////////////////////////////////////////////////////////////
// Class: DbConnector
// Purpose: Connect to a database, MySQL version
///////////////////////////////////////////////////////////////////////////////////////
require_once ‘SystemComponent.php’;
class DbConnector extends SystemComponent {
var $theQuery;
var $link;//*** Function: DbConnector, Purpose: Connect to the database ***
function DbConnector(){// Load settings from parent class
$settings = SystemComponent::getSettings();
// Get the main settings from the array we just loaded
$host = $settings['dbhost'];
$db = $settings['dbname'];
$user = $settings['dbusername'];
$pass = $settings['dbpassword'];// Connect to the database
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, ‘close’));}
//*** Function: query, Purpose: Execute a database query ***
function query($query) {$this->theQuery = $query;
return mysql_query($query, $this->link);}
//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {return mysql_fetch_array($result);
}
//*** Function: close, Purpose: Close the connection ***
function close() {mysql_close($this->link);
}
}
?>
Some explanation is required. After we’ve named the class ‘DbConnector’, we state ‘extends SystemComponent’. This tells PHP to grab all of the data and functions from SystemComponent, and provide us with access to them (we’ll need this in order to get the $settings variable we created earlier).
The first function, ‘DbConnector’, has the same name as the class that contains it, meaning it’s run automatically when DbConnector loads. It firstly calls the ‘getSettings’ function we wrote earlier, and extracts from it the various database settings. It then uses these settings to connect to the database. (Note that we have no code to deal with errors, this will be covered in detail next time.)
The other functions are explained below:
| Function | Purpose |
Save the above code (also attached at the bottom of this article) to the ‘includes’ folder, with the name DbConnector.php. This class will be widely used in the Intranet system, so let me give you an example of how we’d create an instance of DbConnector, extract some data, and display it to the user. Let’s imagine that our database stores the details of one customer, and we want to get hold of his / her name and display it. Here’s the code:
<?php
// Get the PHP file containing the DbConnector class
require_once(‘DbConnector.php’);
// Create an instance of DbConnector
$connector = new DbConnector();
// Use the query function of DbConnector to run a database query
// (The arrow -> is used to access a function of an object)
$result = $connector->query(‘SELECT firstname FROM customers’);
// Get the result
$row = $connector->fetchArray($result);
// Show it to the user
echo $row['firstname'];
?>
If you’d like to try out the DbConnector class now, you’ll need to save the above code in the includes folder in a php file, and set up a ‘customers’ table in your database. I’ll be covering the set up of our Intranet’s database next time.
The importance and power of using a database is clear – we can store information in a formal way, and rapidly access, manipulate and change it. The information we extract or store is specified using the ‘query’ function of the DbConnector class, and we create instances of DbConnector using the ‘new’ command, as shown above. This also demonstrates the usefulness of classes – if the settings are changed in SystemComponent, then all of the classes that extend it will automatically be changed.
Creating the Database
The first table we’re going to add to our database will store articles, for display on the Intranet. The ability to share information is the most important function of an Intranet, and the job of the Content Management System is to make doing this as easy as possible. Consider your own data requirements, a few important ones spring to mind for most articles tables:
| Field | Purpose | Type |
| ID | A unique number given to each article, and the primary key of the table. | Integer |
| Title | The title of the article | Varchar(300) |
| Tagline | A very short summary of the article | Varchar(600) |
| Section | The category to which the article belongs | Integer |
| TheArticle | The article itself | Text |
Before we can create the system itself, we need to create the database to store our information. The code below will set this up if you’re using the MySQL database system – uses of other systems should modify the commands appropriately. Copy and paste the following into the MySQL admin tool, or use one of the many free ‘client’ programs available:
CREATE TABLE `databasename`.`cmsarticles` (
`ID` int(6) unsigned NOT NULL auto_increment COMMENT ‘The unique ID of the article’,
`title` varchar(200) NULL COMMENT ‘The article title’,
`tagline` varchar(255) NULL COMMENT ‘Short summary of the article’,
`section` int(4) NULL DEFAULT 0 COMMENT ‘The section of the article’,
`thearticle` text NULL COMMENT ‘The article itself’,
PRIMARY KEY (`ID`)
);
If all has gone to plan, you should now have a working table in the database. We’re now going to create a page to allow you or your staff to enter articles into the system.
Creating the editor
Firstly, design a form using the HTML editor of your choice. Create text fields for each database field (excluding ID). An example is below:
Add comment October 12, 2007
Custom Content Management with PHP
Custom Content Management with PHP
by Thomas Perl
It is well known that you can create powerful Web pages with PHP. Often, the question arises: How are these pages made? This tutorial wants to give you some hints on how to make your Web site appear more managed from both inside and outside. These are my own approaches to Web development; I hope you find them useful. Take these things as ideas rather than good practice.
Copyright notice: All reader-contributed material on freshmeat.net is the property and responsibility of its author; for reprint rights, please contact the author directly.
About the hints
Each hint in this tutorial can be implemented by itself without the others, but sometimes, it’s more useful if you combine them. It depends on you to decide which hint is good for your site.
Clean directory structure
Are you tired of calling a subpage of your site http://www.example.com/index.php?page=news&id=45? You could have a stylish URI in the form of http://www.example.com/news/45/. This gives better-sounding addresses, and your visitors may more easily remember your URIs. All you need is the Apache Web server or a browser in which this .htaccess file will be processed in the same way:
RewriteEngine on RewriteBase /news/ RewriteRule ^.*$ handler.php
These three lines instruct Apache to rewrite all URIs from the base directory /news/ matching the rule ^.*$ to the handler.php script.
Place this file in your newly-created /news/ directory, then create a handler.php file, which will handle all the requests beneath the /news/ tree. In other words, all URLs you request within that directory will be handled by handler.php. To get an array of “parameters” that are passed to handler.php, you can use this function:
function get_url_params( $base_url)
{
$request = substr( $_SERVER['REQUEST_URI'], strlen( $base_url));
if( substr( $request, -1) == '/')
$request = substr( $request, 0, -1);
return explode( '/', $request);
}
Use it in handler.php like the following:
get_url_params( '/news/');
You will receive an array with the parameters, which you can process as you wish. You could improve the get_url_params() function by adding code for processing a ? (and everything behind it) in the request URI.
I use this technique to get some fancy URI mapping of my Web site. It’s not any harder than using a single index.php which handles all requests, and the benefits are clearly visible. You will be able to make URLs on your Web page that don’t have to change, which is exactly what Cool URIs don’t change tells you is good practice. (This document got me into making this URI mapping system for my Web site; it’s really worth reading.)
Creating a template framework
You can use templates for outputting both static and dynamic content. You will want to create a directory in which you put the templates. You should secure this directory using this .htaccess file:
allow from none deny from all
This will instruct Apache to deny all access to the template files directly. Access using template functions is still granted, because they’re not directly accessed.
You will now want to write a template function. Here’s what I currently use for my site:
function template_create( $template_name, $mapping = NULL)
{
$template_data = file_get_contents( $_SERVER['DOCUMENT_ROOT'] .
'/templates/' . $template_name . '.template');
if( NULL != $mapping)
return str_replace( $mapping['from'], $mapping['to'], $template_data);
else
return $template_data;
}
This means I have my templates in the /templates/ directory of my document root and that the files have the extension *.template (which isn’t necessary; you could name the extension of your templates as you like). If you include the $mapping parameter, this should be an array with two elements: $mapping['from'] and $mapping['to']. All occurrences of the “from” element will be replaced with the “to” element. Both elements can also be arrays, which results in all elements in the “from” array being replaced with the corresponding elements in the “to” array. Here is an example of how you could use this:
$time = time(); $text = 'This is a Test'; $mymap = array( 'from' => array( '%%TIME%%', '%%TEXT%%'), 'to' => array( $time, $text) ); template_create( 'my_document', $mymap);
Where the file /templates/my_document.template could look like this:
<p>Hello. The time is %%TIME%% and here is some text:</p> <p>%%TEXT%%</p>
You should now have seen how easy it is to create templates for pages and how to fill them with dynamic content. This is especially useful if you want to create templates for displaying dynamic data from databases and such. You can surely improve this by creating a function which reads one row from a database table and fills a mapping variable with data from that row, returning a valid mapping for the template_create() function.
Using templates for a unique layout
This is a short and easy one. Let’s say you want to create a unique layout for a page, but you don’t want to include the full code in every file or script you write. Use the templates hint above to create template functionality and include it in every subpage. Then, use it like the following (assuming header.template and footer.template include all the code for the beginning and the ending of the page):
template_create( 'header'); // place content output here template_create( 'footer');
Yes, that’s all!
Make database access abstract
Here’s some more code for your include directory. After some time, it’s easier to make queries in this fashion than to make a mysql_query everywhere you need some data from the database. It also gives more sense to the code and makes it more readable because you just see the function call with the important parameters.
function database_get_single_element( $table_name, $key, $value); function database_select_multiple_elements( $table_name, $from, $to, $order = NULL, $how = 'ASC', $key = NULL, $value = NULL); function database_get_random_element( $table_name, $key = NULL, $value = NULL); function database_get_column_sum( $table_name, $column, $key = NULL, $value = NULL); function database_get_next_element( $query); function database_count_elements( $table_name, $key = NULL, $value = NULL);
The database_get_single_element() function will select and mysql_fetch_assoc one row of the table named by $table_name. There will also be a WHERE part, and the $key field in the table must have the $value value.
The database_select_multiple_elements() will return a mysql_query of the same things. $from and $to are for the LIMIT part of the query. The data can then be fetched with database_get_next_element(), which is exactly the same as mysql_fetch_assoc, but has a more informative name.
database_get_random_element() will use the ORDER BY RAND() LIMIT 1 SQL query words to select some random element from the table.
Finally, database_count_elements() counts the number of rows of the results. This is good for counting how many elements another query will return.
These are just some hints of what I mean by database abstraction. I’m sure that you’ll probably need other functions which better suit your needs, and you might not need all the functions I’ve shown. Let me tell you from experience that it will get a lot easier when you start using these functions instead of simple queries. And if you have some very complicated queries, make a function for each of them. If your database layout changes or if you use another database instead of MySQL (which is certainly possible in PHP), you do not have to change all queries, but simply fire up your editor on the database include files and change all queries there.
Add comment October 12, 2007