docopt gets CLI argument parsing right

Brilliant ideas can be painfully obvious in retrospect. They’ll leave you thinking, “Why didn’t we I think of that before?!” Docopt is that for parsing CLI arguments.

Generate 4 language bindings for your API in one Go #

You just built an API, and want to make sure everyone can use it. Building libraries in every language isn’t only going to be hard, its going to take a lot of time. Time you don’t have. This is where Alpaca can help.

You define your API according to the format, alpaca builds the API libraries along with their documentation. All you have to do is publishing them to their respective package managers.

Right now it can generate API clients in PHP, Python, Ruby, and JavaScript. You can see examples of the generated client libraries here. I can’t speak to the quality of all the generated language bindings, but I took a cursory look at the Python lib and it looks good. Looks like Alpaca could save us all a lot of time.

Meet Boris, a tiny REPL for PHP #

Chris Corbyn was frustrated with PHP’s lack of a good REPL, so he took matters into his own hands and created Boris. I can relate to Chris’s experience. Back when I used to write WordPress plugins I got so frustrated by the lack of a Rails-like interactive console that I created one for WordPress.

Boris is cooler than my little plugin because it works outside of WordPress and runs directly in your terminal. Check it out in action:

You can install Boris via Packagist or use it directly by cloning the repo:

git clone git://github.com/d11wtq/boris.git
cd boris
./bin/boris

This and much more information about the REPL is available in the README. Boris is MIT licensed and hosted on GitHub.

Bring your server side debug logging into the browser with Chrome Logger #

If you find yourself jumping back and forth between Chrome’s Dev Tools and a terminal displaying your server side request logs, Craig Campbell’s Chrome Logger might be just the thing you need!

It’s a Chrome extension which lets you see your server side logs right in the browser. There are currently libraries for:

Is your server side language/environment of choice not on that list? Don’t worry, Chrome Logger uses an open and published protocol so you can easily write client libraries of your own!

See the project’s home page for more info or check under the hood if you’re curious about how it all works.

Requests – HTTP library for PHP #

Higher level libraries for dealing with HTTP are cropping up in almost every language. The latest is Requests, a PHP library from Ryan McCue. Inspired by Kenneth’s Python library of the same name, Requests aims to provide a better HTTP API than cURL:

$headers = array('Accept' => 'application/json');
$options = array('auth' => array('user', 'pass'));
$request = Requests::get('https://api.github.com/gists', $headers, $options);

var_dump($request->status_code);
// int(200)

var_dump($request->headers['content-type']);
// string(31) "application/json; charset=utf-8"

var_dump($request->body);
// string(26891) "[...]"

I’ve written about my thoughts on what makes a good API wrapper and libraries like these that provide a more idiomatic experience are just great.

Grab Requests on GitHub.

Imagine – Unified PHP 5.3 API for GD2, ImageMagick, GraphicsMagick #

Imagine is a nice looking image manipulation library for PHP 5.3+ that supports GD2, ImageMagick, and GraphicsMagick in a clean, chainable API from Bulat Shakirzyanov:

<?php

$imagine = new ImagineGdImagine();
// or
$imagine = new ImagineImagickImagine();
// or
$imagine = new ImagineGmagickImagine();

$size    = new ImagineImageBox(40, 40);

$mode    = ImagineImageImageInterface::THUMBNAIL_INSET;
// or
$mode    = ImagineImageImageInterface::THUMBNAIL_OUTBOUND;

$imagine->open('/path/to/large_image.jpg')
    ->thumbnail($size, $mode)
    ->save('/path/to/thumbnail.png')
;

Check out the extremely detailed project docs and examples for advanced usage.

#54: CouchBase, Erlang, and Mergers with J Chris Anderson

Wynn sat down with J Chris Anderson from CouchBase to talk about CouchDB, the merger with Membase, Erlang, and bringing NoSQL to PHPers. Items mentioned in the show: J Chris Anderson is a Couchbase cofounder, Mobile Architect, CouchDB committer, new dad The CouchDB music video (served up from CouchDB no less) Chris sings the official […]

Options-Framework: Expose an options panel for your Thematic WordPress themes #

I don’t always use WordPress, but when I do, I prefer Thematic (and compass-wordpress). Thematic is a WordPress theme framework from Ian Stewart that provides an abstracted API, letting you focus on your site instead of the lower-level minutia of WordPress.

I was excited when I stumbled across a couple of projects by Devin Price that let you easily expose an options panel for your theme. Thematic Options (and the non-Thematic Options Framework) make it easy to add an options panel for your theme settings, letting your end users customize your theme in the WordPress admin panel.

screenshot

Options are declared in a PHP array, as in this example:

// Set the Options Array
global $my_options;
$my_options = array();

