Skip to main content

Posts

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...

Esperanto Accented Characters in Ubuntu

Today I got fed up with typing Esperanto using the x-method, the practice of following letters that would be accented with an X since the accented characters aren't on the typical keyboard. For example, the word "ankaŭ" would be typed as "ankaux." This is the 21st century, though, and there had to be some easy way enter properly-accented characters! Believe it or not, there is an Esperanto keymap, but I didn't feel like going that extreme since it would make entering other characters that I type on a day-to-day basis more difficult. Instead I tracked down how to augment my English (US) keymap with the extra functionality I needed, and it was easier than I had expected it to be. So if you want to set up your keyboard to type Esperanto accented characters, here's the steps. First, find the Keyboard Layout applet in Ubuntu/Gnome's System Settings window. Then, select the keymap you want to modify (here there's only one) and click the Opt...

Dio, iun novan bonvolu doni al mi!

Tradukita de Please God, Give Me Something New! . Koran dankon al Jon Z kaj 黄鸡蛋/Ĉitano pro ilia kontrolado. “Jen... rigardu ĉi tiun <ligilon>. Tamen, vi devas uzi la plej freŝan version de Chrome.” Aĉ! Ĉu ni ne jam spertis tion? 15 jaroj pasis, kaj nun ni reiras rekte al la sama loko, kie ni ekiris… “Plej bone aspekta pere de .” Estas vera domaĝo. Ne miskomprenu min. Jaroj da laboro por normigi HTML, JavaScript, la DOM, CSS, ktp klarigis multajn malklaraĵojn, kaj tio ja estis necesa. Sed striktaj reguloj ankaŭ sufokas kreadon. Ĉar HTML5 kaj ĝiaj amikoj forigis kelkajn el la limigoj, la pendolo svingiĝi antaŭen. Homoj ekkreas denove. Sed, nun kontraŭas Firefox kaj Chrome anstataŭ Internet Explorer kaj Netscape. Tamen, estas sistema problemo preter la “foliumiloj militoj.” Ĉu vi memoras AOL? Facebook nun klopodas esti “La Interreto.” Ĉu vi memoras komputilegojn kaj verd-ekrajnojn? Ni puŝis ĉion al la komputila labortablo, kaj nun puŝas ĉion reen “al La Nubo.” Ĉiuj el la kvara k...

Please God, Give Me Something New!

"Here... check out this (link). But you have to use the most recent version of Chrome." Sigh. Haven't we been through this already? 15 years have passed and we're headed right back to the same place we started... "Best viewed in <someone's favorite browser>." It's sad, really. Don't get me wrong. Years of standardization work on HTML, JavaScript, the DOM, CSS, etc. cleaned up a lot of messy lose ends and yes it was indeed necessary, but stringent standardization also stifles creativity. And now that HTML5 and friends have loosened some of the restrictions the pendulum has started to swing back in the opposite direction. People have started to innovate again. This time around it's Firefox vs Chrome instead of Internet Explorer vs Netscape. There's a systemic problem that goes beyond browser wars, however. Remember AOL? This time it's Facebook trying to be “The Internet.” Remember mainframes and terminals? After pushing everyt...

Top-10 PHP String Functions

By day I work as a programmer at ShoreGroup, Inc . By night I'm a freelance developer and now the managing editor for SitePoint 's latest site, PHPMaster.com . Helping out with the site has been pretty fun so far; my Australian counterparts are all pretty cool, and I've met some really great new authors too. If you haven't visited yet, take a moment and check out PHPMaster.com (there's still some wrinkles to iron out on the site, but we're working to identify and fix them all as soon as we can). Part of my duties as a managing editor include working with authors to make sure the site's content is well balanced. PHPMaster.com is targeting PHP programmers of all skill levels, so there should be a good mix of basic, beginner, intermediate, and advanced content. Planning for a beginner article that demonstrates basic string handling functions, I wondered which function to highlight. I wanted to show ones that would be most relevant, not necessarily ones that we...