I’ve posted my 2010 NCAA Men’s Basketball Tournament randomized bracket generator. It’s a quick way to pick winners for your bracket pools. It simply weights each game by the teams’ tournament seedings. It ain’t fancy, but if you’re tired of spending hours trying to pick the winners only to find you’re out of the competition by the first Friday, well, this way at least you won’t have wasted as much time.
Beginners’ Corner: Variable Function Parameters
Sometimes when defining a function in PHP, you find that there may be cases where you do not want to specify all the possible parameters when calling it. This could be because you want it to use a default value, or that in certain cases it does not logically apply. If you find yourself in such a situation, probably the first thing you should do is ask yourself if two (or more) separate functions should be defined, instead. (Perhaps one function would call the other internally?)
Assuming you want to stick with one function, the most commonly used approach is to define a default value for one or more parameters in the parameter list. A parameter is assigned such a default value via the = operator, just as you would use it to assign a value in the function body.
function foo($bar='World') {
echo "Hello, " . $bar;
}
When the function is called at run-time, if that parameter is not included in the call, then the default value will be used; otherwise the supplied value is used.
foo(); // Hello, World
foo('Joe'); // Hello, Joe
If you want your function definition to include both required and optional (default) parameters, the required parameters must come first in the list.
function foo($req1, $req2, $opt1='something', $opt2=null) { }
In the preceding example, the use of null can be convenient in that PHP treats a null variable as “not set” by the isset() function, allowing you to do something like:
function foo($bar=null) {
if(isset($bar)) {
echo $bar;
} else {
echo "Nobody home";
}
}
Another approach which can be quite powerful in some ways, but for which I’ve really not run into much use myself, is the use of variable length argument lists. Essentially, the function prototype would have no parameters specified, then you use the func_num_args(), func_get_arg(), and/or func_get_args() functions to determine how many arguments were supplied and then decide what to do with them.
function test()
{
$numArgs = func_num_args();
switch($numArgs) {
case 0:
return false;
break;
case 1:
echo "Hello, " . func_get_arg(0); // args start numbering at zero
break;
case 2:
echo func_get_arg(0) . ", " . func_get_arg(1);
break;
default:
echo "Here are the args:<br /><pre>";
print_r(func_get_args());
echo "</pre>";
}
}
Lastly, another approach is to pass an associative array as the function parameter. You can then test for specific array keys to decide what to do.
function test($args)
{
if (!is_array($args)) {
user_error('Oops!');
return false;
}
if (isset($args['name'])) {
if (isset($args['verb'])) {
echo $args['verb'] . ", " . $args['name'];
} else {
echo "Hello, " . $args['name'];
}
}
return true;
}
A downside of this last method is that the function definition’s parameter list gives no clue by itself as to what array keys are expected/allowed. This can make it tricky to use and maintain, as the coder is at the mercy of the comments and documentation, or else is forced to read the entire function definition to figure out the possibilities.
Book List App: One Query to Rule Them All
I got side-tracked from working on this project for awhile, but I am trying to get back to it now.
One thing I needed to address was that for many of the database tables I would have situations where a user supplies some data, and if it already exists in the table then I just need the primary key for it, or else I need to insert it and then get the key. Typically I’ve seen people do something along the lines of a select query to see if it’s in there, and if not perform a second query to do the insert.
While thinking tonight about how ugly that is, it came to me that maybe I could do an INSERT…ON DUPLICATE KEY UPDATE query. What I wasn’t sure about was if you could get the insert ID if it already existed and therefore does an update. Upon reading the MySQL manual entry on it, it looked like it should work, but I still wasn’t positive the PHP mysql_insert_id() function would work with it, and even less sure the related CodeIgniter database functions would. After a bit of testing, the good news is, it works. This should save me doing extra queries in a number of places, plus eliminate any need for table locking (I think).
So the basic process is:
public function replace($lastName, $firstName)
{
$lastName = $this->db->escape($lastName);
$firstName = $this->db->escape($firstName);
$sql = "
INSERT INTO `author` (`last_name`, `first_name`)
VALUES ($lastName, $firstName)
ON DUPLICATE KEY UPDATE `last_name` = $lastName
";
$this->db->query($sql);
if($this->db->affected_rows())
{
return $this->db->insert_id();
}
return false;
}
Hopefully this will save me — and maybe you — a bit of processing time and coding time.
Memory Usage in PHP GD Image Functions
When working with the PHP GD Image functions, memory usage can become a serious issue. Where PHP developers often stumble is in not realizing that the various imagecreate*() functions create a bitmap in memory with data for each and every pixel. Therefore a source JPEG file that is only a few tens of kilobytes in size might need several megabytes of memory when used as the source of an image (e.g. imagecreatefromjpeg()).
As a rule of thumb to estimate the memory usage of a given image, figure that you’ll need 4 bytes per pixel (3 for the RGB color and 1 for the alpha channel). If you multiply that times the width and height of the image, you will then have a good working number.
Fortunately, PHP’s getimagesize() function will give you the dimensions of an image file without having to first convert it into a GD image, thus allowing you to decide if it’s too big for your application to use or not.
$imgAttrs = getimagesize('path/to/file.jpg');
$estimatedMemory = $imgAttrs[0] * $imgAttrs[1] * 4;
You can then use the result of that estimate to decide if you want to go ahead and process that image, or raise a red flag and do something else, instead.
Amazon Kindle for PC
Amazon.com has just released a beta version of Kindle for PC. This free application allows you to purchase and read Amazon Kindle e-books on your PC. If you also own their Kindle reader
, the application will sync with your existing account, making any e-books purchased through Amazon available both on your PC and your Kindle.
I just downloaded and installed it on my Windows 7 notebook PC, and everything seems to be working fine. The interface is pretty simple and straight-forward, and the syncing with my existing Kindle reader account appeared to work seamlessly. If you’ve been considering whether or not to purchase a Kindle, this could be a good way for you to investigate the availability of reading materials. If you’re already a Kindle owner, this could be useful for situations where it may be more convenient to read a book at your PC — such as your favorite PHP books, perhaps? (There, I made this post have something to do with PHP.)
Beginners’ Corner: Learning Object-Oriented PHP
I often see PHP newbies (and even not-so-newbies) who are confused by the world of object-oriented programming (OOP). At least part of this confusion results from the vast majority of introductory books and tutorials for PHP beginning by teaching procedural programming techniques, treating OOP as an “advanced” subject with a chapter or two at the end. Thus the student is exposed to a bunch of new syntax concerning classes and objects with, at best, a very brief explanation as to “why” that syntax should be used. A purely object-oriented language such as Java or Ruby, on the other hand, will by its nature require that beginners’ resources more fully address the theory of OOP.
I am not going to claim to be an OOP guru, but I can point you to a few resources I have used to become reasonably proficient — but still learning! — with PHP classes and objects. First I would point you to an on-line tutorial at Sun.com: “Lesson: Object-Oriented Programming Concepts“. While the (relatively few) examples in these tutorials are in Java, the syntax is quite similar to that of PHP, and the lessons they illustrate are easily transferred to PHP. If you want to work with those examples yourself in PHP, I would recommend taking a look at a couple PHP tutorials at IBM.com: “Getting started with objects in PHP V5” and “Advanced PHP V5 objects“.
Once you’ve gotten past the basics, to see how things can work together as an OOP whole, I strongly suggest you get your hands on Matt Zandstra’s book, PHP Objects, Patterns, and Practice. Reading this book is what ultimately made objects “click” in my mind. After reading it I felt much more comfortable with the underlying concepts along with the specific techniques for applying them in my PHP projects.
Implementing a Database-based Session-handler
While I’ve been using the database session data handler in the CodeIgniter framework for some time, upon reading this thread at PHPBuilder forums I decided it was time to write my own. In part I just wanted to gain a more thorough understanding of the process, and I also figured I could use it some day for a small project that does not require the power of CodeIgniter or something similar.
I decided to use an OOP approach for this, creating two classes. One class, SessionHandler, would be the interface the client code will use to establish the session-handler functions. A second class, SessionData, would handle the actual interface with the database. For now it uses the MySQLi database
interface; but if I wanted to use PDO or something else, I would just need to either edit the SessionData class appropriately, or even go to some sort of abstract factory pattern, perhaps, to instantiate a DBMS-specific class. For now, though, I’ll just keep it “simple” with only the MySQLi class.
Continue reading ‘Implementing a Database-based Session-handler’ »