The whole of Science is nothing more than a refinement of everyday thinkingAlbert Einstein
Also relates to PEAR
With the latest release of the PEAR::Cache the Cache_DB extension has been removed. I first came across Cache_DB in the PHP Cookbook last year and ran several tests to integrate it as a principle caching mechanism in the Content Management System. However, the class offered no noticeable benefit in performance, and when several database calls were being executed for a single page, it did not make sense to use a cache per query. So as an alternative I decided to test drive the PEAR::Cache_Lite package instead. As its nomenclature suggests, this is an excellent lightweight package and offers the perfect solution for filling the caching void in content retrieval. One of the package extensions is <a href="http://pear.php.net/manual/en/package.default.cache-lite.cache-lite-function.cache-lite-function.php" title="Current End User Documentation on Cache_Lite_Function">Cache_Lite_Function</a>, a caching class for functions. This allows for several database calls and the template system to be wrapped in a single method for caching:
class SS_Content {
// [..snip..]
function fetch($action, $caching = NULL)
{
$this->action = $action;
if ($caching === NULL) {
if (isset($this->_caching)) {
$caching = $this->_caching;
}
}
if ($caching === SS_CACHING_ON) {
return $this->retrieveCache();
}
else {
return $this->retrieve();
}
}
function retrieveCache() {
require_once "Cache/Lite/Function.php";
$options = array(
'cacheDir' => CACHE_DIR,
'lifeTime' => CACHE_EXP
);
$objCache = new Cache_Lite_Function($options);
return $objCache->call(
$GLOBALS['_SS_Content_Obj'] . '->retrieve');
}
function retrieve() {
// this is where the content is built
// eg database retrieval and content
// creation with a template system
}
// [..snip..]
}
This is only a raw example, since within its actual context, SS_Content is actually
an abstract class serving specific modular extensions. But it shows how simple Cache_Lite is to use -
create the object and invocate the <a href="http://pear.php.net/manual/en/package.default.cache-lite.cache-lite-function.call.php" title="End user documentation on the call method of Cache_Lite_Function">Cache_Lite_Function::call()</a> method. There is one area of caution when
using Cache_Lite in an OOP environment like
this. The method will look for an object in the global name space equating to the name preceding the
accessor operator in the parameter string of the method. How this is achieved is dependant on
the application and naming conventions. One solution is to register the variable name of the object in a global variable during
instantiation of the class (as demonstrated above).
Melon Fire provides a terse but detailed introduction to Cache_Lite, Cache_Lite_Function and its counterpart Cache_Lite_Output.
Posted on Jun 20, 2004 at 03:40:35. [Comments for Viva PEAR::Cache_Lite- 0]
Also relates to Databases
I cannot get enough of the new features in PHP 5, and the SQLite extension is no exception. Besides the speed and simplicity, one of the most interesting features is the ability to define custom functions for direct use in the SQL statement.
In a content based public domain application, dynamic creation generally involves three steps:
The sqlite_create_function() effectively removes the need for step 2 altogether - instead define and associate formatting functions with
the sqlite_db object and use them in the SQL statement.
For example, regularly I will use an image_manager table to store references to image files across a broad range of content. With MySQL, the CONCAT() function
allows concatenation of the image file name (stored data) and the directory path (parameter) within the resultset. But the resultset must still pass through a formatter function to confirm the existence of the image, and get additional information for the file (eg the height and width).
In contrast, with SQLite, the formatter function is defined and attached directly to the sqlite_db object.
function get_image_file($data) {
$file = IMG_DIR . $data . ".jpg";
if (is_file($file)) {
$stats = getimagesize($file);
$str = "<img src=\"/g/$data.jpg\" "
. "width=\"$stats[0]\" "
. "height=\"$stats[1]\" />";
}
else {
$str = "NO FILE";
}
return $str;
}
$db = new sqlite_db("db.content");
$db->create_function("get_image_file",
"get_image_file", 1);
Now the SQL statement can include the user-defined function to retrieve the image files directly into the resultset.:
$res = $db->array_query(
"SELECT image_desc, "
. "get_image_file(image_file) as image "
. "FROM image_manager "
. "WHERE image_ref = $param", SQLITE_ASSOC);
The resultset $res is now ready to send direct to the appropriate markup for display. This powerful utility has a range of uses from advanced content parsing, for example with PEAR::HTML_BBCodeParser, to just replicating some of the advanced SQL functions of other RDBMS with added user flexibility.
The ability to use PHP from within SQL allows you to simplify the actual script making it accessible to larger audience of developers. This allows PHP to be used as a templating engine that simply populates HTML structures with database data. In many instances this can simplify the code so much that there is no need to place a templating system on top of PHP. Beyond the code simplification, this also improves performance and reduces the script's memory footprint, since no data manipulations need to occur in user-space. SQLite Introduction, By Ilia Alshanetsky
Here are some useful links to more SQLite related pages.
Posted on Mar 29, 2004 at 00:09:38. [Comments for SQLite Custom Functions In PHP 5- 0]
Also relates to PEAR and Databases
The PEAR::DB_DataObject package is rapidly becoming an integral part of my development arsenal. Building small scale content management becomes surprisingly simple, producing code in the CMS API layer that is concise and clear. Here is a little walk through comparing this package with its uncle - PEAR::DB - for batch deletions.
Take a simple shopping cart that includes customer and order entities as part of a wider database. These
are inevitably linked in a one-to-many relationship on the customer_id field. As part of a spring clean, we
want to remove all customer records that do not have an associated order record (i.e. all customers that have
not placed any orders), while enforcing referential integrity. A typical DML method to achieve
this is a LEFT JOIN as follows:
SELECT
customers.customer_id
FROM
customers LEFT JOIN orders
ON
customers.customer_id = orders.customer_id
WHERE
orders.customer_id = NULL
The following snippet uses PEAR:DB to perform the batch deletion, based on the result of the above SQL:
$db =& DB::connect(ss_dsn());
$query = "SELECT customers.customer_id "
. "FROM customers LEFT JOIN orders "
. "ON customers.customer_id = orders.customer_id "
. "WHERE orders.customer_id IS NULL";
$result = $db->getAll($query);
$prh = $db->prepare('DELETE FROM customers WHERE customer_id = !');
$sth = $db->executeMultiple($prh, $result);
Here, the getAll() method is used to return the set of results as an array of arrays, so
they can be plugged directly into the executeMultiple() method with a prepared statement.
The same result could be achieved by walking through the result set deleting each record in turn. For example:
$result = $db->query($query);
while ($result->fetchInto($record, DB_FETCHMODE_OBJECT)) {
$db->execute($prh, array($record->customer_id));
}
Ok, now let us walk through the process using DB_DataObject. The approach is quite different. One of DataObject's main features is to make the DML virtually transparent, and rather than working with field values stored in arrays, we are working directly with the entities mapped onto objects.
find() methodHere is the snippet:
$customer =& DB_DataObject::factory('customers');
$customer->whereAdd('user_id > 0');
$customer->find();
while ($customer->fetch()) {
if(!$customer->getLink('customer_id', 'orders', 'customer_id')) {
$customer->delete();
}
}
Removing the SQL from this layer makes the code considerably less error prone, especially
if the relationship is threefold or greater. This approach can be readily adapted to the case of a single deletion.
To ensure referential integrity will not be violated when removing a record, SQL statements must be executed against
all entity classes holding a relationship with the current record. With DataObjects the database queries are executed internally, and all
the current layer needs to do is test for link objects. Multiple relationships can actually be stored in a links.ini
configuration file, and the integrity test achieved by simply calling the getLinks() method.
The release of PHP 5 Release Candidate 1 sees a dramatic step forward for PHP into Object Orientated design and development. PEAR::DB_DataObjects complements this nicely.
Posted on Mar 27, 2004 at 04:51:18. [Comments for Enforce Referential Integrity With DataObjects- 0]
Also relates to Apache and DOM Scripting
Here is a cute little bookmarklet to tie in with the source file for viewing underlying PHP as outlined in the PHP Manual.
The source file should be placed in the server root directory for the main server or a virtual host, and the Location
directive set accordingly in the Apache configuration file (See the PHP Manual). This code snippet simply performs a regular expression replace to
change the location.href to point to the source file.
javascript:var re=/\/\/([-a-z\.]+)\//i; _
window.location.href= _
window.location.href.replace(re,"//$1/source/");
This code can be pasted into a new bookmark ( _ just represents line continuation), or drag this PHP Source link
onto your bookmarks. I find this quite useful when walking through a site on my test platform, and it complements the many client side developer utilities in the Firefox Web Developer toolbar and these comprehensive
Web Development Bookmarklets.
Posted on Mar 27, 2004 at 04:49:49. [Comments for View PHP Source- 1]
Also relates to Apache and DOS
For all its anachronistic tendencies, my Windows 98 test platform is surprisingly robust when a new challenge arises. I have been itching to try out the PHP 5 Release Candidate 1, and have had the binary on my desktop for the past few days waiting to be unzipped. My sole apprehension was an install that did not interfere with the current PHP 4 configuration and all the in-progress work that relied on it. Acquiring a few tips from the articles already available on concurrently running PHP 4 and 5, the solution was actually quite simple and very quick to initiate.
Since I only boot Apache server on demand, all that was needed was a separate
httpd configuration file to load the PHP 5 Apache module, with updated
<a href="http://httpd.apache.org/docs/windows.html#cmdline" title="Online Apache Documentation for LoadModule Directive">LoadModule</a> and <a href="http://httpd.apache.org/docs/mod/core.html#addmodule" title="Apache Documentation for AddModule Directive">AddModule</a> directives:
LoadModule php5_module c:/php5/php5apache.dll
AddModule mod_php5.c
Then it was just a case of handling the php.ini file. When PHP is run as a module in Apache, the ini file must be
either located in the Apache root folder or the System root folder. I did not
want to interfere with the current ini file for the PHP 4 configuration (already
located in the System root folder), and wanted to avoid performing a rename/copy/paste action every time Apache
was booted with PHP 5.
So I placed the PHP 5 ini file in the Apache
root folder (read before the System root folder) under a different name, and
set up the following batch file to rename it before booting Apache with the alternate httpd configuration file:
@ECHO OFF
CLS
RENAME php.ini.v5 php.ini
"C:\Program Files\Apache Group\Apache\Apache.exe" _
-f "C:\Program Files\Apache Group\Apache\conf\httpd.php5.conf"
The reverse is required when Apache is shut down, to ensure the version 5 ini
file is not called next time Apache is booted with version 4:
@ECHO OFF
CLS
CD "C:\Program Files\Apache Group\Apache"
apache -k shutdown
RENAME php.ini php.ini.v5
EXIT
Finally, with a shortcut to each of these two batch files, placed somewhere nice and accessible, I can now revel in the delights of the newly improved OOP and XML features, and the in built SQLite database, and revert back to PHP 4 when work needs to be completed.
Posted on Mar 27, 2004 at 04:48:14. [Comments for PHP 5 On Demand- 0]