$my_options[] = array( "name" => "General Settings",
                    "type" => "heading");

$my_options[] = array( "name" => "Custom Logo",
          "desc" => "Upload a logo for your theme, or specify the image address of your online logo. (http://yoursite.com/logo.png)",
          "id" => "logo",
          "std" => "",
          "type" => "upload");

$url =  ADMIN . 'images/';
$my_options[] = array( "name" => "Main Layout",
          "desc" => "Select main content and sidebar alignment. Choose between 1, 2 or 3 column layout.",
          "id" => "layout",
          "std" => "2c-l-fixed.css",
          "type" => "images",
          "options" => array(
            '1col-fixed.css' => $url . '1col.png',
            '2c-r-fixed.css' => $url . '2cr.png',
            '2c-l-fixed.css' => $url . '2cl.png',
            '3c-fixed.css' => $url . '3cm.png',
            '3c-r-fixed.css' => $url . '3cr.png')
          );
$my_options[] = array( "name" => "Custom Favicon",
          "desc" => "Upload a 16px x 16px Png/Gif image that will represent your website's favicon.",
          "id" => "custom_favicon",
          "std" => "",
          "type" => "upload"); 

$my_options[] = array( "name" => "Tracking Code",
          "desc" => "Paste your Google Analytics (or other) tracking code here. This will be added into the footer template of your theme.",
          "id" => "google_analytics",
          "std" => "",
          "type" => "textarea");

...

Devin has a nice blog post with more info including how to use these values in your theme, along with an introductory screencast.

[Source on GitHub]

Respect, Validation for PHP developers #

Are you a PHP developer who feels like you get no respect? That’s exactly what Alexandre Gomes Gaigalas and Carlos A. Ferrari are offering with their GitHub organization.

Validation is billed as “the most awesome validation engine ever created for PHP.” While that might be the epitome of hyperbole, it is indeed nifty. Validation includes more than 30 chainable validators supporting composite validation of nested, grouped, and related rules.

Let’s look at a simple example:

use RespectValidationValidator as v;
v::numeric()->validate($someNumber); //returns true or false 

We did mention chaning, right?

//From 1 to 15 non-whitespace alphanumeric characters 
$username = 'alganet';
$validUsername = v::alnum()
                  ->noWhitespace()
                  ->length(1,15)
                  ->validate($username);

Validators are also reusable:

$idValidator = v::int()->positive();
$idValidator->validate(123); //true
$idValidator->validate(456); //true

Be sure and check the Readme for advanced usage. Also be sure and check out Respect’s other projects including:

  • Relational is a chainable abstraction for relational database queries
  • Daemon is a library for managing daemon systems using PHP
  • Stream is a lightweight, asynchronous, object-oriented layer for the great PHP stream API
  • Env is a lightweight, transparent, testable and awesome environment wrapper for PHP

[Source on GitHub]

GitHub Follow Friday for 20101029

Another Friday, time to spotlight some GitHub folks you should follow. tenderlove (Aaron Patterson) The author of nokogiri and mechanize, Aaron also empowers you to do fuzzy texticle searches. isaacs (Isaac Z. Schlueter) The man who helps you manage your package using npm. abraham (Abraham Williams) The author of the canonical PHP library for the […]

modernizr-server: Modernizr on the server-side #

James is a technologist, executive & entrepreneur, working in the arena of the mobile web, all while living around the world. This year he happens to be living on an island off Belize.

He also wrote modernizr-server – a way to bring Modernizr browser data to your server scripting environment. PHP is currently supported, and James intends to offer other server-side environments in the future, but that’s going to be based on demand!

We’ve covered Modernizr being used in other projects before. Modernizr is a great way to find out about your user’s browser capabilities. However, you can only access its API on the browser itself, which means you can’t easily benefit from knowing about browser capabilities in your server logic.

Progressive enhancement, media queries and body classes are fine for tweaking sites and their appearance. But for structural changes to sites and pages, sometimes it’s much simpler to just emit the right markup from the server in the first place.

The modernizr-server library is a way to bring Modernizr browser data to your server scripting environment. For example, in PHP:

<?php

    include('modernizr-server.php');

    print 'The server knows:';
    foreach($modernizr as $feature=>$value) {
        print "<br/> $feature: "; print_r($value);
    }

?>

The server knows:
canvas: 1
canvastext: 1
geolocation: 1
crosswindowmessaging: 1
websqldatabase: 1
indexeddb: 0
hashchange: 1
...

How it works

The first time the user accesses a page which includes the modernizr-server.php library, the library sends the Modernizr script to the client, with a small script added to the end. Modernizr runs as usual and populates the feature test results.

The small suffix script then serializes the results into a concise cookie, which is set on the client using Javascript. It then refreshes the page immediately.

