PHP

A First Look at Fuel

UPDATE: I didn’t really mention that Fuel is an open source project. If you want to help out, head over to their github page, fork your own repo and get submitting!

UPDATE UPDATE: I’m not actually affiliated with the Fuel project, just a user. Please direct all suggestions over to their contact form or comment on github. thanks 🙂

There was an announcement a while back from Phil Sturgeon and a few others (shortly after some issues came to light with a certain other framework) about a new framework they were developing that came to be called Fuel. According to their site, the goal is to be:

a simple, flexible, community driven PHP5 framework. FUEL aims to take the best idea’s from a bunch of frameworks, throw away the “not so good” stuff, and create one awesome framework. It is provided under the terms of an MIT License, which means it’s free to use in your personal, commercial or enterprise projects.

What’s that? Why does the web need another framework? Well, to be honest, it doesn’t – but there is one thing that Fuel has going for it. If you’re one of the many CodeIgniter users out there, you’ll feel almost immediately comfortable with it. Since the devs are CodeIgniter fans themselves, they’ve built a lot of the same feel into how Fuel handles your applications. Unfortunately, there’s not a user guide for it yet, so I figured I’d share some of my experiences with it and maybe get you set down the road to fuel-ing your app (yep, that cheesy pun was required).

So, to get started, here’s some simple installation instructions:

  • Grab the latest source from Github (this will probably change when they make releases)
  • Unpack the files into a web-accessible directory. Mine are in /www/htdocs/fuelapp
  • There’s a /public directory in there – that’s where you need to point the DocumentRoot to
  • Make sure that AllowOverrides is set to use .htaccess and that mod_rewrite is installed and working
  • Move the “example.htaccess” file over to just “.htaccess” to make the rewrites work
  • At this point, when you visit the host for your site, you should get the “Welcome” message
  • Be sure to chmod the app/cache and app/logs directories so that the web server user can read/write to the directories.

That should get you started and have your basic application structure all set to go. In the basic layout, your application will live in the /app directory (makes sense, eh?) with the actual framework living in /core. As far as the three pillars of a MVC framework – they’re in classes/controller, classes/model and views. There’s also a config directory that houses the configuration files for your application.

Let’s start with the controllers – here’s an example snippet from the welcome controller showing you a basic controller structure:

[php]
<?php

use FuelController;

class Controller_Welcome extends ControllerBase {
public function action_hello()
{
$this->output = ‘Hello ‘.$this->param(‘name’);
}
}
[/php]

This action is called at http://localhost/welcome/hello (obviously replacing the hostname with yours).

If you haven’t seen something like the “use” call before, don’t worry. It’s just namespacing. The framework is PHP 5.3 only, so they can use fun things like namespacing and closures. In the example above, they load the FuelController namespace and extend the ControllerBase by default. There’s some naming conventions to look out for in controllers:

  • Controller class names should be “Controller_*”
  • They should extend ControllerBase
  • Methods should be “action_*”
  • Output pushed to the view belongs in $this->output

Something you don’t see in the above example is how to interact with the view. You’ll need to use the View class to get your data loaded into the right place. Here’s an example of that:

[php]
public function action_index()
{

$arr = array(
‘data’ => ‘test data’,
‘partial’ => View::factory(‘test/partial’)->render()
);

$this->output = View::factory(‘test/index’,$arr);

}
[/php]

If you’re quick, you’ve spotted the “partial view” I’ve simulated. By calling that “render” method on the view object, it returns the results as a string that can be appended. The parameter in that “factory” call is the path to the view file. So, the string “test/index” refers to the file /app/views/test/index.php.

There’s already some handy built-in helpers for the framework. It seems like all of them I saw were able to be called statically. So, for example – here’s how you could use the Uri helper:

[php]
public function action_uri()
{
$detect = Uri::detect();
var_dump($detect);
}
[/php]

Oh, and one last thing I know some of you are wondering about – database connectivity. Right now, there’s only MySQL connectivity, but I’m sure that’ll change quickly. Here’s a simple database example to get you started:

