2012-11-01T10:02:48-05:00http://zombor.github.com/Octopress2012-10-29T07:37:00-05:00http://zombor.github.com/blog/2012/10/29/well-designed-application-architectures-part-3Last time we talked about how your business logic should look. It was a high level overview of the architecture. This time we’ll actually put that into practice and write some code. We’ll be using BDD (Behavior-Driven-Development) to design the application.

We’re going to be using Behat to run these features. So let’s start a new project!

So where do we start? BDD says we should start from the outside and move our way in. So, we’ll start with some Gherkin. I’ll make up some requirements that you might receive from a product manager:

features/register_account.feature

123456789101112131415161718192021222324

Feature: User Registration
Scenario: User Registers With Valid Data
Given I am an unregistered user
When I register with the following information:
| first_name | foo |
| last_name | bar |
| email | foo@bar.com |
| password | foobar |
Then I should be registered
And I should receive a welcome registration email
Scenario: User Registers With Invalid Data
Given I am an unregistered user
When I register with the following information:
| first_name | foo |
| last_name | bar |
| email | foo@bar.com |
| password | |
Then I should not be registered
And I should see the following errors:
"""
password is required
"""

Now let’s run it:

1

bin/behat

You’ll see a bunch of undefined steps with some snippet code. Let’s paste these into our context file (features/bootstrap/FeatureContext.php) and rerun behat. Now we’ll see some TODOs! Time to actually write code! We’ll start from the top:

1

Given I am an unregistered user

This is going to be a no-op. We don’t need to do anything here, so let’s just remove the PendingException in the step defintion:

Now that step should be green when we re-run the behat steps. We’ll move on to the next step. Here’s where the real meat will start. Since we are writing our business logic, we’ll start with defining the interface we want to work with, and write the code we wish we had.

Now if you run behat, we’ll have the next step green in both scenarios.

Let’s move on to the next step. What do we do here? How do we assert the account was created? Simple. We want to use Dependancy Injection, and inject a repository object into the use case class. The use case will then use that repository to persist the data. We will use a mock object to keep track of this. We don’t want to use the real thing because we don’t care about the database right now (we will later, and we’ll replace this code later). We’ll need to modify our last step definition:

Make sure you require that file right above the Mock_Account_Repository class defined above. Now we need to assert that our class does what we want. So in our next step definition, we’ll inspect that mock object:

Sweet! Our first scenario passes! You should be able to implement the rest of the second scenario fairly easily.

This concludes our tutorial on creating a basic Interactor class. It doesn’t do much right now, but next time we’ll add in some validation, and do some other fun stuff with phpspec.

]]>2012-10-02T06:29:00-05:00http://zombor.github.com/blog/2012/10/02/well-designed-application-architectures-part-2Last time we talked about what MVC really is, and how to use it properly. It didn’t really mention much of anything about how/where to put the code that makes your site tick. This code is called your application. It’s the business logic that, you know, actually does the real work on the site.

If you recall from last time, I said that this code should live far, far away from your delivery mechanism (your MVC layer). That’s pretty abstract. Where should it really go? How do you write it?

A lot of people look at me funny when I say “do not write your business logic with a framework”. They think “how on earth will I get anything done?”. It’s actually very easy, and not time consuming at all if you do it right.

Language

I’m going to be using PHP for my code examples here. I prefer Ruby, but it seems that it’s “harder” to do this in PHP, so I want to show that it’s actually not.

File Organization

First off, put your business logic into it’s own repository. This will make the separtion clear and force you to not muck the separation of concerns together. You’ll also be able to recognize your application’s purpose from it’s file structure, as described in the Uncle Bob talk from last time.

People in the PHP world seem to like the PSR-0 standard for file and class naming so we’ll use that, but not the silly PSR-1 and PSR-2 “standards”.

Components

Below are the components that we’ll be using to design our application.

Use Cases

Back in school you learned about a Use Case, right? Well, they aren’t useless after all. Use cases are the backbone of how your application works. We’ll be using a use case driven architecture from now on.

Why? They let us define our classes in a structured way, and let any reader of our code know exactly where to go when they need to look at some functionality. Need to know about how a user registers? Simply go to the Register_User class, all the code is there.

DCI vs Interactors

I prefer to use the DCI pattern for describing my use cases in code. However, it’s not clear how to implement DCI in many languages. Because of this, I’ll just be describing interactors, which are a similar but simpler way to write use cases.

DCI makes a lot more sense overall, but in some languages (especially php), it’s just impossible to implement properly. You basically would need the ability to assign traits to objects at runtime (at the minimum), and php is certainly not capable of that.

An interactor is just a class that describes your use case. It has the following properties:

It has a single public entry point, execute()

All other methods are protected or private

It raises exceptions when an error occurs

It returns normalized data (like an array) for a query operation, and returns nothing for a write operation

It injects all it’s dependancies. I like to use factory methods for these, so I’ll do that in my examples later on