This second time the PHP script is executed, the library takes the cookie and instantiates the server-side $modernizr object with its contents. If possible, this is placed in the PHP $_SESSION so that it can be quickly accessed in subsequent requests.

While either of the cookie or session remain active, no further execution of the Modernizr script will take place. If they both expire, the next request to a page containing modernizr-server.php will cause the browser to rerun the Modernizr tests again.

And also …

You might also want to read James’ blog post on Modernizr on the server-side.

Check out the codes

[Source on GitHub] & [Documentation]

WatchWednesday for 20100929

It’s Wednesday again, time for us to serve up another quick list of projects to watch on GitHub. These are projects you might have missed or should could keep an eye on. Heroku::Autoscale David Dollar makes automatically scaling your Heroku dynos a snap with this gem. Simply add the gem to your Gemfile gem ‘heroku-autoscale’ […]

Slim: A PHP5 Sinatra Clone #

Screen shot

Frank Sinatra was the Chairman of cool. Some fourteen years after his death, the crooner is still imitated.

Just like its namesake, Sinatra, the class Ruby web application DSL still inspires all sorts of projects from Sammy.js to Padrino to Denied.

Slim, a PHP5 project from Josh Lockhart is the latest project to cover the classics.

Setup

To get started, just require the script and call init

<?php
require('slim/Slim.php');
Slim::init();
?>

Routing

Slim supports the familiar Sinatra-style routes for all four HTTP verbs:

Slim::get('/books/:id', function ($id) {
    //Do something
});

Slim::post('/books', function () {
    //Do something
});

Slim::put('/books/:id', function ($id) {
    //Do something
});

Slim::delete('/books/:id', function ($id) {
    //Do something
});

Middleware and callbacks

Slim also allows you to run code before and after your actions:

Slim::before(function () {
    //Do something
});


Slim::after(function () {
    //Do something
});

Templating

Slim supports a variety of templates including Smarty and Twig.

[Source on GitHub] [Hompage]

Episode 0.2.4 – Facebook Open Source projects: Tornado, Hip-hop, and Three20

Adam and Wynn caught up with David Recordon and other Facebook developers to talk about their wide range of open source projects including Tornado, Hip-Hop, and Three20 as well as OpenGraph and OAuth 2.0. Mentioned in the show: David Recordon Open Source developer at Facebook, co-creator of OAuth Paul Bucheit Co-founder of FriendFeed, creator of […]

Snapbird – Twitter search on steroids #

If you’ve ever spent time looking for a long lost tweet and have gotten frustrated by the short window that tweets are indexed by Twitter Search, then check out Snapbird from Remy Sharp of jQuery for Designers fame.

Snapbird lets you search someone’s timeline, favorites, or your own direct messages without the 7 day Twitter Search restriction. It even lets you permalink favorite queries.

Snapbird also uses Twitterlib, Remy’s JavaScript Twitter API wrapper.

Snapbird is open source so you can either use the hosted version or fork the project and run your own.

[Source on GitHub] [Homepage]

Phake: M/Rake for PHP #

It’s always refreshing to see language communities learning from eachother. PHP now as its own clone of GNU Make and Ruby’s Rake: Phake.

Automation Ahoy!

Phake supports task grouping, before/after blocks, and task descriptions. Requires PHP >= 5.3 (for closures).

Here’s a simple task definiton:

task('dependency1', function() {
      echo "i will run first!n";
});

task('dependency2', function() {
  echo "i will run second!n";
});

task('task_name', 'dependency1', dependency2', function() {
      echo "i will run last!n";
});

And to run the task, simply:

./phake task_name

[Source on GitHub]

CoreyLib: PHP Universal API Wrapper #

The PHP world is filled with API and XML Parsers that often bring page rendering to a crawl.

Aaron Collegeman’s CoreyLib library is an incredibly simple universal API wrapper with caching built in.

It can handle most modern APIs with full XML, JSON, authentication, parameterization, xmlNode, and Xpath support. All requests can be cached in MySql and parsed at a custom interval to dramatically improve page rendering speed.

Here’s all the code needed to get the latest 5 tweets from twitter:

Source on GitHub

Fiber: A simple PHP interface to CouchDB #

Fiber from Luis Gomez is a simple way to add CouchDB storage to your PHP app.

Given a User class that extends a Fiber Document:

$user = User::find('john');
$user->email = "john@example.com";
$user->city = "San Francisco";
$user->save();

Fiber also includes some nifty chaining:

$user->set( array( "email" => "peter@example.com", "city" => "Caracas" ) )->save();

Check out the examples in the source.

[Source on GitHub]

storytlr – lifestreaming for geeks #

Open Source has its own Circle of Life. As we discussed in Episode 0.1.1, Open Source creates opportunities for entrepreneurs. Sometimes those businesses can spin off their own projects, paving the way for the next round of startups.

