Stop Using Facades

Apparently when experienced developers are introduced to Laravel they're immediately disgusted by all of the static method calls they see. As soon as someone vocalizes this "atrocity" there are multiple prominent Laravel ambassadors to quickly defend the framework by explaining the facade pattern, "Nope, you're wrong! It's actually using OOP behind the scenes!"

Both sides have valid points. Here's my case against using them...

Before we start! I think some people have taken this article as anti-Laravel. That wasn't my intention at all! Using facades are great for gettin crap done quickly. I don't think anyone needs to read a post about throwing stuff together to make things work. We all know how to do that. This post is about some of the benefits you get when you decide(for yourself) not to use them and illustrate how to do that.
A response! Taylor has now made injecting the dependencies under the facades a lot easier. Check out his response to this post.

It seems like an anti-pattern

Many people view injecting your IoC container into your classes as an anti-pattern. I can understand this. If I were looking at someone else's class and trying to figure out what its dependencies were, I would absolutely prefer to be able to look at the constructor rather than track down everywhere the injected container is used.

Injecting the IoC container seems like an easy way to accidentally turn your unit tests into integration tests. Imagine this, you come back to work on a class which you've injected the container. In this class, you add code to use the container to retrieve and use a new service object. It's much easier to forget to go back to your unit test and mock that new service object. Your test might even still pass if you forget to come back. You wouldn't have that problem if you injected the service object rather than resolved it out of the IoC. Your unit tests would fail immediately if you used constructor injection(which would be a good thing).

In my opinion, using facades in Laravel introduces the same baggage as injecting the IoC container. It's practically the same thing, if not worse. The application/IoC container is statically available on all facade classes. This service location is available everywhere. With Laravel, you don't have a choice. However, Laravel facades are great for new devs getting their feet wet with OOP in a solid framework. I can completely understand why Taylor included them. It's sexy for some people.

They tie you to Laravel

Recently there's been a lot of twitter/blog/reddit bantering about being more mindful of creating framework agnostic packages. Phil Sturgeon recently posted an article on his blog about ditching framework fanboy-ism and focusing more on interoperability among code bases. He ruffled some feathers but I agree with his main point. If you develop framework agnostic code, you and others are going to be able to use it when you work in another project. I don't think anyone will argue that that's not a good thing.

You probably don't have framework interoperability code as your primary focus when developing, but by using Laravel's facades you're immediately tying that code to Laravel.

There are some places, like controllers, that this argument is moot. You're most likely not going to share controllers. I'd still advocate ditching facades in your controllers just for the sake of establishing the habit. Establish this habit for your service objects! There's a far better chance you're going to like a service class you wrote and want to use that code again. It'll be much easier if you typehinted an interface into the constructor of that service object's class rather than have to refactor the facades out to be able to use it in framework X.

Okay, I'm sold. How do I do it?

Let's start with the default HomeController shipped with every Laravel install.

class HomeController extends BaseController 
{
        public function showWelcome()
        {
                return View::make('hello');
        }
}


Let's first inject the renderer. If we take a peek under the hood at the facade located at, project/vendor/laravel/framework/src/Illuminate/Support/Facades/View.php we can see the string view being returned from the getFacadeAccessor() method. This facade is pulling out the object from the IoC container with the key of view. With this information we can register a binding.

// project/bootstrap/start.php

/* --other code-- */

$app->bind('HomeController', function($app) {

    return new HomeController($app->make('view'));
});

return $app;


Now we have to update update our controller...but we don't actually know what in the world $app->make('view') returns. After a bit of searching you can see in the Illuminate\View\ViewServiceProvider::registerEnvironment() method the actual object is an instance of Illuminate\View\Environment. Let's modify the controller.

use Illuminate\View\Environment as View;

class HomeController extends BaseController 
{    
    protected $view;
    
    public function __construct(View $view)
    {
        $this->view = $view;
    }

    public function showWelcome()
    {
        return $this->view->make('hello');
    }
}


Note! We've aliased the class to View to be consistent with the facade. This will probably make people using facades more comfortable with your code.

This is already a heck of lot clearer to see what classes are being used. It will be much easier to tell if we're adhering to the Single Responsibility Principle.

Let's accommodate the Input facade for funzies.

