Upgrading PHPUnit on (X)Ubuntu

When I recently installed Xubuntu 13.04 and added PHPUnit, apt-get installed version 3.6. This is not unusual; the repository is usually running an older version. I happened across this article on upgrading to a newer version and am posting it here (link to original article is at the bottom). All commands should be run via command line, of course:

sudo apt-get install phpunit
sudo pear channel-discover pear.phpunit.de
sudo pear channel-discover components.ez.no
sudo pear channel-discover pear.symfony-project.com
sudo pear upgrade
sudo pear upgrade phpunit/PHPUnit

This upgraded my installation from 3.6.x to 3.7.24 (as of this writing)

Source: http://konradpodgorski.com/blog/213/how-to-install-phpunit-on-ubuntu-11-10-and-get-it-to-work/

Your Perfect PHP Framework

With “Framework X rocks” and “Framework Y is the future of PHP” still being tossed around it’s ok to remember that the perfect framework for you is…

the framework *you* are most comfortable with and can code most quickly in. Whether it’s Yii, CakePHP, Litihum, Symfony, Laravel, Kohana, or CodeIgniter, find the one that “just fits” (and believe me, you’ll know which one works best for you) and get coding!

Note: There *is* something to be said for choosing the right tool for the job, and that is also a consideration (you probably wouldn’t use Slim to code an enterprise level intranet system, for example). Just don’t choose a framework only because it’s the newest thing, or the best known thing, or the flashiest thing.

Composer, Laravel, PHP-FIG, oh my!

It’s safe to say that my “Comparing Laravel, CodeIgniter, and Cakephp” post is the most popular entry this blog gets! I’m very glad that so many people have found it informative and relatively unbiased as they look for a “toolbox” to help them build their apps.

The downside is that it was written 9 months ago – which, in the world of programming/technology, can make a lot of difference! Since I wrote the original post we’ve seen Composer take off, PHP-FIG becoming more widely adopted, and Laravel being the “it” framework in anticipation of version 4. Because I have no desire to pit framework against framework again, let’s look at these three things :)

Composer

Composer allows you to add packages to your application by adding a line to a (composer.)json file and running a simple command via command line. I was very leery of it at first but I’ve grown quite fond of it. Being able to update a Markdown or Swiftmailer package by opening my terminal and typing “composer update” is fantastic. Definitely beats the pants off trying to keep up on version number, downloading, extracting, hoping I didn’t miss something critical. The fact that it also snags the dependencies your package will need is pretty nice, too.

The only caveat I’ve found is that you do need to be aware of the dependencies, as it can quickly fill up your vendor folder with a lot of files that only that one package might use. Disk space is certainly cheap, and the number of files you use shouldn’t really matter, but it’s still a form of bloat, and could easily get out of hand — like, “Why do I have 310 folders…oh, that’s for the XYZ package”.

PHP-FIG

PHP-FIG is a group of leading PHP devs who are striving to help our code become more consistent, more interchangeable  and thus easier to read and easier for programmers to use. They have (at the time of this writing) 4 standards for coding – Autoloading, Basic Coding, Coding Style, and Logger Interface.

Many devs are up in arms that someone is “trying to tell me how many spaces to use”, that “Why can’t I use tabs?”, and “No one tells me how to code!”

Personally, I think the things laid out in each standard make sense insofar as creating smooth, consistent code readability. I don’t necessarily think that using snake_case instead of camelCase for function names really matters as long as you can figure out what the code is doing, but as far as the tabs thing goes – seriously, I forgot I was using spaces instead of tabs by the end of the first day. It’s extremely annoying to open a file from someone else and not be able to read it because their tabs are set at 5.5 and the code is all over the place.

So, I feel that we should put on our big girl/boy pants and just try to work together so we can ALL succeed.

Laravel 4

To say that Laravel 4 is on fire in the PHP world is an understatement. It hasn’t even reached stable release yet and has already been nominated for “Open Source Project of the Year” at the .net Awards. That’s an accomplishment! I’ve gone through and played with the L4 code and I both am and am not impressed.

