emberjs/ember.js — pull request #4861 by tomdale (2014-05-13 16:08:13+00:00)
Title: [FEATURE services] Initial feature

This is an initial spike of the described in [this thread on the discussion forums](http://discuss.emberjs.com/t/services-a-rumination-on-introducing-a-new-role-into-the-ember-programming-model/4947).

The TL;DR is that both controllers and routes get a `services` hash that they can look up services on; it's very similar to the `controllers` hash on controllers and, indeed, is implemented very similarly.

To create a geolocation service, for example, just define an `Ember.Service` class like so:

```js
App.GeolocationService = Ember.Service.extend({
getPosition: function() {
return new Ember.RSVP.Promise(function(res, rej) {
if (!geolocation) {
rej(new Error("Geolocation is not available either in this browser or on this device."));
return;
}

geolocation.watchPosition(function(position) {
res(position);
});
});
}
});
```

If you're using `ember-cli`, just export an `Ember.Service` from `app/services/geolocation.js`.

Once that's done, you have access to your service in both routes and controllers:

```js
App.NearbyTweetsRoute = Ember.Route.extend({
model: function() {
var geolocation = this.get('services.geolocation'),
twitter = this.get('services.twitter');

return geolocation.currentLocation().then(function(lat, lng) {
return twitter.findNearbyTweets(lat, lng);
};
}
});
```

(Note that this deviates slightly from my original post on the forums; in order to avoid naming collisions, everything is namespaced under the `services` hash instead of being injected directly onto the route/controller.)

Tasks left to do before this should be shipped to master:

* [ ] If possible, share implementation of `services` hash generation across controllers/routes
* [ ] If possible, share more implementation between `services` hash and `controllers` hash
* [ ] Write more inline documentation and guides to explain how services fit in conceptually

I'm a little embarrassed at how small the actual implementation is. It feels like it's doing almost nothing, which is basically true. But I hope this can be a starting point for the community to start evolving on our shared understanding of what services are.