This one is a little harder to track down. If you open up the Input.php facade file, you'll see request being returned. I found this binding in the project/vendor/laravel/framework/src/Illuminate/Foundation/Application.php file. You can see the request binding in the registerBaseBindings() method. We can add this to the controller like so:

use Illuminate\Http\Request as Input;
use Illuminate\View\Environment as View;

class HomeController extends BaseController 
{
    protected $input;

    protected $view;

    public function __construct(Input $input, View $view)
    {
        $this->input = $input;
        $this->view = $view;
    }

    public function showWelcome()
    {
        $test = $this->input->get('test');
        
        return $this->view->make('hello');
    }
}


Then update our binding.

// project/bootstrap/start.php

/* --other code-- */

$app->bind('HomeController', function($app) {

    return new HomeController($app->make('request'), $app->make('view'));
});

return $app;


Now if we go to /?test=123, $test will equal "123". Perfect.

Edit! This is an edit made after I originally posted the article. I hadn't looked at Laravel's facade documentation in a while. They have added a handy table for you to find out what the facades actually map to. You can find the Facade Class Reference here.

Stripping facades from service objects

You'll notice we didn't create any interfaces for the controller. Again, this is because we're not going to be sharing controllers across frameworks.

I would create my own interface if I were writing code that I, or others, could possibly be used in the future outside of Laravel. Take the following example.

use MyUserInterface as UserInterface;

class PasswordResetService
{
    protected $user;
   
    public function setUser(UserInterface $user)
    {
        $this->user = $user;
    }
    
    public function fire()
    {
        $email = $this->user->getEmail();
        $message = 'Follow the link: www.project.dev/reset/' . $this->user->getUniqueString();

        Queue::push('SendEmail', array('email' => $email, 'message' => $message));
    }
}


Because we're using the Queue facade, we've unnecessarily tied this service to Laravel. Let's fix that.

use MyUserInterface as UserInterface;
use MyQueueInterface as QueueInterface;

class PasswordResetService
{
    protected $queue;

    protected $user;

    public function __construct(QueueInterface $queue)
    {
        $this->queue = $queue;
    }

    public function setUser(UserInterface $user)
    {
        $this->user = $user;
    }

    public function fire()
    {
        $email = $this->user->getEmail();
        $message = 'Follow the link: www.project.dev/reset/' . $this->user->getUniqueString();

        $this->queue->push('SendEmail', array('email' => $email, 'message', $message));
    }
}


Here's what those new interfaces and class could look like.

interface MyUserInterface {

    public function getEmail();

    public function getUniqueString();
}

interface MyQueueInterface {
    
    public function push($service, array $data);
}

class MyQueueService implements MyQueueInterface
{
    public function push($service, array $data)
    {
        Queue::push($service, $data);
    }
}


We're basically just wrapping the facade. We won't use MyQueueService outside of Laravel. It's adapter code. Now we just need to bind it in the IoC container.

// project/bootstrap/start.php

/* --other code-- */

$app->bind('PasswordResetService', function($app) {

    return new PasswordResetService($app->make('MyQueueService'));
});

return $app;


This is a very simple example but we've completely removed Laravel from this service class. We could package our interfaces and service class up and use it in any other framework now. Awesome.

Get in the habit

Hopefully I've adequately illustrated the benefits of not using facades. Although Laravel's facades are super easy to use, injecting the actual dependencies could really pay off down the line. I think everyone, even Laravel users, will prosper if the use of facades gets phased out. Go forth and develop framework agnostic code by ditching facades!

Tags: PHP, Intermediate, Laravel

Using PHP Generators for Control Flow

As you may know from my last post covering Ember, I have become very interested in expanding my javascript skill set. I posted my 10 part Ember video series to /r/javascript and was glad to see it get some upvotes. I noticed a post about Koa.js sitting next to mine. Koa is touted as a next generation framework for node from the Express team. I have heard of Express but haven't done anything with it. Upon seeing there was something even newer, I was intrigued and decided to check it out.

What the heck is this voodoo?

I was really taken aback when I came to the Cascading section. The example showed a asterisk right in the middle of a closure definition and the use of a yield keyword.

// copy/pasted directly from Koa's docs
var koa = require('koa');
var app = koa();

// x-response-time
app.use(function *(next){
  var start = new Date;
  yield next;
  var ms = new Date - start;
  this.set('X-Response-Time', ms + 'ms');
});

