I am trying to structure a large laravel application.
Trying to figure out:
1) Where does business rules / domain rules objects go?
2) How does business rules objects looks like?
By business rules I mean rules like. Given an invoice has possible states [new, approved, completed]. Only invoices in the "approved" state can be emailed to a customer. This is a simplified example.
Since there are a lot of these rules and these rules change often (once or twice a year), I would like to have them in dedicated classes.
This blog post https://stitcher.io/blog/laravel-beyond-crud-01-domain-oriented-laravel provides an application structure similar to my desired application structure. See below.
app/Domain/Invoices/
├── Actions
├── QueryBuilders
├── Collections
├── DataTransferObjects
├── Events
├── Exceptions
├── Listeners
├── Models
├── Rules
└── States
I'm somewhat familiar with domain driven design "theory". I am looking for code examples, preferably in Laravel or PHP (other languages are also ok). If anyone can point me to a github/gitlab project with code examples that would be great as well.
First I'll provide an example, which will be explained below.
<?php
namespace App;
use RuntimeException;
class Invoice
{
private const STATUS_NEW = 'new';
private const STATUS_APPROVED = 'approved';
private const STATUS_COMPLETED = 'completed';
/** #var string */
private $status;
private function __construct(string $status)
{
$this->status = $status;
}
public function create(): self
{
return new self(self::STATUS_NEW);
}
public function approve(): void
{
if ($this->status !== self::STATUS_NEW) {
throw new RuntimeException('Unable to approve invoice, as it is not new');
}
$this->status = self::STATUS_APPROVED;
}
public function complete(): void
{
if ($this->status !== self::STATUS_APPROVED) {
throw new RuntimeException('Unable to complete invoice, as it is not new');
}
$this->status = self::STATUS_COMPLETED;
}
public function canBeSentToCustomer(): bool
{
return $this->status === self::STATUS_COMPLETED;
}
}
So there's a few ideas behind the code above:
The class and method names reflect the domain language. Example: somebody in sales will talk about approving an invoice, which translates to $invoice->approve()
The class is responsible for maintaining a valid state itself. Example: an invoice can't be completed if it's not approved yet
The code does not care about frameworks, databases, web requests, emails or html. All it should do is implement behavior without worrying about where the input comes from or output goes to.
Related
I know this is a really bad idea, but I ran out of ideas, so I'd like to hear some opinions about it.
I'm working on a PHP project which allows the development of addons so that other developers can add their own functions, not so different from thousands of other open-source projects:
root
└── addons
└── addon-a
└── addon-b
└── addon-c
I have to implement some changes to an already made addon (let's say Addon A) without changing the original files or using Composer PSR-4. Unfortunately, the original author did not follow good practices that would help to accomplish this task. Here's how the Addon A is:
Structure
addon-a
└── main.php
└── classes
└── Foo.php
└── Bar.php
addon-a/main.php
include_once __DIR__ . '/classes/Foo.php';
function run() {
echo AddonA\Classes\Foo::returnTwo();
}
addon-a/classes/Foo.php
namespace AddonA\Classes
use AddonA\OtherFolder\FooBar
abstract class Foo {
public static function returnTwo() {
return 2;
}
public static function returnFooBar() {
return new FooBar();
}
}
I need to override the returnTwo function and return another value. Without changing other files, the only way I was able to do it was through the class_alias method, copying the whole Foo class:
First, I created another addon and made it ran before the Addon A "run" function:
Structure
new-addon-a
└── main.php
└── classes
└── Foo.php
new-addon-a/main.php
function init() {
include_once __DIR__ . '/classes/Foo.php';
class_alias( 'NewAddonA\Classes\Foo', 'AddonA\Classes\Foo', true );
}
init();
new-addon-a/classes/Foo.php
namespace NewAddonA\Classes
use AddonA\OtherFolder\FooBar // No changes to the previous "uses."
abstract class Foo {
public static function returnTwo() {
return 3;
}
public static function returnBar() {
return new AddonA\Classes\Bar(); // Here I had to change because the namespace has changed
}
}
Now, when Addon A executes the function run, the AddonA\Classes\Foo::returnTwo will be my own class.
Well, as I said before, this is pretty ugly, and I would lose any update to the Foo code since I'm overriding the entire class. However, this was the only way I thought. Do you think it would be possible to use another method?
Thanks!
I'm working on a Symfony (2.7.4) website where some users have their own language resources for their own locales. For example, a user might have two locales (for example fr and en) and another user could also have one or all of these locales.
Each user has the ability to edit its own translations in a third party app, so translations are not shared between users.
I would like to be able to load the appropriate (YML or XLIFF) resources file when accessing a user's page, based on the locale (which is defined in the URL) and the user (could be its ID or anything that identifies it).
For example, when visiting user99.my-domain.ext/fr/ I'd like to add [base_directory]/user99/messages.fr.yml to the resources loaded by the Translator so it overrides the keys in the base messages.fr.yml.
I've tried to inject the Translator in my service, but I can only use it for reading translations, not adding any. What would be the best way to do that? Or is doing it in a service is too late? Maybe the Kernel is a better place?
Any help is appreciated!
Note: I'm using the YAML format in my examples, but any of the Symfony-known formats is eligible.
In order to "override" translations you should decorate the translator service. That way your own translator logic will be executed when trans() is called somewhere.
http://symfony.com/doc/current/components/dependency_injection/advanced.html#decorating-services
By decorating the service other bundles will also start using the logic you did describe above. You can inject the active user (eg. token_storage service) and some caching services (eg. https://github.com/doctrine/DoctrineCacheBundle) to make sure your user gets the right translations.
This isn't related to the request or hostname, your translation logic for the user should happen after the firewall / authorization logic was executed.
See Symfony's LoggingTranslator PR to find out how the decorator pattern was used to let the translator log missing translations: https://github.com/symfony/symfony/pull/10887/files
I chose to use a custom Twig filter, so I can decide when I want user specific translations and when I want generic ones.
Here's my extension (my users are in fact Domain instances):
<?php
// src/AppBundle/Twig/DomainTranslationExtension
namespace AppBundle\Twig;
use AppBundle\Document\Domain;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Translation\Loader\YamlFileLoader;
use Symfony\Component\Translation\Translator;
class DomainTranslationExtension extends \Twig_Extension {
/**
* #var ContainerInterface
*/
protected $container;
/**
* #var Translator
*/
protected $translator;
/**
* #var string
*/
protected $locale;
/**
* #var Domain
*/
protected $domain;
public function setContainer(ContainerInterface $container) {
$this->container = $container;
$this->locale = $this->container->get('request_stack')->getMasterRequest()->getLocale();
$domainService = $this->container->get('app.domain_service');
$this->domain = $domainService->getDomain();
// TODO: File loading error check
$this->translator = new Translator($this->locale);
$this->translator->addLoader('yaml', new YamlFileLoader());
$this->translator->addResource('yaml', 'path/to/domain-translations/' . $this->domain->getSlug() . '/messages.' . $this->locale . '.yml', $this->locale);
}
public function getFilters() {
return array(
new \Twig_SimpleFilter('transDomain', array($this, 'transDomain')),
);
}
public function transDomain($s) {
$trans = $this->translator->trans($s);
// Falling back to default translation if custom isn't available
if ($trans == $s) {
$trans = $this->container->get('translator')->trans($s);
}
return $trans;
}
public function getName() {
return 'app_translation_extension';
}
}
Declared like that in app/config/services.yml:
app.domain_service:
class: AppBundle\Services\DomainService
arguments: [ #request_stack, #doctrine_mongodb, #translation.loader ]
And used like that in a Twig file:
{{ 'my.translation.key'|transDomain }}
I hope this helps, thanks!
I have been researching so many times, asking experts on stackoverflow for the best practice, but I still could not find the solution, I might have got told the correct answer, but I didn't get it.
I always wanted to create a 'proper' MVC pattern to work on my projects, I have been researching for example this http://www.phpro.org/tutorials/Model-View-Controller-MVC.html but I got told that this is awful design, and I should not use the registery pattern anymore.
So I looked at teresko's answer, even though it's very old, can be seen here How should a model be structured in MVC? and I got the idea there, to use a global factory, which will create other factories
The idea I got from there, is to have a big factory, called ServiceFactory which will create instances of other factories like ModelFactory which will create instances of classes that are serving the model layer, and a ViewFactory, which will serve the view (Pretty useless at the moment I think).
But got something like this:
namespace library\application;
use library\application\exceptions\ClassNotFoundException;
use library\application\exceptions\PackageNotFoundException;
class ServiceFactory {
private $mapper;
private $package;
private $services = array();
public function __construct(DataMapper $mapper) {
$this->mapper = $mapper;
}
/**
* Setting a default package
* #param $package string Package path
* #throws exceptions\PackageNotFoundException
*/
public function setDefaultPackage($package) {
if (is_dir('library' . $package)) {
$this->package = 'library' . $package;
return;
}
throw new PackageNotFoundException("The package: " . $package . " was not found.");
}
/**
* #param $name string Class name
* #param null $constructor IF the class needs constructor parameters, use it.
* #return Factory
* #throws exceptions\ClassNotFoundException
*/
public function create($name, $constructor = null) {
$path = $this->package . "\\" . $name;
if (file_exists($path)) {
if ($constructor) {
return new $path($constructor);
}
return new $path;
}
throw new ClassNotFoundException("The requested class was not found: " . $path);
}
/**
* #param $name string Class name
* #param $object object Object to register
*/
public function register($name, $object) {
$this->services[$name] = $object;
}
/**
* #param $name string Class name
* #return Factory
*/
public function get($name) {
if (isset($this->services[$name])) {
return $this->services[$name];
}
return null;
}
}
This is awesome actually, but in my opinion, OO-wise, it's totally wrong, because it's not object-oriented friendly, since the returning object of S ServiceFactory::create() is anonymous, well fine, It's no longer anonymous, because the purpose of the class is to create instances of factories, sure, just added the interface of the factories in return.
But now the next problem, when I want to use the factories to create objects, that should not have the same interface, will cause problems to my IDE, since it doesn't know what is the object I am going to return, it can be Foo, can be Car and one day it can be HelloWorld.
So I always will have to declare a variable with the object when using it in the controller:
/**
* #var $items Items
* #var $categories CategoryModel
*/
$items = parent::getModelFactory()->create('Items');
$items->setDb(parent::getDatabase());
$categories = parent::getModelFactory()->create('Categories');
$categories->setDb(parent::getDatabase());
Now in one of Teresko's answer(s), it says the following rule: A controller can not create instances of the Model layer
So I assume he means like $foo = new Foo(); $foo->method($db); in the controller, but why not? how should a controller actually communicate the model layer?
The main purpose of me creating that god factory class, is to prevent doing new Object() in the controller class, but since it's calling the factory, which creates the instance, it's still considered as I am creating an instance of a model layer in a controller (I think).
I also could cache objects, using ServiceFactory::register() method, but that doesn't change the situation.
So is the ServiceFactory and factories idea fine ? What is the correct way communcating between the controller and the model layer?
Not really, but there aren't any rules in how to implement MVC as long as you have M V C clearly defined and C acts as a coordinator for M and V.
A factory of factories is clearly over engineering, if you don't need it don't implement it. What you need to understand in order to be easy for you to apply MVC is that 1) MVC is part of the UI layer and 2) Model refers to the bits of other layers (like, for example, Business, Persistence or Application/Service) which are used by the UI.
The controller always communicates directly to the Model, but depending on the use case, the Model means that bits of layers mentioned above. In a 'normal' app, it usually is like this: the controller uses an application service (the MVC Model) to update the business model. The service should be injected in the controller constructor.
For querying purposes, the controller can use a "querying service" or a query only repository so that it won't contain persistence logic (like writing sql). It still the same approach like above, only this time, the Model represents Persistence bits.
So you see, the Mvc Model is actually a facade for other layers used by UI and you want the controller not to have direct access to the business layer for example, because the controller should really just coordinate what model to change and what view model to be rendered. In contrast, an application service will implement an application use case using business/persistence objects.
Everything is really about respecting Separation of Concerns and Single Responsibility Principle
I want to make an API first application in Laravel. I don't know what is the best approach to do this, I will explain what I am trying to do, but please feel free to give answers how to do this in a different way.
I don't want all my frontend to be written in javascript and parse the JSON output of the API with angular.js or something similar. I want my Laravel application to produce the HTML views. I am trying to go down the road of having two controllers one on for the API and one for the web. For the show User action my routes.php looks like this:
# the web controller
Route::controller('user', 'WebUserController');
# the api controller
Route::group(array('prefix' => 'api'), function() {
Route::resource('user', 'UserController');
});
So /user will take me to WebUserController and /api/user will take me to the UserController. Now I want to put all my logic in the API UserController, and call its actions from the WebUserController. Here is the code for both of them:
class UserController extends BaseController
{
public function show($id)
{
$user = User::find($id);
return Response::json(array('success'=>true,'user'=>$user->toArray()));
}
}
class WebUserController extends UserController
{
public function getView($id)
{
# call the show method of the API's User Controller
$response = $this->show($id);
return View::make('user.view')->with('data', $response->getData());
}
}
In the WebUserController I am able to get the json content of the response with getData(), but I am not able to get the headers and status code (they are protected properties of Illuminate\Http\JsonResponse).
I think that my approach might not be the best, so I am open to suggestions how to make this app.
EDIT: The question how to get the headers and status of the response has been answered by Drew Lewis, but I still think that there might be a better way how to design this
You should utilize the Repository / Gateway design pattern: please see the answers here.
For example, when dealing with the User model, first create a User Repository. The only responsibility of the user repository is to communicate with the database (performing CRUD operations). This User Repository extends a common base repository and implements an interface containing all methods you require:
class EloquentUserRepository extends BaseRepository implements UserRepository
{
public function __construct(User $user) {
$this->user = $user;
}
public function all() {
return $this->user->all();
}
public function get($id){}
public function create(array $data){}
public function update(array $data){}
public function delete($id){}
// Any other methods you need go here (getRecent, deleteWhere, etc)
}
Then, create a service provider, which binds your user repository interface to your eloquent user repository. Whenever you require the user repository (by resolving it through the IoC container or injecting the dependency in the constructor), Laravel automatically gives you an instance of the Eloquent user repository you just created. This is so that, if you change ORMs to something other than eloquent, you can simply change this service provider and no other changes to your codebase are required:
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider {
public function register() {
$this->app->bind(
'lib\Repositories\UserRepository', // Assuming you used these
'lib\Repositories\EloquentUserRepository' // namespaces
);
}
}
Next, create a User Gateway, who's purpose is to talk to any number of repositories and perform any business logic of your application:
use lib\Repositories\UserRepository;
class UserGateway {
protected $userRepository;
public function __construct(UserRepository $userRepository) {
$this->userRepository = $userRepository;
}
public function createUser(array $input)
{
// perform any sort of validation first
return $this->userRepository->create($input);
}
}
Finally, create your User web controller. This controller talks to your User Gateway:
class UserController extends BaseController
{
public function __construct(UserGatway $userGateway)
{
$this->userGateway = $userGateway;
}
public function create()
{
$user = $this->userGateway->createUser(Input::all());
}
}
By structuring the design of your application in this way, you get several benefits: you achieve a very clear separation of concerns, since your application will be adhering to the Single Responsibility Principle (by separating your business logic from your database logic) . This enables you to perform unit and integration testing in a much easier manner, makes your controllers as slim as possible, as well as allowing you to easily swap out Eloquent for any other database if you desire in the future.
For example, if changing from Eloquent to Mongo, the only things you need to change are the service provider binding as well as creating a MongoUserRepository which implements the UserRepository interface. This is because the repository is the only thing talking to your database - it has no knowledge of anything else. Therefore, the new MongoUserRepository might look something like:
class MongoUserRepository extends BaseRepository implements UserRepository
{
public function __construct(MongoUser $user) {
$this->user = $user;
}
public function all() {
// Retrieve all users from the mongo db
}
...
}
And the service provider will now bind the UserRepository interface to the new MongoUserRepository:
$this->app->bind(
'lib\Repositories\UserRepository',
'lib\Repositories\MongoUserRepository'
);
Throughout all your gateways you have been referencing the UserRepository, so by making this change you're essentially telling Laravel to use the new MongoUserRepository instead of the older Eloquent one. No other changes are required.
You should be use Repository for this design.
Example -
//UserRepository Class
class UserRepository {
public function getById($id)
{
return User::find($id);
}
}
// WebUser Controller
class WebUserController extends BaseController {
protected $user;
public function __construct(UserRepository $user)
{
$this->user = $user;
}
public function show($id)
{
return View::make('user.view')->with('data', $this->user->getById($id));
}
}
// APIUser Controller
class UserController extends BaseController {
protected $user;
public function __construct(UserRepository $user)
{
$this->user = $user;
}
public function show($id)
{
$data =>$this->user->getById($id);
return Response::json(array('success'=>true,'user'= $data->toArray()));
}
}
Checkout Laravel's RESTful controllers:
http://laravel.com/docs/controllers#restful-controllers
Their docs do a pretty good job.
But even better is this tutorial:
http://code.tutsplus.com/tutorials/laravel-4-a-start-at-a-restful-api-updated--net-29785
This is a video by Jeffrey Way he is one of the better Laravel developers. In this tutorial he is connecting a BackboneJS application to a RESTful service that he sets up in Laravel. It doesn't get any better then this. I can write you a lot of boilerplate, but just learn it by watching a nice video and having a coffee. ;)
https://www.youtube.com/watch?v=uykzCfu1RiQ
I have a response to the problem you are having with the Response.
You can get the headers, status code and data from the Response.
// your data
$response->getData();
// the status code of the Response
$response->getStatusCode();
// array of headers
$response->headers->all();
// array of headers with preserved case
$response->headers->allPreserveCase();
$response->headers is a Symfony\Component\HttpFoundation\ResponseHeaderBag which inherits from Symfony\Component\HttpFoundation\HeaderBag
I would also recommend using a repository.
Attempting to call one controller from another would be falling into a pattern called HMVC (Hierarchical model–view–controller).
This means that your entire application relies on lower modules.
In this case, your API would serve as a repository for your data (which isn't the worst thing in the world at first).
However, when you then modify the structure of how data is returned in your API, everything else relying on it would have to know how to respond.
Say you wanted to have authorization checks to see if a logged in user should be able to see the details of a returned user and there was an error.
In the API, you would return a Response object with a 403 forbidden code and some meta data.
Your HTML controller would have to know how to handle this.
Contrast this to a repository which could throw an exception.
public function findById ($id)
{
$user = User::findOrFail($id);
if (Auth::user->hasAccessTo($user)) {
return $user;
} else {
throw new UnauthorizedAccessException('you do not have sufficient access to this resource');
}
}
And your API controller would look more like this:
public function show($id)
{
try {
return $this->user->findById($id);
} catch (UnauthorizedAccessException $e) {
$message = $e->getMessage();
return Response::json('403', ['meta' => ['message' => $message]]));
}
}
Your HTML controller would then look like this:
public function show($id)
{
try {
$user = $this->user->findById($id);
} catch (UnauthorizedAccessException $e) {
Session::flash('error', $e->getMessage());
// Redirect wherever you would like
return Response::redirect('/');
}
}
This gives you very reusable code and let's you change your controller implementations independently without worry of changing the other's behavior.
I wrote more on how to implement the repository pattern in this post: you can ignore the interface and skip right to the implementations if you would like.
I have a view that shows a line of 10 numbers in a table (it's a dashboard of stats).
They are information on sales today, tomorrow, the day after etc, split by some different states.
Currently I have some code like:
class Transaction extends Eloquent {
// other methods that aren't relevant
public function scopeConfirmed($query)
{
return $query->where('status', '=', 'Confirmed');
}
public function scopeBooked($query)
{
return $query->where('status', '<>', 'Cancelled');
}
public function scopeDaysAhead($query, $days)
{
$start = \Carbon\Carbon::now()->addDays($days)->toDateString();
$end = \Carbon\Carbon::now()->addDays($days+1)->toDateString();
return $query->where('date', '>=', $start)->where('date', '<', $end);
}
// few other similar scopes
}
Then in my view I have:
(Simplified)
<td>
{{Transaction::->daysAhead(0)
->booked()
->count()}}
</td>
<td>
{{Transaction::->daysAhead(0)
->confirmed()
->count()}}
</td>
<td>
{{Transaction::->daysAhead(1)
->confirmed()
->count()}}
</td>
<td>
{{Transaction::->daysAhead(2)
->confirmed()
->count()}}
</td>
So, I'm dealing with Eloquent calls in my view. In reality there are scopes by sales person and by location, so there are 10-20 values being shown.
I can move this back into the Controller by having a very fat load of with statements, or of course put it into an Array in the controller, but that doesn't seem to help massively.
What is the best way to deal with this?
Keep your views as logic less as possible, don't clutter your controllers with logic either. This would, to most people mean stuffing all the logic into models. Again this isn't an approach that helps with writing re-usable and more importantly testable code.
Laravel's IoC container and dependency injection is incredibly powerful and should be utilised to structure your applications in a testable way.
I can understand why you want to pass the query object around as well, this is something I used to do in my models. It seems to make sense however it quickly becomes apparent that creating a rigid query builder using a powerful query builder will create some quantity of wet code.
My suggestion would be to keep your model as slim as possible, use them to create relationships, set eloquent properties, validation rule arrays and nothing more. Abstract all logic into a repository based on an interface. Why? Well, the interface can be bound through the IoC to the class it should resolve to meaning that it can be dependency injected and swapped out easily (Mockery for example) whilst maintaining structural integrity in any replacements you may want to build (a Mongo, CouchDB etc. implementation for example).
namespace Repositories;
interface TransactionInterface {
public function findAll();
public function findById($id);
public function findByDaysAhead($start = 0, $end = 1)
}
And for the repository
namespace Repositories;
use Transaction;
class TransactionEloquent implements TransactionInterface {
public function findAll()
{
return Transaction::all();
}
public function findById($id)
{
$transaction = Transaction::find($id);
if ( ! $transaction )
{
throw new Exception("Transaction not found");
}
return $transaction;
}
public function findByDaysAhead($start = 0 , $end = 1)
{
// Create one query to return all the data you need
}
}
You can then bind this repository either in a new custom ServiceProvider or in your routes.php.
App::bind('Repositories\TransactionInterface', 'Repositories\TransactionEloquent');
Now you can dependency inject into your controller the interface that will resolve to your eloquent implementation. If you write a different repository implementation you can simply rebind it to the interface meaning it'll be used wherever the interface is injected (Mockery classes for example)
class ApplicationController extends BaseController {
public function __construct(Repositories\TransactionInterface $interface)
{
$this->repo = $interface;
}
public function getIndex()
{
return View::make('index', array('transactions' => $this->repo->findAll());
}
}
In your view you would only require a simple loop over your data and outputting, no logic required.
Obviously you can put as much logic as you like in the repository and as you can see your controllers, models and views fulfil only the responsibility they are intended for (OOPS Single Responsibility Principle)
This is a very short answer to what is a very complex question. I hope this guides you someway to writing testable and reusable modular code in Laravel.
Some 'light' reading
Laravel 4's IoC container
Laravel 4's Service Providers
NetTuts article on building L4 and Backbone apps Ignore the backbone part, this is a great walkthrough on L4's IoC bindings.
Where to place files etc.
Following PSR-0 specifications I would end up with a structure like this
- app
- {name of app}
- Repositories
* TransactionInterface.php
* TransactionEloquent.php
The namespaces for these two files would now be namespace {name of app}\Repositories
In composer you can add this to the autoload object :
"psr-0": {
"{name of app}" : "app/"
}
This will add all PSR-0 compatible namespaces to the autoloader, when you make changes you can use
composer dump-autoload
to rebuild the autoloader and include your new files (not always required but is better and faster than composer update constantly).
How many repositories?
I usually end up with 1+ repositories per model. For example I have a backbone collection of models and individual models in the front end.
Using Backbone.sync(param, collection) would always utilise a repo that handles input as an array of models. Where as Backbone.sync(param, model) would utilise a repo that handled a single model being sent. I would also have two Laravel resource controllers to handle this as well.
Service Providers
I place these in my application folders route, my app is called "MFL" in this instance
- MFL
- Repositories
- MFLServiceProvider.php
I add this to my service providers array in config\app.php
namespace MFL;
use Illuminate\Support\ServiceProvider;
class MFLServiceProvider extends ServiceProvider {
public function register()
{
// Register bindings here, don't use other service providers here
// you can't be sure they are loaded as of yet
$this->app->bind('MFL\Repositories\TransactionInterface', 'MFL\Repositories\TransactionEloquent');
}
public function boot()
{
// Do anything else here with assurance all service providers are
// fully loaded and the application is ready
}
}
Using this method, you don't pollute routes.php with IoC bindings and you can logically partition all your code into services. This is my preferred method for the latter reason.
There is a 3rd option in view composers. At the most basic level these are included in routes.php but I like to break them out by view path so composers/transactions.php would handle all the views in views/transactions like 'transactions.dashboard'. Given that as a view then the composer would be...
View::composer('transactions.dashboard', function ($view)
{
$view->day0_count = Transaction::->daysAhead(0)
->booked()
->count();
}
$day0_count is now available in the view.
<td>{{ $day0_count }}</td>