Database Access

So where does your database access come into play in all this? A lot of frameworks make you think about the database entirely too early. The database is just a detail about where/how your data gets persisted. Don’t worry about it too much yet. Just worry about defining your Data Objects first. We’ll use a repository pattern to send those data objects to be persisted, and it doesn’t really matter to anyone but the repository class on how that’s done.

Data Objects

Your data objects classes that model your business objects. They don’t extend anything, they don’t connect to a database. In php, they are just POPOs (Plain old php objects). Here’s a good example:

The repository class should take data objects in, and spit data objects back out. That’s it.

Next time we’ll start building an actual interactor.

]]>2012-09-25T16:06:00-05:00http://zombor.github.com/blog/2012/09/25/well-designed-application-architectures-part-1I’ve been dumping my brain about this topic in IRC for about 3-4 months now, and I figure it would just be easiest to do a dump here and link people to it. This series will probably be a few parts, I’m just going to do parts of the dump for a few days.

If you have feedback for me, please use twitter (on the right over there) to do so.

Before I begin, you should watch this (I’m basically going to be rehashing it and adding my own notes):

MVC

So, lets start with MVC. Web-based MVC (yes, not the “real” kind). “What’s wrong with MVC?”, you might ask? Well, nothing, as long as you use it for it’s strengths: as a delivery mechanism pattern. We’ll get into what a delivery mechanism is in a bit. So, how do you use MVC effectively? Well, lets start with the different parts of the acronym:

Controller

Your controllers are thin, right? Do they contain only http logic? If they contain any business logic at all, they are not thin. Just because it’s not database calls doesn’t mean you can throw it in the controller. The controller shouldn’t know anything about your domain logic. It should just know:

How to parse incoming request data

How to send that data to your business classes

How to send the output from the business classes to the view

That’s it! What do you gain from doing this?

Your controllers are even thinner

Your controllers are probably testable in isolation, so you can test your http interactions quickly, and without a real web server or framework loading up

Views

When I say “view”, does “class” also come into mind? Are you doing all your presentation logic in your templates? Stop it! You can’t test that. Use something like Mustache. What do you gain by using Mustache?

Logicless templates

Testable views

Portable templates (you can reuse your same templates in both your server and client).

Logicless templates let you start your views with tests (You do TDD, right?). It keeps your views more maintainable and lets you be more confident that the logic contained in them actually works.

When you write your view classes, they should only accept input from the outside world. They should not be reaching into the database, they should not be instantiating any classes (especially not models!). All they should be doing is accepting input from the controller and formatting that input for display. This display can be anything: html, json, xml, etc. This is another advantage of using mustache: it lets you easily adjust your output template, and not change your logic that parses the data. Reuse people!

Model

Wow, what a big area. Basically anything that isn’t a controller or view goes here. That is A LOT. This is the first problem with using MVC 100% to design your application. If you subscribe to the “thin controller, fat model” approach (as just about all web frameworks out there teach you), you will end up with an unmaintainable mess of an application.

Why? Well, first off, you’ll be combining your domain logic (since your controllers are thin, right?) and your persistance logic (just about every framework tells you to put queries in a model) in the same layer. This is very bad for many reasons:

Hard to test

Slow to test

Tests will do too much

A lot of the topics in this series will revolve around testing. How can you make your application easier to test? How can you start with tests?

So what can we do? Easy: Don’t use models. Just don’t. Models don’t belong in your MVC delivery mechanism. In this sense, I suppose I should be calling it CVT (Controller-View-Template).

Delivery Mechanism

A framework of classes that easily let you redistribute your business logic (your application) in a format specific way, over a specific medium.

Your application is not made up of controllers and views. That stuff is all part of your delivery mechanism. So from here on out, I’ll be refering to your business logic as your application.

You do need these things. You don’t want to be writing http request and response classes. That crap is already done, and it’s a lot of work.

A delivery mechanism’s sole purpose is to call your application, and send it’s output to a specific format. It could be an html website, a JSON based REST API, or a console based binary. All three of these could be delivering the exact same business logic. All three of these could be different frameworks, because your application is completely decoupled from your delivery mechanism.

Your delivery mechanism should not know anything about your business rules, except how to call the application. It consumes your application, and spits out the data.

Ever cry when your favorite framework released an upgrade, and it broke the old API? Separate your application from your delivery mechanism, and upgrading to a new version (or a completely different) framework becomes much easier. The framework code no longer has it’s slimy tentacles embeded inside your code. That means less code to change.

This brings me to a related topic: You should try like hell to never have your business logic classes extend a third party class. Don’t let someone else taint your class’s API with theirs. You’ll just end up in a similar situation to the framework problem above. I’ll go into more details on this in a future post.

Business Logic

“If we can’t use models, then were the hell does the business logic go?” You might be asking. Easy:

Far, far, far, far away from your MVC layer. We’ll get into the details on this next time.