// logger
app.use(function *(next){
  var start = new Date;
  yield next;
  var ms = new Date - start;
  console.log('%s %s - %s', this.method, this.url, ms);
});

// response
app.use(function *(){
  this.body = 'Hello World';
});

app.listen(3000);


I had never seen that before. Upon some further investigation I learned that they are generators. Generators allow you to do some really crazy iterations. You can stop the iteration and give the calling code a value by using the yield keyword. You can also send the generator data back in the middle of an iteration. They're pretty mind bottling at first glance. I was curious to know if php has generators and guess what, they're new in 5.5!

I encourage you to get slightly familiar with them before reading on!

Anthony Ferrara has great article on generators here.

SitePoint also has a pretty good post about them here.

A Wikipedia article about generators.

Re-purposing generators

After I got a handle on what generators are I went back to the Koa website to review what they were doing. It didn't looking like they were using them for iteration though. It looks like they're using them to pass control to another generator, where execution halts in the first generator and continues in the next generator, which the first generator is completely unaware of. Once there are no more generators to continue on, flow unwinds back to the yield line in each generator. Koa's using them for a sort of cascading middleware. Look at Koa's docs if what I said didn't make any sense.

I found this concept to be incredibly clever and interesting. I wonder if I could implement the same idea in php...

Mental Gymnastics

This turned out to be a really fun challenge. Man...programming has really warped my idea of fun. Surprisingly, I was able to achieve the same effect. It took me a little while to figure it out and I didn't cheat and look at Koa's source! I'm not even sure with my javascript skills it would've helped much anyway.

Right this way

Let me show you an example.

$obj = new \stdClass;
$obj->result = '';

$first = function() use ($obj) {
    $obj->result .= ' 1 ';
    yield ControlFlow::NEXT;
    $obj->result .= ' 2 ';
};

$second = function() use ($obj){
    $obj->result .= ' 3 ';
    yield ControlFlow::NEXT;
    $obj->result .= ' 4 ';
};

$third = function() use ($obj){
    $obj->result .= ' 5 ';
    return ControlFlow::NEXT;
};

$fourth = function() use ($obj){
    $obj->result .= ' 6 ';
    return ControlFlow::NEXT;
};

$flow = new ControlFlow;
$flow->queue($first()) //notice the parenthesis for generators
     ->queue($second())
     ->queue($third)
     ->queue($fourth);

$flow->run();

echo trim($obj->result); // '1 3 5 6 4 2'

My ControlFlow object accepts two object types in the queue() method, \Generator's and \Closure's. It will always execute each queued action when the run() method is called but the order of execution is dependent on the contents of each generator/closure.

In the above example, the flow occurs like so:

  1. execution starts in the $first generator
  2. ' 1 ' is appended to $obj->result
  3. the $first generator then attempts to stop it's execution and yield/pass control to an unknown piece of code
  4. the ControlFlow then passes control to the next generator/closure which happens to be $second
  5. ' 3 ' is appended
  6. the $second generator then attempts to stop it's execution and yield/pass control to an unknown piece of code
  7. the ControlFlow then passes control to the next generator/closure which happens to be $third
  8. ' 5 ' is appended
  9. the ControlFlow then passes control to the next generator/closure which happens to be $fourth
  10. ' 6 ' is appended
  11. the ControlFlow attempts to pass control to the next generator/closure but none is found so it starts to unwind
  12. control is then relinquished back to the last yield, which is in $second
  13. ' 4 ' is appended
  14. control is then relinquished back to the previous yield, which is in $first
  15. ' 2 ' is appended
  16. '1 3 5 6 4 2' is echoed

If the $third closure did not return ControlFlow::NEXT, execution would have gone like this(the difference starts on step 9):

  1. execution starts in the $first generator
  2. ' 1 ' is appended
  3. the $first generator then attempts to stop it's execution and yield/pass control to an unknown piece of code
  4. the ControlFlow then passes control to the next generator/closure which happens to be $second
  5. ' 3 ' is appended
  6. the $second generator then attempts to stop it's execution and yield/pass control to an unknown piece of code
  7. the ControlFlow then passes control to the next generator/closure which happens to be $third
  8. ' 5 ' is appended
  9. $third doesn't direct flow to another piece of code, so it starts to unwind
  10. control is then relinquished back to the last yield, which is in $second
  11. ' 4 ' is appended
  12. control is then relinquished back to the previous yield, which is in $first
  13. ' 2 ' is appended
  14. control is then passed to the next action it hasn't executed yet, $fourth
  15. ' 6 ' is appended
  16. '1 3 5 4 2 6' is echoed