[php]
public function action_database()
{

$db = Database::instance();
$tables = $db->list_tables();
var_dump($tables); echo ‘<br/><br/>’;

$result = $db->query(Database::SELECT,’select * from test_data’,false);
var_dump($result); echo ‘<br/><br/>’;

var_dump($result->current());
$result->next();
var_dump($result->current());

$this->output = ‘test’;
}
[/php]

Instead of just returning arrays or whatever, the datbase calls by default return iterators. I nice touch in my opinion that could go a long way to help SPL adoption. You can also define an object type on the “query” call that lets you map to and object type.

So far so good…like I said, if you’re a CodeIgniter fan, you’d do well to check out Fuel. It feels more like what CodeIgniter should be when it grows up and joins the rest of the PHP frameworks in the PHP5+ world. I’ve already submitted a small update back to the framework and can already say that the community for it is friendly and open to whatever help they can get. Dan Horrigan, Phil Sturgeon and Jelmer Schreuder are doing a great job so far and I look forward to some more great things to come.

I’m going to continue messing with it and will try to post any fun things I might come across. Feel free to ask me about installation or some of the basics of the framework. I’m happy to share what I know.

Oh, and for those wondering, here’s my sample controller I’ve pulled these samples from:

[php]
<?php

use FuelController;

class Controller_Test extends ControllerBase
{

public function action_index()
{

$arr = array(
‘data’ => ‘test data’,
‘partial’ => View::factory(‘test/partial’)->render()
);

$this->output = View::factory(‘test/index’,$arr);

}

public function action_caching()
{
Cache::set(‘mykey’,’testing’);
$cacheOutput = Cache::get(‘mykey’);

$this->output = ‘cache output: ‘.$cacheOutput;
Cache::delete(‘mykey’);

$this->output.=’cache after: ‘.Cache::get(‘mykey’);
}

public function action_uri()
{
$detect = Uri::detect();
var_dump($detect);
}

public function action_database()
{

$db = Database::instance();
$tables = $db->list_tables();
var_dump($tables); echo ‘<br/><br/>’;

$result = $db->query(Database::SELECT,’select * from test_data’,false);
var_dump($result); echo ‘<br/><br/>’;

var_dump($result->current());
$result->next();
var_dump($result->current());

$this->output = ‘test’;
}

}

?>
[/php]

A Partial Review of “Test-Driven JavaScript Development”

So ever since the fine folks at Addison Wesley sent over a copy of Test-Driven JavaScript Development (by Christian Johansen) I’ve been trying to wrap my head around a new sort of testing when it comes to web apps. I’m not even half-way through the book and I’ve already had my mind blown by advanced javascript and testing methods that I just never thought about when I work on my frontends.

I’m a big fan of unit testing and promote it whenever I can – not only does it help create a code base that a better quality, but it also lets you keep things consistent. No more of the “cross your fingers” kind of coding. A good, well-written set of unit tests can save you a whole world of hassle in the long run. Taking it one step further, you get to TDD (test-driven development) where you write your tests before you even write your code. You start with the usual “W”s – why, where, when, how (yes, I know that last one’s an “H”s) and develop the test for those rather than looking at a current chunk of code and testing what it already does. There’s some people that swear by it, one of them being the author of this book.

He starts with an introduction to TDD and a general how-it-works with javascript quickly followed by an introduction to his tool of choice – JsTestDriver. All of the test examples in the following chapters are run with this tool. Thankfully it’s simple to set up and even easier to write tests for. He shows some introductory tests to help you get familiar with things before diving into the next section – testing javascript itself.

I have to admit, this section left me at a loss for words. I thought I knew a good bit about how javascript works, both out in front and behind the scenes. I was surprised, however, just how much of the functionality he tested I had no idea worked that way. It’s pretty in-depth, so if you’re a beginning javascript dev, you might go read some more tutorials before diving right in.

I’m just now getting to the “Unobtrusive Javascript” part of the book (Part 2, Chapter 9) so I still have a ways to go, but each page is enlightening, especially for some one like myself that’s has a primary focus on backend work and unit testing. I’d definitely recommend this book to anyone looking to get into testing their frontends – it’s a great resource and can probably teach you a thing or two.

