Ryan Tablada

Christian, UX Tycoon, Instructor at The Iron Yard

Checkout my screencasts at EmberGrep

Checkout my newest book on Leanpub

Laravel Archives

I Made a Huge Mistake

Jan/16/2015

Last year I wrote three different articles. And I have to admit something...

I made a huge mistake

Repositories

After reading Fowler's "Patterns of Enterprise Application Architecture", I found that I royally messed things up. Repositories actually are in-memory collections or at least mediators to a different data store or subsystem that FEELS like an in-memory collection of records. Domain classes construct queries and then submit this query object to the Repository to grab data. So when we've been creating "Repositories" that take in simple parameters and return data sets, this doesn't really fit the bill.

UserRepository->findByEmail($email) doesn't really feel like working with a collection, nor does it work on local data, instead it only constructs queries. But is there a better fitting name for this?

Table Data Gateways

Gateways provide entries into discrete subsytems and provide a more logical API for the domain that wraps that subsystem. Table Data Gateways take in primative arguments and then return collection or row results from the database.

Take a look at Fowler's diagram of an example Table Data Gateway and see if it looks familiar?

find, findForCompany, update, insert

Martin Fowler P of EAA

TLDR;

Naming has impact. In the Laravel community, I have led people astray by teaching Table Data Gateways as Repositories. I'm still looking for an analog of the traditional Repository in terms of database interaction.

But if you are looking for a good Repository to look at, just read Laravel's source and the Illuminate\Config\Repository. It interfaces and adds nice query like sytax on top of the Laravel Config Loader which is relatively an existing in-memory collection to do work on.

So. You have be educated! Have a great time being able to speak the same programming terminology shared by everyone else!

Add Variables to Your Password Reset Emails

Jan/13/2015

Laravel ships with a fairly nice default password broker. It creates an auto-expiring reset token, associates that with the user, and sends an email to the user all in one nice fairly modular system. But, there's a problem...

How do you add dynamic data to your reset view.

By default, Laravel will pass through the requesting user and the new token that was created. But, there are times where you need more.


Looking around the usual haunts of Stack Exchange, and Laravel.io: most people recommend firing the underlying token logic yourself, then calling mail send. It's a bit of smell to have to replicate half of the logic that is available from PasswordBroker.sendResetLink. Or they say to create a view composer, on the fly and I'm not a huge fan of that either (view composers should be available for all logic not just a single flow). Instead, I wanted a way to be able to add data to my reset email without ripping out the guts of the rest of Laravel's existing logic.

At this point, you might be asking "why would I want to do this"? So consider the following system.

An app you are building has a closed registration process (only admins can create users). You don't want admins to set user passwords because they will most likely never be reset to something else.