The fact that it has been broken into multiple components and those bits can, theoretically, be used independently of the framework itself  is fantastic. The Support and Database packages are perfect examples of this, and I use both in various projects. Being able to swap other packages — for example, Cartalyst’s Sentry package — is also great. It’s interesting to see, too, how they have managed to create a way for non-static classes to be used statically (via the Facade pattern), maintaining testability while allowing easy access to often used classes (like Config, Lang, etc). That said -

L4 is not quite as decoupled as it might seem; for example, to use the Pagination package you need the Http, Support, and View packages as well as the Symfony Http-Foundation and Translation packages. That’s an awful lot of code for something that should be pretty simple, and doesn’t really lend itself to easily using it outside L4.

I also found it difficult to wade through the code to find out how something worked. For example, I wanted to have a dynamic action key in a route – something like

Route::get('foo/{wut}', 'Controller@{dynamic}')->where('wut', '(add|edit)')->where('dynamic', '(add|edit)');

It took me almost an hour to work out how L4 was setting up routes to realize that this was not going to work. I’m okay with it not working, I’m not okay with it taking me that long to follow the trail.

Other, nit-picky things – I don’t care for the huge App container that is passed around; it doesn’t feel much better than using global $app; or Class::$global or $this->ci->someclass, and makes it difficult when trying to debug one class (if that class has the App instance passed to it). For the majority of the projects I’ve worked on lately, L4 feels huge and like too much.

All this is not to say that L4 is bad or not “newbie” friendly. If you just need a solid base to get you started, L4 is fantastic and can get you going quite fast. Package development is not very difficult either and lets you add to what’s already there.

As always, use what works best for you and your specific project. I would certainly not use L4 for a simple website for the local ice cream parlor, but I might consider it for a local school’s community site for their sports program.

Please note I speak as someone who has programmed at least part-time since 2003 and used a framework since 2006, which is to say I’m by no means an expert but I have worked with a fair amount of code. These are simply my opinions on what I’ve experienced with my usage, and your own mileage may vary.

“Illuminating Your Laravel 3 Application”

“Illuminating Your Laravel 3 Application”

Cool article giving a brief overview of some of the changes/upgrades to Laravel 4

http://www.slideshare.net/aaronsaray/enterprise-php-mappers-models-and-services

http://www.slideshare.net/aaronsaray/enterprise-php-mappers-models-and-services

Great read-through for getting a handle on separating out concerns.

[Quick Tip] Add Composer Dependency Manager Support To Kohana

Composer is a super cool way to manage dependencies for your applications. Kohana’s autoloader does not support Composer’s way of autoloading, so if you’re wanting to use composer packages in your application you’re going to run into issues.

However, it’s really really simple to add support. Simply open your application/bootstrap.php file, and (I added this after Kohana registered its autoloader) add

require [FULL_PATH_TO_COMPOSER_FOLDER].’autoload.php’;

Where, of course, [FULL_PATH_TO_COMPOSER_FOLDER] is the actual absolute path to Composer’s auto-generated auto-loader files.

Voila! You should now have Composer support in your Kohana app! :)

[Laravel] Quick Tip: Saving Related Models with Eloquent

Recently, I encountered some difficulty in saving related models with Eloquent ORM.  I spent quite a bit of time trying to figure out why in one area of my app it saved with no problem but in another, it wouldn’t save the key/val pairs I passed to it.

Finally, (by a bit of trial and error) I realized that the call I was making to Model::accessible (a type of security feature that allows you to specify the accessible fields in a model) was, for some reason, preventing the related models from insert/updating. Once I commented that out it worked like a charm. (Note: I did go back and manually specify the fields the model should insert/update to avoid potential security problems with mass assignment).

Comparing Laravel, CodeIgniter, & CakePHP

Today I received a comment on my Laravel Auto-Generating Named Routes post that I felt deserved its own post.