I’ll try to put up another post when I get closer to the end – it’s hard to find time to sit and read these days, but just little nibbles at a time work just fine.

Speaking at CodeWorks 2010 : Austin

Since Marco Tabini won’t be able to make it to the CodeWorks Austin spot this year, Keith Casey asked me if I could fill his spot and give his talk on working with the object oriented features that the PHP 5.3.x series has to offer. Here’s his summary:

With version 5.3, PHP has finally acquired a well-rounded object-orientation model that rivals – and in many way exceed – those of most other languages, while maintaining PHP’s trademark simplicity and ease of use. In this session, Marco will explore the new OOP features in 5.3 and show you how they can improve your coding.

There’s other great talks coming along with the tour that’ll fill you in on things like unit testing strategies, building effective APIs and scalability. If you haven’t picked up your ticket for the Austin stop and want to join us on November 13th (a Saturday), you can still grab a ticket. Full admission for the day packed full of great sessions and community interaction is $100 USD and, if you’d like to purchase a ticket for the Day Camp 4 Developers event, it’s only another $10 USD on top of that!

Come on down (over/up/above?) and join us for this <a href="great day-long event!

API Testing with Frisk (and Joind.in!)

Two great tastes taste great together, right? As I’ve been working more on Frisk in my spare time (yes, there’s a little in there between PHPDeveloper.org and Joind.in) I’ve been trying to develop features for it that would be helpful not only for testing web site interaction, but also in working with other kinds of web-based interfaces. Naturally, my thoughts wandered over to the Joind.in API and how I could use Frisk to work with and test the responses it gives.

I’ve added a few more handy things lately – like matching values inside of JSON objects and different output options – but one of the latest things is an improvement to the POST and GET handlers to allow for more verbose options on requests. This comes in handy when we want to test something a bit more technical than just your average web site.

First, if you just want to check out the test, here’s the code in a handy .phps file. It’s the sample test I’ll be describing.

[php]
public function testSiteStatus()
{
// This is our object to send
$postData = json_encode(array(
‘request’=>array(‘action’=>array(
‘type’=>’status’,’data’=>array(
‘test_string’=>’my test’))
)));

// This is what the object that comes back should look like
$response = json_encode(array(
‘dt’=>date(‘r’),’test_string’=>’my test’
));

// Build the settings for the connection
$settings=array(
‘location’ => ‘/api/site’,
‘host’ => ‘ji-enygma.localhost’,
‘postData’ => $postData,
‘outputFormat’ => ‘json’,
‘headers’ => array(
‘Content-Type’=>’text/json’
)
);

// Make the request and check the response!
$this->post($settings)
->assertEquals($response);
}
[/php]

The large part of the example test is made up of the “setup” to even make the test happen. In $postData I’ve created a JSON message based on what the Joind.in API is expecting for the Site/Status request and pushed it into a string. The second JSON object, $response, mimics what the API’s response will look like. The $settings array is the more verbose way of specifying settings for the ActionPost request (including the additional headers). The Joind.in API requires that you give it a Content-Type of the message you’re giving it – it’s not a very good guesser.

The next two lines do all of the work – make the post request to the remote API, return the message and check to see if it’s the same as $response. Simple, right?

If you wanted to get a little more fancy with checking, you can use the “paths” in the assertContains to look inside of a JSON object. So, you could do something like:

[php]
<?php

$this->post($settings)
->assertContains(‘look for me’,’message_list/message/message1′);

?>
[/php]

That will look at “message1” in this JSON to see if it contains that “look for me” string:

{“message_list”:{“message”:{“message1″:”I think you should look for me”,”message2″:”but not here”}}}

You can find out more about the Joind.in API and all it has to offer on the Joind.in site and for more information on Frisk, check out it’s project on github.

  • Joind.in API – Interface directly with Community events & feedback
  • Frisk – automated functional unit testing

Test with Frisk!

