Creating A Database Connection On Demand
It may be useful to only create a database connection when you actually use it for the sake of efficiency. Here is a wrapper for MySQLi that does just that in the most simple way I could devise. A (possibly desired) side-effect is that this limits you to a single connection.
How you pass in the connection details is up to you. You can hard-code them into the mysqli initialization, put them in class constants, or pass them into a constructor that sets static properties.
<?php /** * Wrapper for MySQLi * * Creates a database connection on demand */ class DB { private static $db; private function connect() { if(!isset(self::$db)) { self::$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); } } public function __call($name, $arguments) { $this->connect(); return call_user_func_array(array(self::$db, $name), $arguments); } public function __get($name) { $this->connect(); return self::$db->$name; } public function __set($name, $value) { $this->connect(); self::$db->$name = $value; } public function __isset($name) { $this->connect(); return isset(self::$db->$name); } public function __unset($name) { $this->connect(); unset(self::$db->$name); } }
Usage:
<?php $db = new DB(); // functionally identical to a mysqli object $db->query('...');
Round Robin Tournament Scheduler
Here's a snippet I wrote for a project that I thought might come in handy for someone else. It generates a schedule for a round robin tournament. I found some other snippets to do this, but I found them overly complicated or lacking in other ways.
Here's an example of what this code does:
< ?php $players = range(1, 8); echo 'Original List: ' . PHP_EOL; print_r($players); echo PHP_EOL; echo 'Round Robin Schedule: ' . PHP_EOL; print_r(generateRRSchedule($players)); ?>
Output:
Original List:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
)
Round Robin Schedule:
Array
(
[0] => Array
(
[0] => Array
(
[0] => 1
[1] => 8
)
[1] => Array
(
[0] => 2
[1] => 7
)
[2] => Array
(
[0] => 3
[1] => 6
)
[3] => Array
(
[0] => 4
[1] => 5
)
)
(...)
)Snippet: Fetch Twitter Feed (With Retweets) in PHP
Here is a PHP that fetches a Twitter stream for a specified user. It also combines retweets with the regular updates. This puts them all in an array to make it easy to output them however you want.
This snippet uses APC to cache the data, but you can use any caching method such as memcached or database. It should be fairly easy to edit in your own caching.
Snippet: Maintain a Single Database Object in PHP 5 Using the Singleton Pattern
When creating a PHP application, it is usually necessary to connect to a database to perform certain tasks. In some cases you only want to open a connection when necessary, but limit it to a single connection. This way you don't waste resources on unnecessary database connections. For these situations I use the Singleton Pattern, which is perfect for this.
In this example, we are creating a MySQLi object and forcing it to a single instance. We just need to call DB::get() to create and/or access the object.
Snippet: Converting Seconds to Readable Time (PHP & JS)
Sometimes, you might need to convert an integer representing seconds into a format that is easier to read. These functions can be used to turn a number of seconds into a simple format of HH:MM:SS, with leading zeros (ex. 15272 = 04:14:32). This can be used for countdown scripts, which is why I also include both a PHP and a JavaScript version.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function formatTime($secs) { $times = array(3600, 60, 1); $time = ''; $tmp = ''; for($i = 0; $i < 3; $i++) { $tmp = floor($secs / $times[$i]); if($tmp < 1) { $tmp = '00'; } elseif($tmp < 10) { $tmp = '0' . $tmp; } $time .= $tmp; if($i < 2) { $time .= ':'; } $secs = $secs % $times[$i]; } return $time; } |
Snippet: Autoloading Objects (PHP 5)
When writing the PHP that powers TempServers, I wrote the core functions into classes for better organization and efficiency. To make things further organized, each class is stored in individual source files, no matter how small. The problem here is keeping track of which classes are used where, in order to include the appropriate source files. Fortunately, PHP 5 offers a solution: autoloading.
This comes in the form of the __autoload function which automatically gets called if a class is called that does not exist. Here's what it looks like:
function __autoload($class) { require_once(strtolower($class) . '.class.php'); }
Usage
- Place each PHP class in individual files named after the class followed by .class.php (Example: class MyClass goes in a file named myclass.class.php).
- Include the code snipped above into any file that might use one of your classes.
For more details, check out the PHP manual: http://www.php.net/manual/language.oop5.autoload.php
