Monthly Archives: December 2012

My Introduction to the Laravel PHP framework

Disclaimer: I don’t claim to be a framework expert. In fact, I’ve only used 3 to any real degree – Codeigniter(PHP), CFWheels(CF), and now Laravel(PHP). Actually, to be even more precise, I’m not an expert at anything.

I’ve written a lot of bad code. All developers have. It still bugs me when I look at some of the old stuff. For some developers like myself, MVC frameworks are there to help us from writing really, really bad code. Even for very small web apps, I find myself benefiting from the structure provided by a framework. So choosing a new framework, especially when you are jumping in to a different programming language (PHP), is kind of a big deal.

Laravel - A Clean & Classy PHP Framework

I’ve dabbled in PHP a little over the years, and have used Codeigniter for a couple of small projects. So when I decided to move to PHP, Codeigniter seemed like the logical candidate for a framework: I’d used it before, it’s well-supported, well-documented, and has a large community. But I kept hearing about another framework called Laravel (version as of this writing: 3.2.12). It also appeared to be well-supported and well-documented, and the size of the community, though dwarfed by Codeigniter, appears to be growing fast.

What really struck me about Laravel is there are a lot of passionate developers out there who insist this is THE way PHP must and will move forward (PHP 5.3+ (namespacing, etc.), modular libraries, and a lot of stuff I really don’t understand yet. And since I’m apparently very impressionable, I decided I should give it a go.

I’m not going to go into detail regarding the installation of Laravel, folder structure, or even what it takes to build a simple CRUD application (except maybe for Eloquent) because, frankly, anyone with a computer, an internet connection, and who can read should be able to do that with just about any popular framework with a little time and effort. Instead, I’ll focus on what has stood out to me so far in the few weeks I’ve been using Laravel.

Routes

Both Codeigniter and CFWheels use “implicit” routing. Create a controller and a controller action (i.e., “/users/create”) and you can route to it with any extra configuration. Laravel uses “explicit” routing (though you can make routes implicit by using

Route::controller(Controller::detect());

in the routes.php file, but I’ve read that’s a bad idea for some reason).

This seems like extra work, and it is. But the benefits are worth it. Not only do I see a summary of my entire application in one place, I can group routes for use with filters and even declare entire controllers instead of individual controller actions when it makes sense (see below).

//Home
Route::get('/','[email protected]');

//Auth
Route::post('login','[email protected]');
Route::get('logout', array('as' => 'logout', 'uses' => '[email protected]'));

Route::group(array('before' => 'auth'), function()
{
        Route::controller(array(
                'chores',
                'users'
                ));
});

Another thing I like about Laravel routes is that I can create a route, write some code, and then return something without having to write a controller action at all. This is great for running little tests. You could even call your views here and put the entire application in routes.php if you really wanted.

Route::get('test', function()
{
return eloquent_to_json(Chore::get());
});

Artisan

One of the advantages of PHP is the ability to run php scripts from the command line. Laravel has something called Artisan that comes with its own commands, as well as user-created scripts called “tasks” that can take advantage of Laravel’s ecosystem (Eloquent, etc.).

I’ve primarily used Artisan for running Migrations. Migrations are one of those development practices that I never really saw the value of. It just seemed easier for me to create and update the db schema via a MySQL client like Sequel Pro. However, I thought I’d give them a try with Laravel and I’ve discovered a couple of scenarios already where Migrations have proven to be very helpful (though I’m not sure if either one was an intended benefit):

  1. Early on in a web dev project, I find my self wanting to just wipe the data in the db without losing the schema itself. One way to do this is to make structure-only backups each time you update the schema which would be a hassle. With laravel migrations, I can just run “php artisan migrate:reset”, then run “php artisan migrate” to recreate the schema. If you need to always have a user to log into your app with, include that user record insert as one of your migrations.
  2. When you deploy an app, either the first time or for subsequent updates, you can run “php artisan migrate” on the remote server and ensure that the db environments are in sync (in terms of the schema). You can even add the migrate command to a git hook or something like Pagodabox’s Boxfile (more info.) to further automate the process.

Eloquent

Eloquent is Laravel’s ORM. It reminds me a lot of the only other ORM I’ve used in CFWheels.

Basically, you can do this (and much more):

$users = User::with('role','group')->get();

Instead of something like this (using laravels Fluent query builder):

$users = DB::table('users')
->left_join('roles','users.role_id','=','roles.id')
->left_join('groups','users.group_id','=','teams.id')
->get(array('users.*','roles.name AS role_name','teams.name AS team_name'));

All you have to do is create the model files for each table, and within those files, set up the relationships (one-to-one, one-to-many, etc.) between the tables.


This is really only scratching the surface of what makes laravel so attractive, and it will only get better with laravel 4. Hopefully, more and more developers will give it a look so that the community will keep getting stronger.

Setting up Laravel 4 via Tutsplus

I’m planning on writing up a post about the Laravel framework and why I’ve chosen it for my new foray into PHP and away from Coldfusion.
In the meantime, Tutsplus and Jeffery Way have put together a nice tutorial for setting up Laravel 4, the yet-to-be-released next version of the PHP framework that’s really getting a lot of buzz lately.
I also highly recommend the Laravel Essentials course by Tutsplus, also by Jeffrey Way, as well as the tutorial series by Shawn McCool at Laravel.io.

Why I’m moving from Coldfusion to PHP

People have spent a lot of time both predicting the death of Coldfusion, as well as refuting that assertion. Of course, it’s not really “dying”. It’s still very popular in government and higher education (I don’t have any stats to back this up, but this is what I’ve observed). Everywhere else, however, it’s market share appears to be small compared to PHP, Rails, etc. I blame Macromedia/Adobe for not providing a free, open-source version and for not marketing it sufficiently. Railo has filled the open-source hole, but it’s too little, too late.

It doesn’t matter that Coldfusion is a great tool for Getting Things Done. New developers are going to be drawn to languages with thriving frameworks (yes, CF has frameworks. I like CFWheels. There just aren’t many under active development and a lot of CF developers still don’t use them), low cost entry, and unlimited hosting choices. Old developers see that fewer new opportunities include Coldfusion as the solution in spite of its strengths. So you have to be able to adapt.

I can’t go into great detail in comparing Coldfusion to [your language here] because I’m a self-described hack. If you want that, you can check out this blog post and comments. Frankly, I don’t build apps large enough that would really expose the weaknesses and strengths of CF, PHP, etc. I do know that I can do cool things with very little code in CF and the PHP learning curve is slowing me down for now. But it doesn’t matter any way. What matters is career survival and future opportunities.

Why PHP?

Everything above that I described as a negative about Coldfusion is just the opposite with PHP. Tons of active frameworks, supported by just about every web host, unlimited opportunities, low-cost entry, etc. etc.

It’s really reached a new level of maturity with 5.3+ and frameworks like Laravel promise to bring some of that Rails developer-love back to PHP. I’ll do another post later about Laravel from a hack’s point of view, but I’ve already discovered the power of command-line PHP using Laravel’s Tasks and Artisan. I can see the value of Composer while playing with the Laravel 4 alpha. I can see the value of being able to publish an app on infinitely more web hosts than is possible with CF.

So basically, Coldfusion, it’s not you, it’s me.

MAMP PRO, CF10, and OS X Mountain Lion

In my last post, I professed my love like for using MAMP over the built-in/download/make/make test/make install/scratch eyes out method of setting up a web dev environment on OS X. I felt so good about it, I decided to get “work” to purchase MAMP PRO to take it to another level. Frankly, I’m not so sure it’s worth it, but running MAMP on port 80 without having to enter my password every time is nice.
In order to upgrade, I kept my vhosts file for my current MAMP install for safekeeping and then uninstalled MAMP since it was an older version. Then I installed the new version, set up my first vhost (a PHP Laravel project) and everything worked. MAMP PRO likes to set up virtualhosts using Server Names instead of Ports, though ports are an option. It even edits your hosts file for you so the names resolve properly. Nice.
Next it was time to hook up MAMP PRO to Coldfusion 10. This was a pain in the ass, but I’ll just go thru the final steps in case anyone is in the same boat. I ended up doing a fresh install of CF10 after having no luck with just running wsconfig on the existing install.

Here’s the deal:

MAMP PRO uses it’s own dynamically created httpd.conf file based on the settings you provide in the GUI. And it also provides “templates” that are used as the base for httpd.conf, as well as the PHP and MySQL config files. To connect CF10 to MAMP PRO using the web server connector utility during the CF10 install, first point the httpd.conf file that MAMP PRO is currently using (dynamically created from it’s template).
This httpd.conf file is located at /Users/[username]/Library/Application Support/appsolute/MAMP PRO/httpd.conf
After pointing to that file, click on Advanced and point to /Applications/MAMP/bin/apache2/bin/apachectl and /Applications/MAMP/bin/apache2/bin/httpd where required.

This is all pretty much standard stuff when connecting Apache and CF10 except for the location of httpd.conf
The trick is that once the CF10 web server connector (wsconfig) is done and has made changes to httpd.conf, you need to open the file, go to the bottom and copy the line that looks like this:

Include “/Users/[username]/Library/Application Support/appsolute/MAMP PRO/mod_jk.conf”

Now go into MAMP PRO and click on File | Edit Template | Apache | httpd.conf

Paste the line above to the bottom of that file. And then go find this line:

DirectoryIndex index.html index.php

and change it to

DirectoryIndex index.cfm index.html index.php

Now whenever MAMP PRO restarts and recreates the httpd.conf file, the CF10 stuff will be there since it’s now part of the base template.
The only problem I had left to deal with is that MAMP PRO started telling me that the built-in Apache was running and creating a port conflict. I kept killing the httpd process that showed up in the Activity Monitor, but it kept coming back. I finally noticed that MAMP PRO has a Tools menu with an for stopping the built-in Apache. Somehow, it was able to do what I couldn’t.

Moving from MAMP to OS X’s built-in apache, etc. Not fun.

So I just got my 5-year old Macbook Pro back from Apple* after it sat dead for several months (my kid killed it playing Minecraft). I decided I needed it for do some web work in the family room while pretending to watch the Real Lives of Whatever with the family.

I have the impression that real, tough guy developers don’t sissy their way into a local dev environment using MAMP. You gotta use the built-in version of Apache, and download, make, make test, make install, etc. etc. everything else. So that’s what I did.

The Apache part is easy because it’s already there. So is PHP (5.3.15 for Mountain Lion I think). However, it doesn’t include mcrypt, which is required for Laravel. To get that working, just follow the 20 or so steps here, which including getting the latest version of Xcode. Fun.

MySQL was fairly easy if you choose the package installer (sissy) over compiling it yourself (tough guy).

Once it’s finally working, you feel good about yourself, then realize that the mysql ports are different for the dev machines that are still using MAMP and share the same code, PHP CLI isn’t in your path, you don’t know how to switch between PHP 5.2/5.3 if you need to (easy with MAMP), etc.

So in the end, I just went back to using MAMP.

The End.

*Apple has a nice deal where they fill fix anything and everything for $310.