Sometimes commercial apps just don’t survive, but let’s not confuse viable with valuable. Take the case of Storytlr, a hosted lifestreaming service which sought to let you remix your social networking interactions into your own “stories.” When the hard decision was made to pull the plug on the service at the end of last year, the founders did what many apps have done and handed the source code over to the community.

The official Storytlr open source project is on Google Code but John Hobbs has a fork on GitHub that adds:

  • A tool to rename users (dangerous if not handled properly)
  • Plugins built in for…
  • Github
  • goodreads
  • Foursquare
  • Stack Overflow
  • Twitter favorites
  • Google Buzz
  • Ability to delete items that are from other sources (not just ones from Storytlr itself)
  • tidy is replaced by htmLawed
  • Misc fixes for issues reported on the Google group
  • Misc fixes from other forks, esp. paths courtesy of Stuart Herbert

For a live demo, check out @abraham’s Storytlr at http://stream.abrah.am/.

Storytlr runs on PHP (which runs darn near everywhere) and installation instructions can be found in the README.

[Official Google Code Project] [Source on GitHub]

riak – high performance document store built on JSON and REST #

riak
Riak, REE-ahk, combines the power of Erlang with the ubiquity of JSON to deliver a highly scalable document store over REST. Hold on CouchDB fans, before you pounce, you haven’t heard this one before.

Master-less replication

Riak is architected for master-less replication from the GET-go. All nodes participate equally in the replication so scaling horizontally means just adding new servers to join the party.

Links for powerful object graphs

Riak supports link-walking which is far more powerful than traditional relational DB joins. As Sean Cribbs explains:

Every datum stored in Riak can have one-way relationships to other data via the Link HTTP header. In the canonical example, you know the key of a band that you have stored in the “artists” bucket (Riak buckets are like database tables or S3 buckets). If that artist is linked to its albums, which are in turn linked to the tracks on the albums, you can find all of the tracks produced in a single request. As I’ll describe in the next section, this is much less painful than a JOIN in SQL because each item is operated on independently, rather than a table at a time. Here’s what that query would look like:

GET /raw/artists/TheBeatles/albums,_,_/tracks,_,1

More powerful Map/Reduce

Map/Reduce works a bit differently in Riak. Riak’s Map function expects a list of keys on which it should run. You can of course pass every key in your bucket, but doing Map in this way allows Map to be run on the node where the data is actually stored.

Riak ships with libraries for Python, Ruby, Java, Erlang, and even JavaScript. Want to know more? Stay tuned. Riak will be the focus of an upcoming episode of The Changelog.

[Source on BitBucket] [Homepage] [Brian Fink’s NYC-NoSQL talk]

Kohana – The Swift PHP Framework #

Kohana is a PHP MVC web framework that aims to be easy, lightweight, and secure. It has no dependencies on PECL or PEAR extensions and uses strict PHP 5 OOP. It uses what it calls “cascading resources” to allow developers to extend the framework without editing the core system.

There is an extensive list of [modules], even a MongoDB ORM, MangoDB.

[Source on GitHub] [Homepage] [Docs]

Facebook’s HipHop leaves PHPers dancing #

When Twitter faced early scaling issues, much was made of decisions to rewrite large portions of the Rails site in Scala.

Facebook however has decided to double down on PHP, releasing HipHop, a PHP source code transfomer:

HipHop programmatically transforms your PHP source code into highly optimized C++ and then uses g++ to compile it. HipHop executes the source code in a semantically equivalent manner and sacrifices some rarely used features — such as eval() — in exchange for improved performance. HipHop includes a code transformer, a reimplementation of PHP’s runtime system, and a rewrite of many common PHP Extensions to take advantage of these performance optimizations.

** Update **

We posted this blind yesterday when GitHub was unavailable. Looks like the repo isn’t public yet. Keep an eye out. GitHub explore shows five watchers…

[Source on GitHub] [Announcement]

phpMoAdmin: MongoDB admin tool for PHP #

Extra (or deducted, depending on your point of view) points for an SEO optimized repo name, phpMoAdmin aims to be mo’ admin than phpMyAdmin by providing a MongoDB administration tool for PHP. phpMoAdmin is built on a stripped-down version of the Vork high-performance framework.

Features include:

  • Database

    • List
    • Create/drop
    • Repair
  • Collection
    • Show collections
    • Create/drop collection
    • List indexes
    • Create/drop indexes
  • Data objects
    • Show objects with 3-different viewing options (full, compact & uniform)
    • Create/delete objects
    • Edit object data
  • Mongo GridFS
    • GridFS objects automatically link GridFS chunks to GridFS files

[Source on GitHub] [Homepage]