Skip to main content

Posts

Building an Array with array_reduce?

Whether it’s twisting a function or taking advantage of side effects and flexible language constructs, it’s no secret I occasionally take joy in writing bastard PHP code. The other day I was in an evil mood and used array_reduce() to construct an array. If you’re not familiar with array_reduce() , it’s a function that iteratively reduces a given array to a single value using a callback function. For example, suppose the function array_sum() didn’t exist. We could achieve the desired functionality using array_reduce() like so: <?php $nums = [1, 2, 3, 4, 5]; $sum = array_reduce( $nums, function ($acc, $val) { return $acc + $val; }, 0 ); array_reduce() executes the callback function for each element in the array, passing to it an accumulator and the current array member. The returned value is used as the accumulator value for the next iteration. This is roughly the functional equivalent of this iterative approach: <?php $acc = 0; foreach ($nums as $val) { ...

Composing Music with PHP

I’m not an expert on probability theory, artificial intelligence, and machine learning. And even my Music 201 class from years ago has been long forgotten. But if you’ll indulge me for the next 10 minutes, I think you’ll find that even just a little knowledge can yield impressive results if creatively woven together. I’d like to share with you how to teach PHP to compose music. Here’s an example: You’re looking at a melody generated by PHP. It’s not the most memorable, but it’s not unpleasant either. And surprisingly, the code to generate such sequences is rather brief. So what’s going on? The script calculates a probability map of melodic intervals and applies a Markov process to generate a new sequence. In friendlier terms, musical data is analyzed by a script to learn which intervals make up pleasing melodies. It then creates a new composition by selecting pitches based on the possibilities it’s observed. . Standing on Shoulders Composition doesn’t happen in a vacuum. Bach wa...

PHP Assertions

I stumbled upon assertions in PHP today, though why I didn’t know they exist after working in the language for so long and what I was originally looking for when I came across them are both mysteries. And with the increasing focus on software quality in the PHP community, I wondered why I hadn’t seen them used by others. I decided to ask around. I asked a few friends if they knew about assertions. They did. I asked if they used them. They didn’t. Remi Woler : I think nobody has found a good use case. It weaves tests into code. How are you going to recover from a failed assertion? Davey Shafik : They kinda suck. For example: assert('mysql_query("")') It's a string of code that gets eval’d. So, PHP assert didn’t get stellar endorsements from people whose opinions I respect. My main experience with assertions comes from C where they are defined as macros. Its argument must evaluate true, otherwise the program terminates with an error. These checks can be st...

PHP_EOL: Most Worthless Constant?

PHP_EOL may very well be the most worthless general-purpose constant in modern PHP. It's supposed to be helpful for cross-platform developing, for example you could write a PHP-powered shell script that says: <?php echo "Operation Successful!" . PHP_EOL; and then expect the proper newline to terminate the output string based on the platform PHP is running on. That's all well and good, but the following is functionally equivalent: <?php echo "Operation Successful!\n"; Try it out and you'll see. In console output on Windows, Linux, and Mac they all are displayed with the expected newline terminating the output string. I don't see it being useful for writing data or log output to a file either. If you're writing and reading on the same platform then newline discrepancies won't be an issue, and if you're writing on one platform and reading on another then you'll want to standardize on a newline anyway. Has PHP_EOL ...

PHP Recursive Directory Traversal

It sounds like a simple enough task: Generate an array that mirrors a directory structure. Directories may have subdirectories (arbitrary nesting), and entries should be alphabetized with directories grouped first. The image below shows what the array should look like given a sample directory. While not terribly difficult, there are a few snags that can trip you up if you're not careful. For me, the first snag was trying to do it “the right way.” The RecursiveDirectoryIterator “provides an interface for iterating recursively over filesystem directories” ( php.net ), so this was my first approach. I hacked together this code after a short while: <?php function getDirectoryList($dir) { $dirList = []; $dirIter = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS); $iterIter = new RecursiveIteratorIterator($dirIter); foreach ($iterIter as $entry) { $path = substr($entry->getPath(), strlen($dir) - 1); $keys = "...

Writing a Minimal PSR-0 Autoloader

An excellent overview of autoloading in PHP and the PSR-0 standard was written by Hari K T over at PHPMaster.com , and it's definitely worth the read. But maybe you don't like some of the bloated, heavier autoloader offerings provided by various PHP frameworks, or maybe you just like to roll your own solutions. Is it possible to roll your own minimal loader and still be compliant? First, let's look at what PSR-0 mandates, taken directly from the standards document on GitHub : A fully-qualified namespace and class must have the following structure \<Vendor Name>\(<Namespace>\)*<Class Name> Each namespace must have a top-level namespace ("Vendor Name"). Each namespace can have as many sub-namespaces as it wishes. Each namespace separator is converted to a DIRECTORY_SEPARATOR when loading from the file system. Each "_" character in the CLASS NAME is converted to a DIRECTORY_SEPARATOR . The "_" character has no special ...

Doing a 180 on Grid 960

I've never been a fan of CSS frameworks; They just seem unnecessary to me. Every project can benefit from a reset.css file and maybe basic typography styles, but a whole framework? Meh. Then I read an excellent argument in favor of grid-layout frameworks in some book which I've since forgotten the name of and changed my mind (a tremendous feat indeed). I decided I'd make use of a grid-layout framework in my next project. I chose Grid 960 for the project since that was the one mentioned in the book, I had heard about it before, and it seemed to me the most mature and stable. My experiences with Grid 960 weren't bad per se... I mean, it didn't sour me back to my original mindset... but a few points will have me looking for another framework. The extra markup required is basically reminiscent of tables. Instead of <tr> or <td> though now you've got <div class="container_12"> and <div class="grid_3"> . Borders...

Are Coding Standards Futile?

Unless the visual layout of a program's code affects its execution, there will always be programmers who circumvent the established coding standards. I admit, I've done it myself from time to time. There's no scientific survey that such standards really reduce cognitive friction when reading someone else's code as far as I know, and aesthetic matters are generally subjective. Make the argument for tabs over spaces until you're blue in the face; someone will just come along touting the benefits of spaces. I warned achieving a consensus on PHP Coding Standards as PSR-1 would be difficult and that the group's efforts would be better spent discussing more "meatier" topics, such as object caching. Two months later, the proposal failed to garner enough votes for a simple majority and has now been split . And let's not forget the "Beat Up on Crockford" festival over bootstrap and JSMin . His comments were a bit harsh, yes... but then again h...

The Future of PHP, Ruby, and Esperanto

A few weekends ago I traveled down to Richmond, Virginia, for Urba Semajnfino 2 . It was my first Esperanto gathering, and it was a great opportunity both for a vacation and a chance to use Esperanto as a real language as opposed to just a study hobby. Afterwards, In the midst of the post-vacation blues that followed my return, I found myself thinking about the future of Esperanto, PHP, and Ruby. I've said before that Java is the new COBOL -- a lot of legacy code has been written in Java and still needs to be maintained, but "fresher" languages are increasingly considered when it comes time for new development. We've witnessed the increasing acceptance of PHP in enterprise environments which were predominantly steeped in Java in only a few years ago. And now that PHP is a mature, "grown up" programming language, I admit it's a little less fun to program with as it used to be. PHP is the new Java, and in 10-years time it may be the new new COBOL. A n...

Relative Date Ranges: Current Week of Prior Year

A handy feature in reporting applications is the ability to query data using relative date ranges. A relative date range is nothing more than a predefined start and end time offset some manner from the current date/time, but the specifics are hidden from the end-user behind a human readable label. For example, if you had a database full of access logs and wanted to query for a list of login failures that happened yesterday you could write: <?php $yesterday = sprintf("BETWEEN '%s 00:00:00' AND '%1\$s 23:59:59'", date("Y-m-d", strtotime("-1 day"))); $query = "SELECT username, tstamp, ip_address FROM failed_logins WHERE tstamp $yesterday"; The user could select "Yesterday" from a list, and the code would dynamically build the query accordingly. Alternatively, you could write it entirely in SQL using MySQL's date and time handling functions. It looks a bit messier, but is just as effective: SELECT ... BETW...