Matthew Schenker wrote I see you’ve worked with CakePHP and CodeIgniter, and now you’re mentioning Laravel. I’ve been happily using CodeIgniter for a while now, but lately I see a lot of people mentioning (and loving) Laravel. I’m not looking for one of those “which is best” answers. Long ago, I learned that this is not a good way to look at various frameworks. But I’m curious — what are your general impressions when comparing these three frameworks?

CakePHP, CodeIgniter, and Laravel are all great frameworks in their own rights. They each have their pros and cons which I will cover here. Bear in mind that these are my opinions and forming your own by messing a bit with them is always the best policy. And as mentioned in Matthew’s comment, this is not an “OMG FRAMEWORK X IS TEH BESTEST!!!1!” post.

CakePHP
Cake, if I recall correctly, was one of the first PHP frameworks around back when spaghetti code was standard. The idea behind Cake was to make developing applications fast (ie, “convention over configuration”) by cutting down on how much code the developer needed to write. Less time working means more time making money.

Pros

  • Built-in ORM which I’ve always really enjoyed. I really like how the results are in $post['Post']['field'] format. Building queries is really simple and you can fetch (for example) a blog post and all of its comments in one or two lines of code.
  • Reverse routing. This makes maintaining links in an application so much easier. This means if you change a controller’s name at some point, instead of search/replacing 200 instances of “admin/foo” with the new “admin/bar” (and hoping you didn’t miss one) you simply update the route in one place. Any links using the reverse route array will automatically point to the right spot at runtime.
  • Big community. Because Cake had been around so long you can find the answer for pretty much any question you come up with. If you can’t? They have their own website where you can submit questions, as well as (I believe) a mailing list.
  • Plugins. This makes re-using code super simple and help keep the app folder clean (if, for example, you are distributing an app that uses modules).

Cons

  • Incredibly slow. Recent versions of Cake (2.2.x as of this post) are much faster and more efficient than previous versions, but  it is still one of the slowest frameworks. I am personally not sure how well it holds up when an app of it gets slammed with tons of hits. I am aware that Mozilla’s plugin site runs on an (old) version of Cake, as does Cake’s own bakery and Q&A sites, which all seem to run fine. I suspect it’s a balance between caching and server fine-tuning.
  • TONS of lines of code. Some developers don’t care what’s going on under the hood; I like to be able to quickly find out how/why something works the way it does. The code is well documented but there’s just so much of it it can be overwhelming.
  • Occasionally, you need to use code to reign in just how much it does. For example, my first step is to open my AppModel and set $recursive = -1 and adding Containable to Behaviors to prevent it from auto-grabbing related models and letting me tell it what I need.
  • Autoloading can be awkward. In recent versions of Cake they’ve introduced lazy loading in the form of  App::uses. Then, if you need to have access to (for example) the Model class, you do something like App::users(‘Model’, ‘Data/Model’) at the top of the file. This is, IMO, clumsy and no better than doing a require CORE_PATH.’Data/Model/Model.php’;

Conclusion: Personally, I use Cake if I need to put together a dynamic site quickly that I don’t foresee getting a lot of hits (like for a local restaurant, for example).

CodeIgniter
I’ve mentioned on here before that CI was the first framework I ever used and helped me finally understand the concept of OO programming. It’s certainly popular, and has been around a similar amount of time as Cake.

Pros

  • Super easy to set up and use. This makes the entry level for a newer PHP developer much lower.
  • Extremely well-documented, with examples in a lot of places to illustrate usage.
  • Extremely fast.
  • Huge community. As with Cake, since CI has been around so long you can almost always find your answer via Google, CI forums, or their IRC channel. This also means there’s lots of code contribution to help get things done (like Paypal libraries, etc)
  • Sparks, the “hub” where CI packages go to hang out and be used.