Instead, you fill in the password with a random string and hash that (or even better a random string that isn't a valid hash so it never matches if someone tried to brute force guess passwords). Then you send the user a reset email to set the password on their new account.

This flow is great because you use existing tested logic to bring a new user into your system instead of having to maintain a password reminder AND a confirmation setup. But, for most users, they'll be more than a little confused when they see an email telling them to reset a password on a site they've never been to or created an account for. So, if we want to use the reset system and keep the nice syntax of PasswordBroker.sendResetLink.

The magic comes from the optional callback that is accepted as the second argument to sendResetLink. Usually you would use this to change the replyTo or subject for a Swift Mail Message. But, there's more going on under the hood.

The callback has access to the Swift_Message instance that eventually is used to send the email. And in the send function in Laravel's Mailer, this Swift_Message instance is set to the message variable in our template. Most often, this is used to use the email's subject in the template.

But, we can do a lot more than this. By setting undefined public properties on Swift_Message in this callback, we can pass almost ANYTHING into our email template. So, for the example above with creating a User with a random password, and sending an email, my code can look like this:

```php public function createWithRandomPassword($attributes = []) { $attributes['password'] = Hash::make(str_random());

$user = $this->user->create($attributes);

return $this->passwordBroker->sendResetLink($user->toArray(), function($message) {
    $message->newUser = true;
});

} ```

And my template can grab that newUser property:

```php @if ($message->newUser)

Welcome New user!

@endif

Click here to reset your password: {{ url('password/reset/'.$token) }}

```


Do you have any hacks in Laravel that you like? Share them in the comments below!


Are you a Laravel or Ember developer wanting to branch out and learn how to build awesome apps in Node and Express? Sign up for the newsletter at embergrep.com to learn more about my upcoming course "Express.js: Zero to Sixty"!

Make Laravel 4 Feel Like New

Oct/21/2014

After creating an API with Laravel 5 about a month ago, I was really liking the new directory structure and some of the features that were available. Today, I tried to replicate this magic and was having issues getting a stable version of Laravel 5 (which is to be expected to a degree since Taylor is still deciding some of the bootstrapping process). Then it hit me.

I can make Laravel 4 act a lot like Laravel 5!

Most of what I liked was the structure and use of service providers to boot things. With the development process that we've created with our team, some of the new features like Annotations, Elixer, and Request Validations aren't on our list to adopt adopt. So, after a bit of scratching my head, I was able to come up with a way to set up Laravel 4 to work similar to Laravel 5 (and hopefully make converting to Laravel 5 REALLY easy).

src Folder

The first thing that I do is create a src folder for my application code. Then I put in some basic folders (somewhat inpired by the namespaces included in the bootstrap project for Laravel 5).

src/
|-Http/
| |-Controllers
| |-Requests
| |-Responders
|-Models/
|-Providers/

Strip out app

From the app directory, I delete the folders for controllers, commands, models, and tests. And, I delete the routes.php and filters.php files. Then, I move the database, and storage folders up to the root level of my project.

Then there's some updating to do in the app/start/global file. I go and remove commands, controllers, and models from the class loader, and I update the app_path().'/database/seeds' to base_path('/database/seeds').

I then need to remove and update the autoloader in my composer.json file to look like this:

"classmap": [
    "database/migrations",
    "database/seeds"
],

resources

Next, I move the app/views directory to resources/templates (I prefer to call these templates since I refer to the objects that perform the actual rendering views). To make this work in the framework, I then go to app/config/view and update the paths to array(base_path('resources/templates')).

Autoloading with PSR-4

Now, I go and update the composer.json file to autoload the src/ directory to my application/vendor namespace.

Bootstrap Provider

In order to make my src directory as easy as possible to drop into any project, I create a single service provider called BootstrapServiceProvider in my src/Providers folder. It then looks like the following:

class BootstrapServiceProvider extends ServiceProvider
{
    protected $providers = [
    ];

    public function register()
    {
        foreach ($this->providers as $provider) {
            $this->app->register($provider);
        }
    }
}

Now in app/config/app.php I just need to refer to this single provider. And when I'm building my application itself, any new service provider that I want to load within my own application namespace just get's thrown into the providers array in my BootstrapServiceProvider.

Routes Provider

I then can create a routes provider that looks a bit like this:

class RoutesServiceProvider extends ServiceProvider
{

    protected $namespace = 'Acme\\Http\\Controllers';

    public function register()
    {

    }

    public function boot()
    {
        $router = $this->app['router'];

        $router->group(['namespace' => $this->namespace], function($router) {
            require __DIR__.'/../Http/routes.php';
        });
    }
}

And now in my src/Http/routes.php file, I can use the $router variable to declare routes rather than using the Route facade.

Build from there

Right now, that's about the needs for my application to make it structured like Laravel 5 and pull out some of the weight that was in the original app directory. As I need them, I create more service providers to alias interfaces, register events, register class based filters, and more.

Multiple Front Controller Layers?

Oct/11/2014

In my persuit to continue making my code more maintainable and a bit cleaner, I have come across a new question with controllers.

Is it ok to have multiple layers of front-controllers.

What is a front controller?

If you are unfamiliar with a front controller, it is a single object for channeling the flow of a program based on request information. In most apps, you won't really think about front controllers since even the thinnest MVC frameworks will handle this for you and you'll call it a router. The Router often will check the URL and HTTP method and send it off to a lower layer controller and optionally pass the response of the controller to a presentation layer.

Why use multiple layers of front-controllers?

This is assuming a server-side MVC framework such as Django, Rails, or Laravel and you are using the built in router as your first line of Front Controllers. However, what happens when you need to further whittle down a request using more than just the URL and HTTP method. For this I would say let the router match on usual parameters and THEN pass it on to a thin Front Controller that further handles the requests and then passes on the remaining request to a Page Controller or Server Page. Yes, there are routers that allow you to route based on HTTP headers, request data, and more: but the syntax is awkward and creates multiple entry points into a single system.

Where would this come up?

One situation you may find yourself in would be handling Github Webhooks. When hitting your site, Github will send every event to a single API url on your site. The only way you can differentiate between the various event types is by checking the X-GitHub-Event HTTP header. I've seen a lot of people handling all of these events in a single controller and it gets really ugly really fast. So, I started thinking about ways to clean this up.

At first, I thought of using basic ADR: My traditional controller would send off the formated request data to a Domain layer that read in the HTTP header and... Domain shouldn't know how to talk about HTTP!??? Not to mention the mess of having a responder that could respond to all of the possible formats of data to handle all of the various responses for all of the possible events. It was a mess.

More Front Controllers to the Rescue!

Scratching my head for a second, I stopped and thought, "what if I had this controller ONLY look at the Request header and based on that pull a different controller out of IoC and return it's response?"

After a bit of practice I had something like this:

// routes.php

Route::post('/api/github-webhook', 'Acme\\Github\\WebhookFrontController@__invoke');

// controllers/Acme/Github/WebhookFrontController.php

<?php namespace Acme\\Github;

use Request;
use App as Application;

class WebhookFrontController extends \Controller
{
    public function __construct(Request $request, Application $app)
    {
        $this->request = $request;
        $this->app = $app;
    }

    public function __invoke()
    {
        switch ($this->request->header('X-GitHub-Event')) {
            case 'commit_comment':
                return $this->app->make('Acme\\Github\\CommitCommentController');
                break;
            case 'deployment':
                return $this->app->make('Acme\\Github\\DeploymentController');
                break;
            case 'push':
                return $this->app->make('Acme\\Github\\PushController');
                break;
            default:
                return $this->app->make('Acme\\Github\\InvalidEventController');
                break;
        }

        return $controller->__invoke($this->request);
    }
}

Then, your controller that is invoked by the Front Controller can be just like a normal old controller! If you want to use an ADR architecture or something more traditional to your architecture flow, it's up to you!

OOP API Responders

Sep/15/2014

The first thing that started getting me interested in a new way of emitting responses was listening to talks on hexagonal architecture. Essentially, having methods on a listener that would call a success method or a failure method. The idea of having dedicated functions for building success and failure cases really stuck for me... But, the implementations all seemed a bit cumbersome to use and usually just moved logic around in the same class. I shoved it to the side.

Next, I was digging around in the source code for Ember and started really messing with the Serializers that it included. Basically, it allowed Ember to have its own parameter language and then provide a very thin translation layer for swapping out data with third party APIs. I tried implementing this with some controller magic a few different times, but it was hard to get out of the conventions.

The third thing that got me interested was reading Paul Jones' article on the Action Domain Responder pattern. I had already been extracting my domain logic to gateways, repositories, and other OOP patterns that made my controllers very thin. But, what interested me was the idea of a responder. A full class that once I give it the data it needs, it will go and build my response, and return the prepared headers and more. This was starting to really get me interested, but having classes for every action within every resource made the code base a bit larger than I really wanted.

The final nail in the coffin that allowed me to make responders that I loved, was Laravel 4.3's controller action injection. This means that while my domain handlers can be injected at the controller class level, things like my request handlers and responders can be injected at a action level. I mixed this with Phil Sturgeon's Fractal to get really customizable responses from my APIs. So, my controller for a resource now looks a bit like this:

Class Users extends Controller
{
  protected $userRepo;

  public function __construct(UserRepo $user)
  {
    $this->user = $user;
  }

  public function index(IndexRequest $request, UserResponder $responder)
  {
    if ($user = $this->user->paginate($request->perPage)) {
      return $responder->successCollectionResponse($user);
    } else {
      return $responder->failureCollectionResponse();
    }
  }

  public function show($id, ShowRequest $request, UserResponder $responder))
  {
    if ($user = $this->user->find($id)) {
      return $responder->successItemResponse($user);
    } else {
      return $responder->failureItemResponse();
    }
  }
}

Then in my responder I can call out to Fractal, build my status codes, append meta data, and do things that muddy up controllers, while having it in a maintainable OOP set of code.

Right now, I share a responder for my different actions, and while this means that I could inject the responder in the controller, I choose to keep it injected to the action so that I can change my responder for a particular action without changing it for every action in a resource.

Also, cool to note is that when you need to add meta data to an API response, you don't have to dig through your controller and worry about messing up any of that code, you just jump in the responder or transformer, make the changes to the response format and that's it!