For a while now, I’ve had a renewed interesting testing applications – unit, functional, performance, etc – and have been learning all I can about the software you can use to run these tests. Obviously, one of the mainstays of the PHP world is PHPUnit for unit testing. There’s a few others out there that are good for other kinds of testing – too many to name (and lots that aren’t written in PHP).

Lately, though, I’ve been looking more at testing the frontend of applications and their flow. I started looking around at the current testing tools and found some I wanted to use, but I wanted more to know how they worked. So, as an exercise, I started on Frisk, a light-weight simple testing framework that has some of the basics of functionally testing, nothing fancy though. Oh, and of course it’s open sourced so you can take a look at the work behind it too.

It’s not a complete testing tool, but it does work. I’ve thrown together a simple example of how I’ve used it to test two things on the Joind.in site – the homepage content and the result of a login:

JoindinTest.phps

When this file is dropped in the “tests” directory and the “frisk” executable is run, it’ll execute these tests and check the results of those requests. The “ji-enygma.localhost” is a reference to my local Joind.in instance. The results are spit back out as a PHP array that reports the results of each part of the test (pass/fail) split out by test function name and action/assert result:

[php]
Start!

=====================
ending status: Array
(
[JoindinTest] => Array (
[testHomepageContent] => Array (
[ActionGet] => Array (
[0] => pass
[1] =>
)
[AssertContains] => Array (
[0] => pass
[1] =>
)
)
[testValidLogin] => Array (
[ActionGet] => Array (
[0] => pass
[1] =>
)
[ActionSubmitform] => Array (
[0] => pass
[1] =>
)
[AssertContains] => Array (
[0] => fail
[1] => AssertContains: Term not found
)
)
)
)
[/php]

The project is hosted on Github so you can grab the source, fork it and play with the assertions and actions (or helpers!) and check out the project wiki for complete details on what the project has to offer.

New @ Joind.in – Widgets!

With the latest site release over on Joind.in, we’ve added something a bit more fun for users of the site – handy little widgets that let you embed information from the site into yours. You can see an example of it if you look to the right (well, if you’re looking at the site not the feed, of course).

The widgets currently let you do a few things with a few different bits of information:

  • talks
  • events
  • and users

Each of the widgets comes in different sizes (some are still in the works) and right now you can use a small and large template for the talks, a large template for the events and a large template for the user information. The example I’ve put here on the site is a user widget that lists the talks I’ve claimed on the Joind.in site and the ratings they’ve been given. Here’s how I called it:

[php]

joindin.display_user_large(1);
[/php]

Pretty easy, huh? Well, you can find out more about the widgets on the Joind.in site here: http://joind.in/about/widget

For those interested in how it all works, I’m working on a post detailing each of the pieces. If you’d like to look more into the templating used, check out mustache (javascript).

If you haven’t heard of Joind.in and are involved in events (or speaking) at all, you should check it out! The site lets you give and get real-time feedback on presentations!

Speaking at Dallas TechFest 2010 – Building a Web Service API

Just a heads up for all of those in the Dallas/Ft. Worth area – there’s a great one-day event coming up this Friday (July 31st) blending PHP, .NET, Java, new media, Joomla and WordPress into one packed day of sessions – Dallas TechFest 2010 at the University of Texas at Dallas.

I’ll be giving a session called “Building a Web Service API” from 10:30 – 11:45am in the PHP track. Here’s a summary of the session:

When is a web application more than just a web application? Hook up an API and you’ll see! I’ll walk you through the basics of what an API is and the concepts behind it as well as key pieces of technology you can use to create both the client and server. There’s a focus on PHP but other languages and tools will be touched on as well.

There’s still time to register for the event – tickets can be purchased for an early bird price (ending today) of $50 or $60 at the door. You can see the full list of sessions here.

Joind.in Articles – Import & WordPress