Cons

  • No modular separation by default. This is a big deal for me as I prefer keeping my code as separated as possible. There is Modular Extensions, which does the job, but I’ve never been 100% satisfied with it.
  • Since 2.x broke CI has been 5.1.6+ for its minimum PHP version, but the whole $this->library, procedural function helpers, and extending a class by prefixing MY_ in front of it way of doing things just doesn’t work well for me. Perhaps this will change in 3.0? *shrugs*
  • I personally have to extend way too many core files to get CI working the way I like it. The more you modify the core, the more you have to maintain later. I’d rather be coding something productive.

Conclusion: CodeIgniter is a fantastic framework for getting the hang of PHP and OO coding and for knocking a small site together fairly quickly with low overhead.

Laravel
Laravel is still in its early days compared to the “grandpas” of the framework world (I believe it was first introduced in 2011), but it has already gathered quite a following.

Pros

  • Modularity is built in via “bundles”, making it really easy to drop in/reuse code across application
  • Eloquent ORM is a simple, super fast ORM that makes working with database relations easy
  • Very configurable and extendable. I can set up apps with the folder structure the way I like it and how it works best for me.
  • Blade template engine. Very fast (compiles to PHP then caches the results) and very extendable. So easy to add new features without hacking the core.
  • Artisan (CLI). Before I started using Laravel I had zero use for CLI tools like migrations and tasks. It’s so easy to create both of those things with Artisan that I can’t believe I waited so long to try it out!
  • Reverse routing!
  • Excellent documentation.

Cons

  • It’s still quite new which can mean some instability with the code. However, since 3.x’s release (and certainly since 3.2.x’s, the most current as of this post) this has slowed down quite a bit.
  • Laravel’s core files are all within (at least) the Laravel namespace and not all of the files in core use a namespace slash ( a \ ) in front of a call to another core file, which makes extending some classes a bit trickier. This is not a huge issue and one not every developer will need to worry about.
  • Routing can feel a little odd sometimes. In my dynamic controller routing post I showed the workaround I used to dynamically route to an add function in any controller. I have not dug deep enough into the semantics of Laravel’s routing methods to understand why such a workaround is necessary but it does add another layer of complexity, IMO.
  • Because of its newness the options for finding answers are still limited in comparison to CakePHP and CodeIgniter. However, the forums and IRC seem to be quite active with helpful people, so usually the answer is findable.

Conclusion: Laravel is currently my framework of choice. Its coding style meshes the best with my own which makes developing much quicker for me.

So there you have it! A personal comparison of 3 big players in the PHP framework world. As always, the best framework for you is the one that you code best in. The “Cons” foreach ;) framework are my personal beefs with each of them and should be taken with a grain of salt. The best advice I can give is to try them each on for size and see which you like best.

(CakePHP) Get a Database Connection Instance

In my current project I am working on, I am using CakePHP and need to fetch some data from the database very early in the request cycle (don’t worry; it’s cached to avoid unnecessary queries).

In past versions of Cake you could use ConnectionManager::getInstance(). However, in 2.2 (and possibly in earlier versions of 2.x; I do not have the time to check), this no longer works.

The solution is to use the getDataSource method. So, by calling ConnectionManager::getDataSource('default') I can retrieve an instance of the default database connection and go along my day. Yay!

UPDATED (Laravel) Auto Generate Named Routes For Easy Reverse Routing

UPDATED: It occured to me that having the route names match the controller name might not lend itself well to preventing the need to update multiple places in the event of a controller’s name changing. I have updated this post with a better method to tackle that.

What *Is* Reverse Routing?
Reverse routing is an awesome feature. In Laravel (as well as other frameworks) when you create a route you can also define a name for it. Then, when you need to generate a link in your app, instead of doing your standard

<a href="/blah/bler/blo">Link</a>

You can do this:

<a href="<?php echo URL::to_route('some_route', array('bler', 'blo')); ?>">Link</a>

The difference, you ask? Let’s say later you decide to rename the Blah controller to Clover. You’d have to go through your entire app and replace any links starting with “blah” with “clover”.

