Eloquence is now 2.0

04 Dec 2015

Eloquence is an open source package that brings a wealth of additional features to the fantastic Eloquent library we all know and love. These features include:

  • True camelCase support for your model attributes
  • A count cache for related models
  • A sum cache for related models

Along with some…

API improvements

In 1.x, Eloquence introduced behaviours which were a way of extending Eloquent features across 2 or more models at once. The first of these behaviours was the Count Cache behaviour which allowed you to easily add the counting of related models together. For example, say a User is an author that writes Posts for a blog. By adding the Count Cache behaviour to the Post model, you could update a post_count column on the users table with the relevant post count whenever the user authored a new post, removed it, or edited it.

However, the API for how this was managed always irked me, despite it working:

1 Post::observe(new CountCacheObserver);

This utilised an Eloquent feature that allowed the library to create observers which you could then attach to the relevant models once they’d been configured for the required behaviour. Add to this that you needed to implement an interface, setup the config for the model.etc. In short, it was too many steps. In 2.x Eloquence does away with the need for observers, and instead includes the observing functionality within the trait itself. So now, instead of implementing the CountCache interface on your models, you now simply include the Countable trait, and implement the countCaches method as required (same as before).

This API is much cleaner and removes the additional step that was previously required. In addition, the new Summable behaviour now works in the same fashion, so it’s extremely easy to add both count and sum behaviour to a model:

 1 class Post extends Model
 2 {
 3     use Countable;
 4     use Summable;
 5     
 6     public function countCaches()
 7     {
 8         // Return count cache config
 9     }
10     
11     public function sumCaches()
12     {
13         // Return sum cache config
14     }
15 }

No more need for external observer classes! I think this is awesome :)

Along with the API improvements, I’ve also been able to extract shared functionality out of some traits - as both Countable and Summable have a bunch of features that are very similar. These now exist in the Cacheable trait, which is meant for internal use only.

Tagged:
comments powered by Disqus