I’ve been paying a lot of attention lately to the price of software. Now that everyone and their brother has an ‘app store’, it has shone a bright light on the practice of getting people to pony up money for apps, services, gadgets and games.
I’m a finicky software buyer. I don’t like parting with cash until I’m absolutely sure it’s worth it. So what makes a piece of software worth buying? How much is too much or too little to charge? And what are the deal-breakers when it comes to going from trial download to full license?
Flexible licenses
This is a big one for me. What are the rules for using the software legally, and does it fit my pattern of computer use? For example, my Textmate license is valid on any computer I use, as long as I’m the one using it. This has served me well, as I’ve traveled from job to job over the years.
Adobe CS5 allows me to install one copy on my desktop and one on my laptop. Windows 7 allows for one physical install, and up to four virtual machines. All of this fits with my computing profile.
The Mac App store also allows you sync purchases across computer. Most software these days offers some kind of multi-machine or personal use license, but I always like to check before I buy.
Price vs. Need vs. Interest
Paying 99 cents for software is like buying a candy-bar in the checkout line (actually, cheaper). I don’t need to think about it. If I’m mildly curious about an app, and it’s only a dollar or three, chances are I’ll check it out.
I’ve paid upwards of $10-15 for apps that I’ve used a few times, and left neglected. I regret buying these, and now whenever I consider spending that much on something I’m not sure if I’ll like or not, I’ll typically go without.
Once we’re out of the $20 range, I typically won’t buy anything unless I can use a full-featured trial. I need to make sure this software fits me like a glove before I commit any money.
Once a piece of software gets to be $100 or more, it has to solve a critical problem for me. It has to be something that that I can’t live without.
Upgrades, Support and Annoyance.
I remember buying a copy of Parallels 4 in one of those MacUpdate software bundles. It was a great deal at the time, but my license didn’t allow me to upgrade without shelling out the full price.
That restriction, combined with an obnoxious updater dialog and oodles of email from Parallels asking me to pay for even more upgrades every few months led to me become a happy VMware Fusion user. Each time you nag me, or ask for more money, there’s less chance you’ll ever see another dollar from me.
I don’t like paying for upgrades. If the software is already solving my problem, so what do I need to upgrade for? I even took a while to upgrade from Transmit 3 to Transmit 4 (which is like the best thing ever). If you can include free upgrades, or at least a free year of upgrades with your software, you’ll get an extra point from me.
So What Have I Bought Lately?
So I thought I would feature a few recent purchases, and whether or not I thought they were worth the asking price.
Adobe Creative Suite 5 for $1,500 Verdict: Overpriced.
CS5 is bloated, buggy and hasn’t seen a useful new feature in years, especially when it comes to making web design easier. But it’s the only game in town, which is why designers shell out such a ridiculous amount of money.
Sparrow for $9.99 Verdict: Try it!
There aren’t a lot choices when it comes to desktop mail clients on OS X. I was never a huge fan of Mail.app, so thought I’d give Sparrow a try. After a shaky beginning, I’m a big fan. The Twitterific-esque interface is a big improvement, and it integrates directly with Gmail folders and labels, unlike Mail.app.
OmniFocus for $79.95 Verdict: If you’re into that sort of thing.
After going freelance, I wanted something that could allow me to organize the stuff I had to do. OmniFocus seemed to be favorite among the Mac community, and for good reason. It’s easy to use, extremely flexible and allows deep organization. If you’re a hardcore GTD, task organizing guru, then it’s probably perfect. However at eighty dollars, it’s a bit expensive for a casual user. An alternative like Things or Evernote might be a better fit.
Tower for $59.00 Verdict: Buy it!
Tower is the most comprehensive graphical Git interface I’ve used. Using just the command-line is okay for simple things, but I do like to have a nice graphical view of my diffs, checkboxes for files to commit and a one-click ‘append to previous commit’ option. I had been using GitX with some success for a while, but was extremely impressed by Tower.
iA Writer for Mac for $17.99 Verdict: Buy it!
I’d heard a lot about iA Writer for iPad, but being iPad-less, could never try it. Having been a happy WriteRoom user I wasn’t sure how much it brought to the table, and if it would really be worth the price. I was totally wrong. With it’s gorgeous full-screen mode, brilliant looking font, and smart, but not too clever Markdown integration, it’s a pitch-perfect app for anyone who just wants to site and write.
What About Web Services?
This post was mostly about desktop software, but there are a number of web services I use personally and professionally and highly recommend. Many have free plans, but I’ll only mention them if I’m using the paid service:
I started my career in web development as a front-end guy, writing an incredible amount of HTML and CSS day in and day out. Now a number of years later, I find myself getting back on that horse, tackling the thorny issues of website layout as a consultant.
I never really stopped doing front-end work, but while I was out sharpening my other programming skills, there were some new developments that I quickly had to acquaint myself with:
Three (or four, depending on your support level) concurrent versions of Internet Explorer
HTML5 and CSS3 support in what are now commonly used browsers
A sudden emergence of mobile browsers
The philosophy of responsive design
The funny thing about front-end development is that I’ve never found it to be particularly difficult in the sense that it requires a great deal of abstract thinking or problem solving skills, but it does however require enormous amounts of detail work. The process of writing application on the back-end is so complex, we’ve developed incredibly mature tools to let us split the logic up into pieces and modules so we can focus on one problem at a time. But when writing HTML and CSS, we’re typically forced to work on everything at once, and keep the entire layout system in our heads. Websites have only gotten more complex, and trying to keep track of a thousand different elements, their children, class and ID names, etc can be an exhausting mental tax.
Front-end developers historically haven’t had the same set of sophisticated tools that their back-end brethren have been using for decades. When putting together a comprehensive set of website templates, we’re typically faced with the same problems again and again:
Long, poorly organized files.
I know most people have a system, but is there any real good rule of thumb for organizing a CSS file? Alphabetically? By order of element appearance? By display module? Split it up into text and block styles? How do you organize descendant selectors, overrides or shared classes? It’s not easy, and I always find myself simply falling back on my text-editors find command to get where I need to be.
Code repetition.
Lots of it, especially when writing static HTML. Creating a dozen site templates? That means pasting the site header and footer a dozen times. Have fun updating each one when making a small change to HTML. If you’re smart, you’ve been concatenating files together with PHP. But what about 2-step layout or partial rendering? Wouldn’t that be nice?
Really complicated defaults.
How long does it take you to zero-out your browser styles so you can start writing actual site code? Are you taking HTML5 elements into account now? Did you remember to add all your meta tags, set the charset=utf8, force the latest IE rendering engine, and import that latest version of jQuery from Google’s CDN?
Or do you just do what I typically do and open up the last project you worked on to copy and past all that into the new file?
Complete lack of programmatic logic.
If it wasn’t for javascript, I’d lose any sense of what real programming was like when writing front-end code. Admit it, CSS is a pretty boring language to work in. And how often do you find yourself going back to photoshop, or scrolling to the top of your document to get the hex value of a color? Do you see the words Arial, Helvetica, sans-serif float by when you close your eyes?
Face it, doing front-end development of even remote complexity can be a boaring and mentally exhausting exercise in repetition and inanity.
There’s hope.
Introducing Things With Prototypes
It would be unfair to the development community to state that there hasn’t been much progress made in the past few years. In fact, there have some pretty amazing tools under development for years. But it seems to me that only in the past year (or two), things have really picked up steam and these tools have matured to the point where I’m comfortable integrating them into an everyday tool chain.
So I present Things With Prototypes, a collection of tools, frameworks and technologies to help any front-end developer get their work done faster and better. These aren’t technologies I created myself, I’ve just bundled them up into a neat little package you can user over and over again for each new project.
Prerequisites
I won’t go into setup instructions here, but you will need to have Ruby installed on your system to use it, and will possibly need VirtualBox as well if you plan to use a virtual machine as a development environment.
What’s included?
Things With Prototypes brings together the following tools to work together in harmony:
Sinatra
Sinatra is a Ruby-based framework that’s really, really simple. Its main purpose here to to handle url routing and page rendering. It will allow you easily call partial html files, execute a 2-step layout and build helper functions to reduce the amount of repetitive code and DRY up your templates.
HAML
This is one of those love-it-or-hate it technologies, but if you find yourself typing too many angle brackets in a day, you’re gonna love HAML.
You know how HTML looks like this?
<div id=‘main’>
<ul class=‘my-list'>
<li>This is an item in my list</li>
</ul>
</div>
The same HTML written in HAML looks like this:
#main
%ul.my-list
%li This is an item in my list
In essence, HAML is a white-space sensitive language that compiles down to HTML. It will save you a lot of typing.
SASS / SCSS
SASS is cousin to HAML, but seems to be a bit more popular among the development community. It’s essentially the missing link for CSS. It comes in two different language flavors: one is HAML-like and whitespace sensitive, and the other looks a lot more like traditional CSS. Which one to use is a personal presence. But both syntaxes provide the following benefits:
Nested selectors, no more typing the same selector prefix over and over again
Inherit styles from one selector to another
Variables. Honest to god variables.
Mixins, or pre-defined blocks of styles that can be included inline
Conditionals, loops and functions. Yea, you heard me.
Sass is great. It takes some getting used to, but it makes plain ol’ CSS look just silly by comparison.
Compass
Compass is a CSS3 framework built on top of SASS. It provides an extra layer of awesome, including pre-defined modules, helper functions and integration with the Blueprint layout framework (if you’re into that sort of thing). It’s very extensible too, allowing you to build your own front-end swiss army knife.
HTML5 Boilerplate
Boilerplate is probably my favorite piece in the tool chain. I’ve always been a bit hesitant about frameworks like the 960 Grid System or Blueprint, as they often force you to adopt a specific markup or layout structure. However, Boilerplate is different. It’s a set of CSS and HTML defaults designed to give you the best possible starting point for creating a site that will work rock-solidly across all browsers and devices.
If you want to start safely writing in HTML5 today, look no further than the Boilerplate.
Middleman
Confession: When I originally put together Things With Prototypes, I wrote the Sinatra, Compass and server integration myself. It worked pretty well, but then I discovered that Middleman did all that and more.
But primarily, we use Middleman as a static site compiler. When you’re ready to deliver files you client, you can issue a single command to take your entire application and compile down to plain HTML and CSS. Couldn’t be simpler.
Not an Immediate Panacea
Okay, so if you’ve never used a Ruby framework before, using this package will feel pretty overwhelming. But I encourage any developer who likes learning new stuff to check it out. There’s some pretty wicked-powerful tools in here that could really revolutionize the way you build websites.
There is a supreme frustration that has affected both myself and countless web content managers for years: the tools you use to edit and format your content suck. They suck really hard. I’m talking about those clunky rich text editors that have toolbars that kind of look like Word, but behave so erratically you’d swear they had a personal vendetta against you.
I’ve worked with writers, editors and content people who are, at times, close to tears trying to understand why it has to be so difficult to achieve such simple tasks as formatting multi-line captions, putting images in a sidebar or displaying data in a table. These sorts of problems aren’t just the result of bad software either, they’re endemic to the most popular systems like Wordpress and even high-end CMS systems that costs tens of thousands of dollars.
The web is the most amazing publishing tool ever, right? Why is it so hard to get things to look right?
Here’s the single best explanation I can give the non-technical audience that’s fighting their CMS editor: tools for managing content on the internet are woefully
inept in the face of modern design. When I say ‘woefully inept’, I mean it just like that, but I am also indicating that nobody, to date, has invented a magic-bullet solution to these problems, and that if you’re thinking how hard could it be?, let me just stop you right there and say, really freaking hard. The tools thatdoexist have had uncountable man-hours poured into them and have overcome some pretty beastly obstacles, so while we may curse their name, we should still give them credit for trying really hard.
So if nobody will come along and provide a straight-up fix for the problem of easily formatting content for display on your site, what do we do? How do we reduce the pain of site layout while simultaneously building a better website?
It starts in the design phase
Most of the headache inducing trials with content layout come from attempting to do design inside a rich text editor. I’ll get into the technical details in a different post, but the critical piece of knowledge here is that the entire web works under the premise that content is format-less. A paragraph is only just a paragraph, a list is only a list, and an image is only an image. As a writer or editor, you should never get too concerned about where or how stuff appears on the page. That has (presumably) already been decided by your designer and implemented by your developer. If you do need new layout conventions, don’t try to create them in an editor. You’ll only end up frustrating yourself, your designer, and your developer. And it will look ugly.
There’s nothing more frustrating for a web designer than to spend weeks and months in requirements meetings and doing mock-up iterations, only to have a client suddenly throw out all design conventions by trying to force a new layout their CMS editor.
The solution to this, of course, is to design for all the potential layout conventions on your site before launch, and (possibly more importantly) figure out how those conventions affect each other. No developer is going to be able to hand you a tool that offers you ultimate flexibility, and nor should they ever try. There will always be constraints, so you must trust your designer to work expertly within them.
A Design System takes the surprise out of layout
If you are just starting to embark down the path of working with someone to build a content-heavy site, what you’re looking to do is have them create a design system. It should go without saying that a design system is precisely what you’re paying a designer to make in the first place, but it should come as no surprise that both clients and designers will get hung up trying to find the right logo size or color gradient and lose sight of the bigger picture (that your website needs to function without causing you or your users mental anguish).
A proper design system serves two purposes. First, it defines a blueprint for site style (a design manual if you will). It defines what headings, sub-headings and paragraphs look like, as well as site-wide conventions for images, columns, sidebars, etc, etc. It ensures that the aesthetic vision of your website doesn’t have to be compromised as you add new features, areas and pages. And second, it takes the surprise out of layout. How text and images will be displayed on the site under all conditions you’ve specified suddenly makes your layout a known quantity. If you never have to wonder exactly how something will look, it will reduce the change that you’re going drive yourself crazy trying to ‘fix’ it in the editor.
When you understand the behavior of the layout, it allows you to craft content with confidence.
Use markdown for proper markup
The purpose of all these rich text editors is to allow non-technical people to write HTML documents without actually knowing HTML. They work had to resemble interfaces we’re familiar with, primarily MS Word, with a formatting toolbar for the most common layout conventions. The primary fallacy of these tools is that they attempt to auto-generate HTML that’s tied to specific formatting rules, when in fact, HTML itself isn’t supposed to carry any formatting rules at all.
Enter Markdown, a small, easy to use formatting language that lets you write strict semantic HTML without ever having to open or close a bracket. It allows not-technical people to specify headers, lists, links and images in semantic, format-less HTML without the struggle of actual markup. Here’s a sample.
## Level 2 Heading
This is a paragraph, with a [link](http://google.com).
- List Item 1
- List Item 2
- List Item 3
Most major CMS systems support Markdown through a plugin. Ask your designer / developer about installing one. It may take a little time to learn, but it will save you time in the long run (this blog post was written in Markdown).
More custom fields and content types
Another major step to be taken in jettisoning the rich text editor is to develop smarter templates that use specific data fields to add more logic and intelligence to your site. If you have an A-spot on your homepage with an image and a caption on your site, you should only need specifying an image url (or upload) and caption text in custom input fields, and let the template take care of the rest.
Chances are, you already have a few custom fields in your CMS, possibly for sidebar widgets or header / footer sections. However, it is likely that you continue to rely entirely on rich text to write your primary content, using the all-encompassing Post type. It might be time to re-think this.
Consider features in a magazine layout. These sections may have their own distinctive layout and style, but they’re consistent from week to week, remaining the same until they’re redesigned. Why should it be any different for your content? If you’re posting an image gallery once a week, you should have a specific post-type for gallery posts. Doing interviews? Build a post type for it. Product review? Separate post type. You get the idea. Buy using specific posts types, you can include custom fields for your A-spot, B-spot, pull quote, sidebar, etc.
The idea of custom fields and post types isn’t exactly a new concept (heck, it’s how Expression Engine works by default), but with the immense popularity of Wordpress (which only supports custom fields through plugins or custom development) and the ubiquity of rich text editors, it’s easy to pass this kind of functionality by. Using custom fields and post types means that you can treat different types of content differently. Makes more sense that trying shove everything into a single layout format, right?
It should be easier
Your content is the lifeblood of your website. As a web editor it is time you got better tools to help put it on the page properly, without having to run in through the meat grinder of a rich text editor. You should be able to focus on creating better content and media, not adjusting margins or text flow.
If you’re considering a new website or a redesign, have a serious talk with your designer about the tools you’ll have for crafting content before jumping headfirst into the design.
Stay tuned for a future post, where I’ll get into some of the technical details behind rich text editors, and why they’re an inappropriate tool for creating content.
jQuery is great, isn't it? It makes everything a cinch. Ajax requests? No problem! Cool image gallery effects? No sweat! Popups, tool-tips, and overlays? Owned! jQuery is the veritable sonic screwdriver of our javascript toolkit.
But anyone who has written a medium to large sized application relying heavily on jQuery knows that things can degrade quickly from an organizational standpoint. Once a codebase starts to grow, and functionality becomes complex, you will consistently run into a number of issues that plague the typical jQuery coding practices:
Large number of dependencies, that need to be included in order
Heavy HTTP payload
Code repetition, too depedent on DOM
No design patterns or tightly coupled code
Polluted global namespace
A hodge-podge of plugins that 'just work', even though you don't know what's going on under the hood
So how do we address these problems? Simple: treat your Javascript like you would any other large codebase, and adhere to the same emphasis on organization and best practices.
In her talk, Murphey highlights the some of the primary problems that plague modern javascript codebases. But she also takes time to underscore a core reality that many developers forget: jQuery is primarily a DOM and AJAX tool. And that DOM and AJAX is a small sub-set of the overall Javascript platform. With that idea firmly planted in our heads, we need to realize it is not enough to just use jQuery, you need to learn to use Javascript as a language and platform. This means implementing all the same best practices you would with your 'real' application code.
Namespacing is good. Even if it takes slightly longer to type.
The global namespace in Javascript is a terrifying place. In fact, most jQuery plugin authors wrap their code in anonymous functions to avoid leaking variables into the global namespace, or avoiding the dreaded `$` collision.
The whole idea of namespacing was design to stop this problem. Why fight it? It's not hard to implement. While some frameworks and plugins do implement fancy namespacing functionality, the basic approach to declaring and importing namespaces looks like this (as cribbed from Google's Closure library):
Only having a single root-level object ensure that we're not polluting the global window object and we'll avoid naming collisions. You don't need to prefix your class names, or worry about competing with other plugins, or shield your code inside its own closure scope. Just namespace it.
One class, one file. Concat, minify and serve.
Time to stop making excuses for the MegaFile. If you're writing in PHP or Ruby or C# and you will always start to notice code smell when your files expand beyond a few thousand lines. Why should it be any different in javascript? Create a `lib` folder in your javascript folder, and divide your classes into folders and files. Again, simple.
To organize your files, just use the namespace structure we created in the example above.
But Bryan, you ask, there's no way I can split up my files like that. How am I supposed to manage importing them all into my page? Well, if you're not minifying your code before sending it out to the user, you should start right now. But during the minification process, you can also take advantage of a build phase. By using a proper build process, you can not only reduce your HTTP payload, but create automated steps for syntax checking and unit testing. Some tools to help you out:
Google's Closure Compiler will do concatenation and minification
JSLint will enforce syntax rules and tell you mean things about your code.
unit testing frameworks for Javascript. Have your pick.
The other wonderful benefit of a build process is that could conceivably be used to cherry pick different components and pieces from your library, allowing you to create and customize packages for different uses. You're not required to take the entire library with you when you only need a portion.
jQuery is a third-party library. Treat it like one.
Your application code does not begin and end with jQuery. It is just another tool in your tool chain. It does not need to be part and parcel of your entire application.
Remember that jQuery excels as AJAX and DOM. Don't write your entire application as a plugin. Separation of concerns exists in Javascript-land, too.
When you create a jQuery plugin, you're extending the core jQuery object (via the fn object, a place where jQuery has sanctioned for you to use). This is great, but only to extent that jQuery needs to know your application logic. If we're thinking about our app in MVC terms, jQuery plugins should really only operate as a controller. Say we're building a time-tracking application for our employees. Your plugin shouldn't care about an employee's name is or what they charge per hour. That's domain logic, and should safely encapsulated in a model object.
See what I mean? By taking our domain logic out of the plugin, we've not only simplified jQuery's role, but we've create a reusable model class that can be used across the entire application without having to duplicate logic.
Using Javascript as a platform
Stop reading articles like '25 jQuery Plugins to Make Your Site Rock' or '10 jQuery Techniques for Gorgeous Websites.' Other people's plugins are useful, but only to a point.
Master jQuery isn't terribly difficult: effects, DOM manipulation and AJAX all follow the same simple syntactical principles. Your real challenge is in architecture, performance and maintainability. When it comes to the Really Important Stuff, think through the problem and write that code yourself.
Things With Pixels has had a few different incarnations over the year, as my own personal site and weblog. Well, now things are changing up quite a bit: Things With Pixels is now my own web studio, offering website design and custom application programming. It’s only me at the moment working virtually from my cozy home office. However, I’m happy to offer full service design and development using tools like Photoshop, a text editor and my huge brain.
So what are you doing, exactly?
I’m solving your problems, that’s what. Not in the psychological sense, or in the sense that the sink in your upstairs bathroom leaks if you don’t turn the knob really tight. I’m solving your technology and design problems. I can meet with you, listen intently while you explain your needs and the needs of your business, then tell you what you probably want to do. If you like what I have to say, I can help design, develop and deploy those solutions.
At a glance, I’m a traditional web designer working in Photoshop, but also a crack code expert who can build an application using Ruby on Rails or your typical LAMP stack. I’ve got one foot in both the creative and engineering realms. I’m strange like that.
Why start a business in this economy?
Sure, I could sit in a cube all day collecting a paycheck at the end of the week. But that’s boring, and makes me sleepy. There’s way too many exciting things going on in the tecnology world these days to idle away in a cubicle somewhere. The decision to strike out on my own wasn’t just out of a desire to be self-employed, but to find the freedom and time to pursue the things that make living in 21st century really exciting. I want to spend more time writing code, sharpen my design skills, and help people and companies take advantage of all the fine things the internet has to offer.
Why should I hire you?
It’s really easy to make bad technology decisions - not because you’ve been lied to, or because you don’t understand the terminology, but because doing technology right is just hard. You need someone who knows the landscape, and who can translate business requirements into usable solutions. Obviously, I’m just one guy with a keyboard, so I may not always be the right choice. But for small businesses looking to stay small, startups who need a technology parter, or other companies looking for help on a project, I might be the perfect choice.
In Part Two of my Doctrine 2 tutorial, I’m going to spend some time talking about the general ideas behind Doctrine 2, and how it lets you manage database persistence using Plain Old PHP Objects (POPO).
What Doctrine is Not
But first, a few words about why Doctrine might not be like any other ORM you’ve used. Doctrine is not ActiveRecord. If you’ve been working with Rails, Django, Propel or even Doctrine 1, you’re probably very used to the ActiveRecord pattern.
ActiveRecord ORMs are typically characterized by providing a model base class for your business objects to inherit from:
class User extends Doctrine_Record // Doctrine 1
class User < ActiveRecord::Base // Rails
class User(models.Model) // Django
In Doctrine 2, there is no need to inherit from a base class. You can define your business objects like so:
class User
That’s it. Real simple.
Furthermore, ActiveRecord usually provides a save() method on the model object that handles insertion and updates to the database. With most implementations, this means that a single instance of your model object corresponds to a single row in your database. And the model object is responsible for its own data persistence.
Instead, Doctrine 2 relies on a separate persistence layer to handle database updates, via an Entity Manager object. This can have several benefits, including making it easier to test a domain layer.
What Doctrine Is
If we’re going to contrast Doctrine 2 to ActiveRecord, it can be said that it is an implementation of the Data Mapper pattern. It fully separates the in-memory representation of an object from it’s persistence details. It accomplishes this using a combination of provided mapping information along with class reflection.
While not a direct port, Doctrine 2 is very similar to Hibernate framework found in Java (or NHibernate in C#). It will likely feel very familiar to anyone who has used either of those libraries.
The Entity Manager
If you followed part one of this tutorial, you learned how to create entity mappings and classes. You should treat these entity classes just like any other object in PHP. When you’re ready to write back to the database, you will need an instance of EntityManager.
For details on configuring and instantiating the Entity Manager, see the documentation.
Once you have an instance of EntityManager, you can send entity objects to it to either be added, updated or removed in the database.
$em->persist($employee); // will create or update rows
$em->remove($employee); // will remove rows
By using these methods, you are instructing the Entity Manager to modify the Unit of Work. When it’s time to actually write back to the database, call flush()
$em->flush();
All pending database operations will be wrapped in a single transaction and executed.
So for a complete example, let’s use our entities to create a new Employee, and assign it a new project.
$employee = new Employee();
$employee->setLastName('Roberts')
->setFirstName('Roger')
->setJobTitle('Manager');
$project = new Project();
$project->setName('TPS Initiative');
$employee->getProjects()->add($project);
$project->setEmployee($employee);
$em->persist($employee);
$em->persist($project);
$em->flush();
Note that for new objects, id’s will not generated until flush() is called.
In the third part, I’ll discuss how to handle relationships between objects, and concept of the ‘owning side’ in Doctrine 2.
Update: Since this post, Doctrine 2 has seen a stable release. I highly recommend you consult the documentation, many things about the API have changed, or new features added.
I’ve been developing with version 2 of the <a href=’http://www.doctrine-project.org/>Doctrine ORM for a few months now, and am really excited about the upcoming beta release. Not only does Doctrine 2 improve upon the first version of the framework, it is gearing up to be the de-facto ORM for modern PHP development.
What follows will be the first part in an ongoing series of articles about getting up and running with Doctrine 2. In this first part, we’ll create mapping files using XML, and use the command line tool to generate our entity classes and database schema.
Learning Doctrine 2
Before we begin, I first want to point you to the official Doctrine 2 Documentation. It’s well written, with lots of great code samples. It’s also been continually updated with each new release, so there’s more information be added all the time.
Seriously, any time you’re stuck working with Doctrine, go back to the manual. There’s a good chance you’ll find the answers you need. If not, getting a response mailing list is usually your second best option.
Now let’s get started.
Starting the project
For the full source code of the sample project as it evolves, please visit the project page on Github.
For now, the project is split up into two folders: lib and tools. lib will hold all our code, plus external libraries. tools will contain the Doctrine command line tool. Create a folder inside lib called Tutorial. This is the namespace we’ll use for our code.
Installing Doctrine
Note: Doctrine is now in it’s second Beta. There are some things in this article which may no longer apply, especially as it concerns the CLI. Please check the Doctrine documentation for up-to-date info. I’ll try to fix this tutorial when I have time.
This series of tutorials is aimed at the first Beta release of Doctrine 2. The Beta hasn’t quite been released yet, so, we’ll be working off the trunk release of the framework for now. Let’s check it out from the repository:
svn co http://svn.doctrine-project.org/trunk DoctrineTrunk
After getting the source, make sure to copy or symlink the Doctrine and Symfony library folders (which can be found in lib and ‘lib/vendor’, respectively) into our own project’s lib folder.
Also, copy the following 3 files from tools/sandbox into the tools folder in your project:
cli-config.php
doctrine
doctrine.php
These are the command line tools we’ll use later to automatically generate our entity classes and database schema.
Starting with XML Mappings
First, I should note that using XML to map your entities is not the default choice Doctrine makes. Most people seem to prefer the Annotation mappings that are in-line with your class property definitions. This mapping style is already well documented, so I thought I would demonstrate an alternate method instead.
If you’re interested in using annotations or YAML instead of XML, I encourage you to keep following along. The basic ideas are the same, only the syntax will differ.
Next create two folders inside our Tutorial folder:
Entities
Entities\Mappings
These are the folders that will hold our entity classes, and the mappings we’re about to create.
Let’s create our first mapping file. Inside the mappings folder, create an XML file named Tutorial.Entities.Employee.dcm.xml. Accurately naming the file is important, because Doctrine requires you to use the fully-qualified namespace. In this case, the namespace of our entity classes is Tutorial\Entities.
This is the basic shell of any entity mapping. It consists of a root node called<doctrine-mapping> and an <entity> node. Notice how we’re including the fully-qualified class name as the name of the entity, as well as the name of the database table that the entity will use.
Note: One of the many reasons I prefer XML mappings is because Doctrine provides a schema definition. This enables many IDEs to provide validation and code completion which makes writing the mappings very easy.
Now we need to tell the mapping file how to generate a unique id (or primary key) for our entity:
We use the element to tell Doctrine the name of our identifier, it’s type, and which column in the database to use. We also provide a ‘generator’, which in this case, is telling doctrine to use auto-increment in our primary key field.
Now we can start adding other fields to our mapping:
The <field> element is created, along with a name and a type. Tthese types are not database types, but rather a type specific to Doctrine that binds to a specific database type.
Also note that the name attribute references the property that will be on your entity class, not the column name in your database. By default, Doctrine will generate the column name based on your property name. If you wish to customize a column name, use the column attribute:
For this tutorial, we’re going to have two entities: Employee and Project. We just finished creating the mapping for Employee, so here’s the complete mapping for Project.
Of course, no ORM implementation is complete without a way to establish relationships between objects. These come in the form one-to-one, one-to-many, and many-to-many relationships between your entity classes that need to be represented in your database layer. For our project, we want to establish a bi-directional one-to-many relationship between an Employee and a Project.
In your Employee mapping file, include this element:
This establishes a one Employee to many Project relationship. We’ve also defined which fields will represent this relationship in our entities. On the Employee side, we will use a property named projects, and the inverse of the relationship will be represented by employee property in the Project entity.
Once again, we’re working at the class level by defining properties that will be mapped to our database. At this level, we have no need to define foreign keys ourselves. When we generate our schema, doctrine will automatically create the foreign key fields.
We also need to define the inverse of the relationship in our Project mapping:
That’s it for our mappings. Now we’ll set up our command line environment for generating our classes and schema.
Doctrine Command Line Interface
The command line tool has lots of useful feature. For this part, we’re going to focus on two commands. One that will generate entity classes from mappings, and one that will generate database schema.
First, we need to configure the cli-config.php file you copied into the tools folder to load our library namespaces and our XML mappings. Copy and paste this into the file:
<?php
require_once __DIR__ . '/../lib/Doctrine/Common/ClassLoader.php';
$classLoader = new \Doctrine\Common\ClassLoader('Tutorial', __DIR__ . "/../lib");
$classLoader->register();
$config = new \Doctrine\ORM\Configuration();
$config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache);
$driverImpl = new \Doctrine\ORM\Mapping\Driver\XmlDriver(array(__DIR__ . "/../lib/Tutorial/Entities/Mappings"));
$config->setMetadataDriverImpl($driverImpl);
$config->setProxyDir(__DIR__ . '/../Proxies');
$config->setProxyNamespace('Tutorial\Proxies');
$connectionOptions = array(
'driver' => 'pdo_sqlite',
'path' => __DIR__ . '/../db/database.sqlite'
);
$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
$helperSet = new \Symfony\Components\Console\Helper\HelperSet(array(
'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()),
'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)
));
While I won’t go into the details of this here, configuring the Doctrine CLI is already a well-documented process. However, you’ll notice that we’re using sqlite for the purposes of this tutorial. Feel free to substitute your database of choice.
Now we’ll run the command to generate our entity classes. Navigate to your tools folder and run the following:
$ ./doctrine orm:generate-entities ../lib
This should create class files in the project’s Entities folder. You’ll notice it also automatically generates properties as well as getter and setter methods. Very handy.
Once the entities are create, we can create the database schema:
$ ./doctrine orm:schema-tool:create
With luck, everything worked perfectly, and we now have both entity classes and a database schema to start programming with.
In the next part of this tutorial, I’ll talk a bit about the Entity Manager, and how to save and update objects.
I've been paying a lot of attention lately to the price of software. Now that everyone and their brother has an 'app store', it has shone a bright light on the practice of getting people to pony up money for apps, services, gadgets and games.
I'm a finicky software buyer. I don't like parting with cash until I'm absolutely sure it's worth it. So what makes a piece of software worth buying? How much is too much or too little to charge? And what are the deal-breakers when it comes to going from trial download to full license?
#### Flexible licenses
This is a big one for me. What are the rules for using the software legally, and does it fit my pattern of computer use? For example, my [Textmate](http://macromates.com) license is valid on any [computer I user](http://macromates.com/license_policy), as long as I'm the one using it. This has served me well, as I've traveled from job to job over the years.
Adobe CS5 allows me to install one copy on my desktop and [one on my laptop](http://www.adobe.com/products/eulas/?PID=2159997). Windows 7 allows for one physical install, and up to [four virtual machines](http://superuser.com/questions/25678/how-does-windows-7-licensing-work-for-running-the-os-as-virtual-machines). All of this fits with my computing profile.
The Mac App store also allows you sync purchases across computer. Most software these days offers some kind of multi-machine or personal use license, but I always like to check before I buy.
##### Price vs. Need vs. Interest
Paying 99 cents for software is like buying a candy-bar in the checkout line (actually, cheaper). I don't need to think about it. If I'm mildly curious about an app, and it's only a dollar or three, chances are I'll check it out.
I've paid upwards of $10-15 for apps that I've used a few times, and left neglected. I regret buying these, and now whenever I consider spending that much on something I'm not sure if I'll like or not, I'll typically go without.
Once we're out of the $20 range, I typically won't buy anything unless I can use a full-featured trial. I need to make sure this software fits me like a glove before I commit any money.
Once a piece of software gets to be $100 or more, it has to solve a critical problem for me. It has to be something that that I can't live without.
##### Upgrades, Support and Annoyance.
I remember buying a copy of Parallels 4 in one of those [MacUpdate software bundles](http://www.mupromo.com/). It was a great deal at the time, but my license didn't allow me to upgrade without shelling out the full price.
That restriction, combined with an obnoxious updater dialog and oodles of email from Parallels asking me to pay for even more upgrades every few months led to me become a happy [VMware Fusion](http://www.vmware.com/products/fusion/overview.html) user. Each time you nag me, or ask for more money, there's less chance you'll ever see another dollar from me.
I don't like paying for upgrades. If the software is already solving my problem, so what do I need to upgrade for? I even took a while to upgrade from Transmit 3 to [Transmit 4](http://www.panic.com/transmit/) (which is like the best thing ever). If you can include free upgrades, or at least a free year of upgrades with your software, you'll get an extra point from me.
#### So What Have I Bought Lately?
So I thought I would feature a few recent purchases, and whether or not I thought they were worth the asking price.
**Adobe Creative Suite 5** for $1,500
**Verdict:** Overpriced.
CS5 is bloated, buggy and hasn't seen a useful new feature in years, especially when it comes to making web design easier. But it's the only game in town, which is why designers shell out such a ridiculous amount of money.
**Sparrow** for $4.99
**Verdict**: [Try it!](http://sparrowmailapp.com/)
There aren't a lot choices when it comes to desktop mail clients on OS X. I was never a huge fan of Mail.app, so thought I'd give Sparrow a try. After a shaky beginning, I'm a big fan. The Twitterific-esque interface is a big improvement, and it integrates directly with Gmail folders and labels, unlike Mail.app.
**OmniFocus** for $79.95
**Verdict**: [If you're into that sort of thing.](http://www.omnigroup.com/products/omnifocus/)
After going freelance, I wanted something that could allow me to organize the stuff I had to do. OmniFocus seemed to be favorite among the Mac community, and for good reason. It's easy to use, extremely flexible and allows deep organization. If you're a hardcore GTD, task organizing guru, then it's probably perfect. However at eighty dollars, it's a bit expensive for a casual user. An alternative like [Things](http://culturedcode.com/things/) or [Evernote](http://evernote.com) might be a better fit.
**Tower** for $59.00
**Verdict:** [Buy it!](https://sites.fastspring.com/fournova/instant/tower)
Tower is the most comprehensive graphical Git interface I've used. Using just the command-line is okay for simple things, but I do like to have a nice graphical view of my diffs, checkboxes for files to commit and a one-click 'append to previous commit' option. I had been using [GitX](http://gitx.frim.nl/) with some success for a while, but was extremely impressed by Tower.
**iA Writer for Mac** for $17.99
**Verdict:** [Buy it!](http://www.iawriter.com/)
I'd heard a lot about iA Writer for iPad, but being iPad-less, could never try it. Having been a happy [WriteRoom](http://www.iawriter.com/) I wasn't sure how much it brought to the table, and if it would really be worth the price. I was totally wrong. With it's gorgeous full-screen mode, brilliant looking font, and smart, but not too clever Markdown integration, it's a pitch-perfect app for anyone who just wants to site and write.
#### What About Web Services?
This post was mostly about desktop software, but there are a number of web services I use personally and professionally and highly recommend. Many have free plans, but I'll only mention them if I'm using the paid service:
- [Github](http://github.com) for storing my code. Starting at $8/mo.
- [TypeKit](http://typekit.com) for all the web fonts on my site. Starts at $24.99/yr
- [Linode](http://www.linode.com/index.cfm) for web hosting. Starts at $19.95/mo.
- [Freshbooks](http://freshbooks.com) for invoicing. Starts at $19.95/mo