With reverse routing, you’d make exactly one replacement: in the routes.php file. Any links in your app using the second example will automatically go to the clover controller. Yay!

So How Do I Do The Magic?

As you can tell, I very much like using reverse routing. However, I realized that Laravel does not automatically generate names for the routes created by Route/r::controller (which is not a critical flaw; not everyone has the need for it, and that’s fine). After a bit of digging and head-scratching I came up with a fairly easy way to have it do the work of naming all routes for me.

NOTE: This requires manually setting your controller names instead of using Controller::detect() (probably not a bad idea anyway since it’s less file lookups for Laravel to do)

1. Open routes.php and list the controllers for the bundle. If you want to specify a name, do a key => val pair. Example:
Route::controller(array(
// This will set the admin/home controller as a route named foo
'foo' => 'admin.home',
// This will be a route called users, since we did not set a name
'users'
));

2. Create 2 files in your application folder. I placed mine in application/libraries. route.php and router.php.

3. Open up router.php and put the following into it:

<?php

class Router extends Laravel\Routing\Router {

/**
* Register a controller with the router.
*
* @param string|array $controller
* @param string|array $defaults
* @param bool $https
* @return void
*/
public static function controller($controllers, $defaults = 'index', $https = null)
{
foreach ((array) $controllers as $as => $identifier)
{
list($bundle, $controller) = Bundle::parse($identifier);

// First we need to replace the dots with slashes in thte controller name
// so that it is in directory format. The dots allow the developer to use
// a cleaner syntax when specifying the controller. We will also grab the
// root URI for the controller's bundle.

///// Here is where the named route will be set. If the $as variable is numeric,
//// we will use the controller name
(is_numeric($as)) and $as = $controller;
$controller = str_replace('.', '/', $controller);
$root = Bundle::option($bundle, 'handles');

// If the controller is a "home" controller, we'll need to also build a
// index method route for the controller. We'll remove "home" from the
// route root and setup a route to point to the index method.
if (ends_with($controller, 'home'))
{
static::root($identifier, $controller, $root);
}

// The number of method arguments allowed for a controller is set by a
// "segments" constant on this class which allows for the developer to
// increase or decrease the limit on method arguments.
$wildcards = static::repeat('(:any?)', static::$segments);

// Once we have the path and root URI we can build a simple route for
// the controller that should handle a conventional controller route
// setup of controller/method/segment/segment, etc.
$pattern = trim("{$root}/{$controller}/{$wildcards}", '/');

// Finally we can build the "uses" clause and the attributes for the
// controller route and register it with the router with a wildcard
// method so it is available on every request method.
$uses = "{$identifier}@(:1)";
///// Just adding the as variable to the compact statement so it'll get set upon register
$attributes = compact('uses', 'defaults', 'https', 'as');

static::register('*', $pattern, $attributes);
}
}

}

Here we are basically adding a couple of lines so the named route (defined by the ‘as’ attribute) will be created for us when Laravel is detecting controllers & generating routes.

4. Open up your route.php file and add the following:

<?php

class Route extends Laravel\Routing\Route {
/**
* Register a controller with the router.
*
* @param string|array $controllers
* @param string|array $defaults
* @return void
*/
public static function controller($controllers, $defaults = 'index')
{
Router::controller($controllers, $defaults);
}

/**
* Register a secure controller with the router.
*
* @param string|array $controllers
* @param string|array $defaults
* @return void
*/
public static function secure_controller($controllers, $defaults = 'index')
{
Router::controller($controllers, $defaults, true);
}
}

The reason we need to extend the route.php file as well is that the default file (found in laravel/routing/route.php) points to laraveroutingrouter, which means our custom router class would never get used. So, we simply override the controller functions and add the handy backslash in front of the Router call so it will look for our router file.

5. Open up application/config/application.php and comment out Route and Router in the aliases section.

You should now be have auto-generated named routes. The best part is that any custom route names you define will not be overridden by this method.

Follow

Get every new post delivered to your Inbox.

Join 127 other followers