Tag Archives: PHP

Static Caching in Drupal

If you’re a PHP veteran, then you know static caching is a relatively simple thing to do in PHP, but it can result in inconsistent behavior and sloppy code, such as adding an extra parameter to a function for the sole purpose of resetting that function’s internal cache.

Drupal’s static caching system improves upon the old way by providing a simple and consistent way for creating your own cache store and resetting cache stores set by other systems within Drupal.  The entire functionality of this system is wrapped up in the drupal_static() function, with a side function, drupal_static_reset(), for resetting any existing cache store.
Continue reading

IP Addresses in PHP/MySQL

I’ve been working on a web-based tool that stores, among other network-related things, IP addresses. When I first started I stored each IP address as four TINYINTS (0-255 for each octet):

mysql> DESC ipaddresses;
+----------+---------------------+------+-----+---------+----------------+
| FIELD    | TYPE                | NULL | KEY | DEFAULT | Extra          |
+----------+---------------------+------+-----+---------+----------------+
| id       | INT(10) UNSIGNED    | NO   | PRI | NULL    | AUTO_INCREMENT | 
| A        | tinyint(3) UNSIGNED | NO   |     | NULL    |                | 
| B        | tinyint(3) UNSIGNED | NO   |     | NULL    |                | 
| C        | tinyint(3) UNSIGNED | NO   |     | NULL    |                | 
| D        | tinyint(3) UNSIGNED | NO   |     | NULL    |                | 
+----------+---------------------+------+-----+---------+----------------+
5 ROWS IN SET (0.00 sec)
 
mysql> SELECT * FROM ipaddresses WHERE id=1
+----+----+----+----+-----+
| id | A  | B  | C  | D   |
+----+----+----+----+-----+
|  1 | 10 | 20 | 30 | 131 |
+----+----+----+----+-----+
1 ROW IN SET (0.02 sec)

As I started manipulating these addresses I found it awkward to do common binary math (like bitwise ANDs). I decided instead to store these 32-bit values as unsigned integers (of length 32). To make my life easier yet, MySQL and PHP both have native functions to convert IP addresses between my old and new formats to make this migration extremely easy.
Continue reading