As you can see, each action will always be executed, but their order is entirely dependent on the contents of the actions.

It's worth mentioning, in the first scenario, that if there was a $fifth generator action that looked like the others(append ' 7 ' , yield next, append ' 8 '), both ' 7 ' and ' 8 ' would be appended at the same time because it would be the last action in the queue. It would then start to unwind.

I showed my coworker my example and he likened it to using templates, which is a great analogy. You have a template that has a placeholder for other markup to be rendered into. That base template has no idea what's going to get rendered into to but as soon as that happens it can continue on and render the rest of its own markup. I'm applying this same principle to php code.

Is this useful?

I have no idea! It's a pretty neat trick though. It seems like it could be a really confusing way to do some sort of pub/sub event propagation considering that generators are not required to yield anything. They must have the yield keyword in them but it could be wrapped up in a an if-statement that may not allow the execution to get there. Generators are strange beasts.

I would love to see someone smarter than me take this idea and run with it. I would be very curious to see what you come up with!

ControlFlow

Here's my ControlFlow class. It should probably be named something like YoYo.

class ControlFlow
{
    const NEXT = 'NEXT';
 
    /**
     * @var array
     */
    protected $queued = [];
 
    /**
     * @var array
     */
    protected $initiated = [];
 
    /**
     * Queue an action
     *
     * @param \Closure|\Generator $action
     * @return $this
     * @throws \InvalidArgumentException
     */
    public function queue($action)
    {
        if ( ! $action instanceof \Closure && ! $action instanceof \Generator) {
            throw new \InvalidArgumentException('Queued action must be a \Closure or \Generator');
        }
 
        $this->queued[] = $action;

        return $this;
    }
 
    /**
     * Run all queued actions
     *
     * @return void
     */
    public function run()
    {
        foreach ($this->queued as $action) {
            $this->runAction($action);
        }
 
        //flush everything because generators can't be reopened
        $this->flush();
    }
 
    /**
     * Run a queued action
     *
     * @param \Closure|\Generator $action
     * @return void
     */
    private function runAction($action)
    {
        if (in_array($action, $this->initiated, true)) return;
 
        $this->initiated[] = $action;
 
        if ($action instanceof \Generator) {
            $this->runGenerator($action);
        } elseif ($action instanceof \Closure) {
            $this->runClosure($action);
        }
    }
 
    /**
     * Run a queued closure
     *
     * @param \Closure $closure
     * @return void
     */
    private function runClosure(\Closure $closure)
    {
        if ($closure() === self::NEXT) {
            $this->initiateNext();
        }
    }
 
    /**
     * Run a queued generator
     *
     * @param \Generator $generator
     * @return void
     */
    private function runGenerator(\Generator $generator)
    {
        foreach ($generator as $result) {
            if ($result === self::NEXT) {
                $this->initiateNext();
            }
        }
    }
 
    /**
     * Initiate the next action
     *
     * @return void
     */
    private function initiateNext()
    {
        $nextAction = current($this->queued);
        next($this->queued);
        $this->runAction($nextAction);
    }
 
    /**
     * Remove the actions
     *
     * @return void
     */
    public function flush()
    {
        $this->queued = [];
        $this->initiated = [];
    }
}

Tags: PHP

Ember CRM

It's been a while since I last posted and for good reason...I've decided I need to attempt to compliment my backend skills with some frontend skills! I've never enjoyed writing javascript. Mostly because I've only ever used jQuery to added a little pizzazz to my sites(ie. toggleClass() and ajax()). I didn't have any javascript code organization. It was all spaghetti.

Javascript Revolution