I’ve been slacking a bit and haven’t posted these two articles/tutorials written up by Lorna Mitchell about using the Joind.in site in two different ways – importing your event’s information in and a handy WordPress plugin she’s whipped up to show some of the latest information from the site’s API.

  • Importing Data into Joind.in
    “As a conference organiser I work extensively with the site joind.in, which allows attendees to comment on sessions at a conference. Recently the site has also started supporting sessions with both times and tracks, making it indispensable as a way of keeping track of all the sessions during an event. The only downside is entering all the data into it!! Joind.in does have some import functionality, which I recently rebuilt to reflect the timings and track changes, however this only accepts XML at present, so there is still some preparation work to get your data ready to import.”
  • WordPres Plugin for Joind.in
    In case anyone thinks I’ve gone joind.in crazy after already writing about its import functionality this week, I really haven’t. Its just that some months of pulling a few things together have finally bourne fruit and so I can actually write about them now they are done! The good news is that this includes a plugin for wordpress, which pulls data from the joind.in website. You can find its official page on the wordpress plugin directory here: http://wordpress.org/extend/plugins/joindin-sidebar-widget/

Many thanks to Lorna for writing these up! It’s always great to see something you’ve worked on be well used by the community that has contributed so much back to it. Want more information on Joind.in and what it has to offer? Check out the About page or send an email to me personally – i’m always happy to answer any questions!

The times, they are a-changin’

Let’s get the exciting part of this post out of the way first – as of today I will be leaving Atmos Energy and will be starting at JWT on Monday the 19th!

I’ve been with Atmos for what seems like forever – this is my eighth year here – and I have grown so much in those years. I’ve come from a developer that barely knew OOP and couldn’t design pattern his way out of a paper bag to someone completely different. If you had asked me back in 2002 if I’d be writing articles, running an open source project and have had a few speaking notches under my belt, I would have thrown an Oracle manual at you (which was all new to me at the time). I’ve learned about best practices, fought my own battles with both code and things more on the human interaction level (I hadn’t worked in a large office before this) and have come a long way as a developer.

Atmos has provided me with an environment to make all of this possible – they’ve been receptive to my requests for training and conferences and for letting me try out new things and technologies. I’ve done things here that I can’t say I’ll so at other companies like write applications to interface directly with gas systems and work with huge customer databases (1.5 million customers over 13 states).

Unfortunately, over the last months I’ve become more and more aware that I’ve grown a bit too comfortable in my current skills. You know how it is – you do the same kinds of things over and over (and over) that you get used to doing that thing and not so much developing the applications you know you could. This is a big reason why I’m making the move. I’ve been doing the “gas applications” for a good while now and I wanted some place where I could stretch back out and really get back into a more real form of development. I think that JWT can offer me that so I’ll be starting there two weeks from today.

Thanks to all of you who have supported me in my job hunt, it definitely means a lot! Oh, and if you know of any good PHP developers (Oracle experience a plus) in the Dallas area looking for a job – let me know. I know recommendations would always be appreciated!

Are You an Olympic Developer?

The Olympics have just started and I can’t help but look at those competing and liken them to the development work so many of us do. What’s the same, you ask? How could an international sporting event of the best of the best possibly connect with the work we do behind our keyboards? It’s simple – it’s all about being the best.

Olympians work most of their lives (if not all of them) trying to become the best at their sport that they can be. Some of the figure skaters have even been paired since they were little kids and know each other’s moves as if they were their own. They have honed their craft down to the point where they know in the first thirty seconds of a routine or race how well it’ll turn out in the end. They know the result because they know themselves. They’ve worked hard to get to where they’re at and they know that to compete on this new level, they’ll have to step things up and do even more than their best.

It’s easy to see how this relates to us, the software developers (or managers of these developers) all over the world. There’s no excuse for you to not look at things on a more global scale and try to be the best you can possibly be. Sitting in your chair and being comfortable in the knowledge you learned five years ago isn’t enough. Don’t lull yourself into thinking that, just because you know your current codebase, you’ve done all you can. Get out there, look at what other developers are doing and hone those skills. There’s tricks that you can learn from the best and tools that you can use to hone your own development work into a razor sharp edge that can cut through any problem and push you up into that next level of development.

Who knows…you might just find something you can apply that could make you and your development soar to new heights and help you feel the rush that you did when you were first learning a language – flying headfirst into the unknown, unsure about what was to come and where you might land.

Don’t be afraid. Take the risks. Become the best you can be.