Currently javascript is getting an insane amount of attention. New things are popping up all over the place(or maybe I've just been sheltered under my php rock). There are all sorts of frontend javascript frameworks now: Backbone, Angular, Ember, CanJS. Combine one of those with Twitter Boostrap or Zurb's Foundation and you can create some pretty slick frontends without doing much work.

Javascript is even becoming popular for the backend with the advent of Node. Node has spurred Express, Meteor, Sails, and more. I've got to say, programming both the backend and frontend with the same language is pretty darn appealing, even if I hate the fact that javascript isn't class based.

Where I'll start

Considering all that, I figure it would do my career well to really start giving javascript more of my attention. So where in the world do I start? Well, Ember seems to be the new hotness and even though I don't know a lick of ruby or rails, having a contributor to both rails and jQuery on the core team, gives me a warm fuzzy feeling. I'll start with Ember!

Ignition

After a couple of days of trying to create something I realized one thing: Ember is hard. Ember does a ton of magic for you behind the scenes. As a noob, this was a hindrance to me. I couldn't distinguish what Ember was doing for me and what it expected me to do. It was also extremely difficult to wrap my head around what MV* means in Ember. It doesn't resemble MVC in the backend at all. Once I realized and understood that, it all started to click and I've grown to really enjoy developing the frontend with Ember.

Another frustration of learning Ember/Ember-Data was the lack of up-to-date resources. I would constantly find stackoverflow questions that were "answered" and the answer referred to a jsfiddle that referenced "ember-latest.js" and guess what...Ember's api had changed, rendering it useless. So many times I found myself wanting to ditch it and stick to backend dev, but no, I don't want to be the guy unwilling to adapt. I. Must. Persevere.

I set out to build a tiny CRM application and implement some features I know I'll run into when developing something for real. Some features like:

  • basic CRUD operations
  • various relationship types, including a polymorphic relationship
  • loading relationships asynchronously
  • modals
  • Select2 integration
  • data normalization, serialization
  • and more
After trying to soak up absolutely everything Ember(stackoverflow, blogs, digging through the docs, IRC) for a solid two weeks I finally found some enlightenment. I successfully built out my application and am delighted with the result.

I've recorded a 10 part video playlist of myself rebuilding the app so that you all may reap the benefits of my efforts. I know when I first set out to learn ember I got tired of being pointed to paid methods of learning the framework. This is me giving back for all of the help I've received on my quest. Enjoy.

Project Overview

Before we get started I think it makes the most sense to have a look at what we're going to build.


You can find all of the frontend source code in the repo. Each part has its own branch.

Part 1

Let's get to it. In this first episode we're going to cover:

  • project structure
  • libraries used
  • model definitions
  • route definitions


Part 2

Topics covered:

  • creating Route objects
  • retrieving models from the ember-data store/API
  • expected JSON format
  • displaying a list of models in a template
  • using a few handlebars helpers


Part 3

Topics covered:

  • creating a route that uses a dynamic segment
  • using handlebars partials
  • getting and displaying related models
  • sending actions from templates to controllers
  • using ember-data model flags
  • rolling back model changes
  • saving models


Part 4

Topics covered:

  • reviewing relationship JSON
  • creating a custom REST serializer


Part 5

Topics covered:

  • creating a route for new models
  • rendering a specific template from the route
  • what JSON to return when saving models
  • removing unused models
  • cleaning up unsaved model changes


Part 6

Topics covered:

  • hiding models based on properties
  • creating mixins for our controllers
  • handling backend errors
  • using Twitter Bootstrap's alerts


Part 7

Topics covered:

  • fixing a mixin bug
  • reviewing my error response JSON


Part 8

Topics covered:

  • implementing everything we've done for companies so far for people


Part 9

Topics covered:

  • fixing a dynamic model property bug
  • incorporating Select2 using a custom view
  • using meta data in our JSON
  • sending actions from a view


Part 10

Topics covered:


<

p>

Questions, comments?

I hope you've found this useful. It was a really fun exercise and it sparked my interest to dive deeper into the javsacript world.

I'd love to hear any questions or comments. As I said in the first video, I want to learn from you guys as well. Please tell me if I'm doing something wrong or I could be doing something better!

Help! One huge aspect I didn't touch on was pagination. I'm still lurking and trying to figure out the best way to handle it. I'd love to learn more about the preferred method of paginating requested models using the meta object, especially paginating related models. For instance, if I'm on the company route, viewing a company that has 10,000 tasks, how do you paginate through those?

If you have some ideas, please let me know! I'll append this post with the information.

Tags: Javascript, Ember, Ember-data